Technical Documentation: ranaroussi/yfinance
โน๏ธ Provenance: Multi-Tier Ingestion ยท CodeWiki Reference
Overview (`README.md`)
Download market data from Yahoo! Finance's API
yfinance offers a Pythonic way to fetch financial & market data from Yahoo!โ finance.
[!IMPORTANT]
Yahoo!, Y!Finance, and Yahoo! finance are registered trademarks of Yahoo, Inc.yfinance is not affiliated, endorsed, or vetted by Yahoo, Inc. It's an open-source tool that uses Yahoo's publicly available APIs, and is intended for research and educational purposes.
You should refer to Yahoo!'s terms of use (here, here, and here) **for details on your rights to use the actual data downloaded.
Remember - the Yahoo! finance API is intended for personal use only.**
[!TIP]
THE NEW DOCUMENTATION WEBSITE IS NOW LIVE! ๐ค
Main components
Ticker: single ticker dataTickers: multiple tickers' datadownload: download market data for multiple tickersMarket: get information about a marketWebSocketandAsyncWebSocket: live streaming dataSearch: quotes and news from searchSectorandIndustry: sector and industry informationEquityQueryandScreener: build query to screen market
Installation
Install yfinance from PYPI using pip:
$ pip install yfinanceTo install without curl_cffi for requests fallback, see Advanced โธ Installation.
[yfinance relies on the community to investigate bugs and contribute code. Here's how you can help.](https://github.com/ranaroussi/yfinance/blob/main/CONTRIBUTING.md)
Legal Stuff
yfinance is distributed under the Apache Software License. See
the LICENSE.txt file in the release for details.
AGAIN - yfinance is not affiliated, endorsed, or vetted by Yahoo, Inc. It's
an open-source tool that uses Yahoo's publicly available APIs, and is
intended for research and educational purposes. You should refer to Yahoo!'s terms of use
(here,
here, and
here) for
details on your rights to use the actual data downloaded.
P.S.
Please drop me a note with any feedback you have.
Ran Aroussi
Doc Source Index (`doc/source/index.rst`)
yfinance documentation
Download Market Data from Yahoo! Finance's API
.. admonition:: IMPORTANT LEGAL DISCLAIMER
Yahoo!, Y!Finance, and Yahoo! finance are registered trademarks of Yahoo, Inc.
yfinance is not affiliated, endorsed, or vetted by Yahoo, Inc. It's
an open-source tool that uses Yahoo's publicly available APIs, and is
intended for research and educational purposes.
You should refer to Yahoo!'s terms of use
(here <https://policies.yahoo.com/us/en/yahoo/terms/product-atos/apiforydn/index.htm>),
(here <https://legal.yahoo.com/us/en/yahoo/terms/otos/index.html>),
and (here <https://policies.yahoo.com/us/en/yahoo/terms/index.htm>__)
for details on your rights to use the actual data downloaded.
Remember - the Yahoo! finance API is intended for personal use only.
Install
.. code-block:: bash
$ pip install yfinanceQuick start
Showing a small sample of yfinance API, the full API is much bigger and covered in :doc:reference/index.
.. code-block:: python
import yfinance as yf
dat = yf.Ticker("MSFT")
One ticker symbol
.. code-block:: python
dat = yf.Ticker("MSFT")
dat.info
dat.calendar
dat.analyst_price_targets
dat.quarterly_income_stmt
dat.history(period='1mo')
dat.option_chain(dat.options[0]).calls
Multiple ticker symbols
.. code-block:: python
tickers = yf.Tickers('MSFT AAPL GOOG')
tickers.tickers['MSFT'].info
yf.download(['MSFT', 'AAPL', 'GOOG'], period='1mo')
Funds
.. code-block:: python
spy = yf.Ticker('SPY').funds_data
spy.description
spy.top_holdings
.. toctree::
:maxdepth: 1
:titlesonly:
advanced/index
reference/index
development/index
Doc Source Advanced Caching (`doc/source/advanced/caching.rst`)
Caching
Persistent Cache
To reduce requests to Yahoo, yfinance stores some data locally: timezones to localize dates, and cookies. Cache location is:
- Windows = C:/Users//AppData/Local/py-yfinance
- Linux = /home//.cache/py-yfinance
- MacOS = /Users//Library/Caches/py-yfinance
You can direct cache to use a different location with :attr:set_tz_cache_location <yfinance.set_tz_cache_location>:
.. code-block:: python
import yfinance as yf
yf.set_tz_cache_location("custom/cache/location")Doc Source Advanced Config (`doc/source/advanced/config.rst`)
Config
yfinance has a new global config for sharing common values:
.. code-block:: python
import yfinance as yf
yf.config
{
"network": {
"proxy": null,
"retries": 0
},
"debug": {
"hide_exceptions": true,
"logging": false
}
}
yf.config.network
{
"proxy": null,
"retries": 0
}
Network
proxy - Set proxy for all yfinance data fetches.
.. code-block:: python
yf.config.network.proxy = "PROXY_SERVER"
retries - Configure automatic retry for transient network errors. The retry mechanism uses exponential backoff (1s, 2s, 4s...).
.. code-block:: python
yf.config.network.retries = 2
Debug
hide_exceptions - Set to
Falseto stop yfinance hiding exceptions... code-block:: python
yf.config.debug.hide_exceptions = False
logging - Set to
Trueto enable verbose debug logging... code-block:: python
yf.config.debug.logging = True
Locale
Localized fields (longName, shortName, ...) followyf.config.locale. The default is en-US / US. Switch the Yahoo
locale once at session start and every subsequent v7 / v10 endpoint call
(Ticker.info, Ticker.fast_info, Ticker.calendar,earnings_dates, ...) inherits it:
.. code-block:: python
import yfinance as yf
yf.config.locale.lang = "zh-Hant-HK"
yf.config.locale.region = "HK"
yf.Ticker("1810.HK").info["longName"] # โ 'ๅฐ็ฑณ้ๅ๏ผ๏ผท'
yf.config.locale.lang = "ja-JP"
yf.config.locale.region = "JP"
yf.Ticker("7203.T").info["longName"] # โ 'ใใจใฟ่ชๅ่ป'
Yahoo only returns translated values for tickers natively listed in that
locale; Ticker("AAPL") keeps returning "Apple Inc." underja-JP.
Doc Source Advanced Index (`doc/source/advanced/index.rst`)
======== Advanced
.. toctree::
:maxdepth: 2
install
logging
config
caching
multi_level_columns
price_repair
Doc Source Advanced Install (`doc/source/advanced/install.rst`)
Installation
To install without curl_cffi for requests fallback:
.. code-block:: bash
curl -fsSL https://raw.githubusercontent.com/ranaroussi/yfinance/main/requirements.txt | grep -vi '^curl_cffi' | pip install -r /dev/stdin
pip install --no-deps yfinanceDoc Source Advanced Logging (`doc/source/advanced/logging.rst`)
Logging
yfinance uses the logging module to handle messages. By default, only errors are logged.
If debugging, you can switch to debug mode with custom formatting using:
.. code-block:: python
import yfinance as yf
yf.config.debug.logging = True
Doc Source Advanced Multi Level Columns (`doc/source/advanced/multi_level_columns.rst`)
Multi-Level Column Index
The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance? <https://stackoverflow.com/questions/63107801>_
yfinancereturns apandas.DataFramewith multi-level column names, with a level for the ticker and a level for the stock price data
The answer discusses:
- How to correctly read the multi-level columns after saving the dataframe to a csv with
pandas.DataFrame.to_csv - How to download single or multiple tickers into a single dataframe with single level column names and a ticker column
Doc Source Advanced Price Repair (`doc/source/advanced/price_repair.rst`)
Price Repair
The new argument repair=True in history() and download() will attempt to fix a variety of price errors caused by Yahoo. Only US market data appears perfect, I guess Yahoo doesn't care much about rest of world?
The returned table will have a new column Repaired? that specifies if row was repaired.
This can also repair currency mixups, so check Ticker.history_metadata['currency'] after for true currency. Not Ticker.info.
Price repair
Missing dividend adjustment
If dividend in data but preceding Adj Close = Close, then manually apply dividend-adjustment to Adj Close.
Note: Repaired? is NOT set to True because fix only changes Adj Close
.. figure:: /_static/images/repair-prices-missing-div-adjust.png
:alt: 8TRA.DE: repair missing dividend adjustment
:width: 80%
:align: left
8TRA.DE
.. container:: clearer
..
Missing split adjustment
If stock split in data but preceding price data is not adjusted, then manually apply stock split.
Requires date range include 1 day after stock split for calibration - sometimes Yahoo fails to adjust prices on stock split day.
.. figure:: /_static/images/repair-prices-missing-split-adjust.png
:alt: MOB.ST: repair missing split adjustment
:width: 80%
:align: left
MOB.ST
.. container:: clearer
..
Missing data
If price data is clearly missing or corrupt, then reconstructed using smaller interval e.g. 1h to fix 1d data.
.. figure:: /_static/images/repair-prices-missing-row.png
:alt: 1COV.DE: repair missing row
:width: 80%
:align: left
1COV.DE missing row
.. container:: clearer
..
.. figure:: /_static/images/repair-prices-missing-volume-intraday.png
:alt: 1COV.DE: repair missing Volume, but intraday price changed
:width: 80%
:align: left
1COV.DE missing Volume, but intraday price changed
.. container:: clearer
..
.. figure:: /_static/images/repair-prices-missing-volume-daily.png
:alt: 0316.HK: repair missing Volume, but daily price changed
:width: 80%
:align: left
0316.HK missing Volume, but daily price changed
.. container:: clearer
..
100x errors
Sometimes Yahoo mixes up currencies e.g. $/cents or ยฃ/pence. So some prices are 100x wrong.
Sometimes they are spread randomly through data - these detected with scipy module.
Other times they are in a block, because Yahoo decided one day to permanently switch currency.
.. figure:: /_static/images/repair-prices-100x.png
:alt: AET.L: repair 100x
:width: 80%
:align: left
AET.L
Price reconstruction - algorithm notes
Spam minimised by grouping fetches. Tries to be aware of data limits e.g. 1h cannot be fetched beyond 2 years.
If Yahoo eventually does fix the bad data that required reconstruction, you will see it's slightly different to reconstructed prices and volume often significantly different. Best I can do, and beats missing data.
Dividend repair (new)
Fix errors in dividends:
- adjustment missing or 100x too small/big for the dividend
- duplicate dividend (within 7 days)
- dividend 100x too big/small for the ex-dividend price drop
- ex-div date wrong (price drop is few days/weeks after)
- NEW: capital gains double-counted
Most errors I've seen are on London stock exchange (ยฃ/pence mixup), but no exchange is safe.
IMPORTANT - false positives
Because fixing (3) relies on price action, there is a chance of a "false positive" (FP) - thinking an error exists when data is good.
FP rate increases with longer intervals, so only 1d intervals are repaired. If you request repair on multiday intervals (weekly etc), then: 1d is fetched from Yahoo, repaired, then resampled - this has nice side-effect of solving Yahoo's flawed way of div-adjusting multiday intervals.
FP rate on 1d is tiny. They tend to happen with tiny dividends e.g. 0.5%, mistaking normal price volatility for an ex-div drop 100x bigger than the dividend, causing repair of the "too small" dividend (repair logic already tries to account for normal volatility by subtracting median). Either accept the risk, or fetch 6-12 months of prices with at least 2 dividends - then can analyse the dividends together to identify false positives.
Adjustment missing
1398.HK
.. code-block:: text
ORIGINAL:
Close Adj Close Dividends 2024-07-08 00:00:00+08:00 4.33 4.33 0.335715
2024-07-04 00:00:00+08:00 4.83 4.83 0.000000
.. code-block:: text
REPAIRED:
Close Adj Close Dividends 2024-07-08 00:00:00+08:00 4.33 4.330000 0.335715
2024-07-04 00:00:00+08:00 4.83 4.494285 0.000000
Adjustment too small
3IN.L
.. code-block:: text
ORIGINAL:
Close Adj Close Dividends 2024-06-13 00:00:00+01:00 3.185 3.185000 0.05950
2024-06-12 00:00:00+01:00 3.270 3.269405 0.00000
.. code-block:: text
REPAIRED:
Close Adj Close Dividends 2024-06-13 00:00:00+01:00 3.185 3.185000 0.05950
2024-06-12 00:00:00+01:00 3.270 3.210500 0.00000
Duplicate (within 7 days)
ALC.SW
.. code-block:: text
ORIGINAL:
Close Adj Close Dividends 2023-05-10 00:00:00+02:00 70.580002 70.352142 0.21
2023-05-09 00:00:00+02:00 65.739998 65.318443 0.21
2023-05-08 00:00:00+02:00 66.379997 65.745682 0.00
.. code-block:: text
REPAIRED:
Close Adj Close Dividends 2023-05-10 00:00:00+02:00 70.580002 70.352142 0.00
2023-05-09 00:00:00+02:00 65.739998 65.527764 0.21
2023-05-08 00:00:00+02:00 66.379997 65.956371 0.00
Dividend too big
HLCL.L
.. code-block:: text
ORIGINAL:
Close Adj Close Dividends 2024-06-27 00:00:00+01:00 2.360 2.3600 1.78
2024-06-26 00:00:00+01:00 2.375 2.3572 0.00
REPAIRED:
Close Adj Close Dividends 2024-06-27 00:00:00+01:00 2.360 2.3600 0.0178
2024-06-26 00:00:00+01:00 2.375 2.3572 0.0000
Dividend & adjust too big
LTI.L
.. code-block:: text
ORIGINAL:
Close Adj Close Adj Dividends 2024-08-08 00:00:00+01:00 768.0 768.0 1.0000 5150.0
2024-08-07 00:00:00+01:00 819.0 -4331.0 -5.2882 0.0
REPAIRED:
Close Adj Close Adj Dividends 2024-08-08 00:00:00+01:00 768.0 768.0 1.0000 51.5
2024-08-07 00:00:00+01:00 819.0 767.5 0.9371 0.0
Dividend too small
BVT.L
.. code-block:: text
ORIGINAL:
Close Adj Close Adj Dividends 2022-02-03 00:00:00+00:00 0.7534 0.675197 0.8962 0.00001
2022-02-01 00:00:00+00:00 0.7844 0.702970 0.8962 0.00000
.. code-block:: text
REPAIRED:
Close Adj Close Adj Dividends 2022-02-03 00:00:00+00:00 0.7534 0.675197 0.8962 0.001
2022-02-01 00:00:00+00:00 0.7844 0.702075 0.8950 0.000
Adjusted 2x on day before
clue: Close < Low
2020.OL
.. code-block:: text
ORIGINAL:
Low Close Adj Close Dividends 2023-12-21 00:00:00+01:00 120.199997 121.099998 118.868782 0.18
2023-12-20 00:00:00+01:00 122.000000 121.900002 119.477371 0.00
.. code-block:: text
REPAIRED:
Low Close Adj Close Dividends 2023-12-21 00:00:00+01:00 120.199997 121.099998 118.868782 0.18
2023-12-20 00:00:00+01:00 122.000000 122.080002 119.654045 0.00
ex-div date wrong
TETY.ST
.. code-block:: text
ORIGINAL:
Close Adj Close Dividends 2022-06-22 00:00:00+02:00 66.699997 60.085415 0.0
2022-06-21 00:00:00+02:00 71.599998 64.499489 0.0
2022-06-20 00:00:00+02:00 71.800003 64.679657 5.0
2022-06-17 00:00:00+02:00 71.000000 59.454838 0.0
.. code-block:: text
REPAIRED:
Close Adj Close Dividends 2022-06-22 00:00:00+02:00 66.699997 60.085415 5.0
2022-06-21 00:00:00+02:00 71.599998 60.007881 0.0
2022-06-20 00:00:00+02:00 71.800003 60.175503 0.0
2022-06-17 00:00:00+02:00 71.000000 59.505021 0.0
Capital-gains double-counted
Clue: price drop matches dividend better than dividend+capital gains.
DODFX
.. code-block:: text
ORIGINAL:
Close Adj Close Dividends Capital Gains Date
2025-12-18 00:00:00-05:00 16.219999 16.219999 0.837 0.417
2025-12-17 00:00:00-05:00 16.920000 15.665999 0.000 0.000
.. code-block:: text
REPAIRED:
Close Adj Close Dividends Capital Gains Date
2025-12-18 00:00:00-05:00 16.219999 16.219999 0.42 0.417
2025-12-17 00:00:00-05:00 16.920000 16.083000 0.00 0.000
Doc Source Development Code (`doc/source/development/code.rst`)
Code
To support rapid development without breaking stable versions, this project uses a two-layer branch model:
.. image:: assets/branches.png
:alt: Branching Model
Inspiration <https://miro.medium.com/max/700/1*2YagIpX6LuauC3ASpwHekg.png>_
- dev: New features and some bug fixes are merged here. This branch allows collective testing, conflict resolution, and further stabilization before merging into the stable branch.
- main: Stable branch where PIP releases are created.
By default, branches target main, but most contributions should target dev.
Exceptions:
Direct merges to main are allowed if:
yfinanceis massively broken- Part of
yfinanceis broken, and the fix is simple and isolated - Not updating the code (e.g. docs)
Creating your branch
Fork the repository on GitHub. If already forked, remember to
Sync forkClone your forked repository:
.. code-block:: bash
git clone https://github.com/{user}/{repo}.git
Create a new branch for your feature or bug fix, from appropriate base branch:
.. code-block:: bash
git checkout {base e.g. dev}
git pull
git checkout -b {your branch}Make your changes, commit them, and push your branch to GitHub. To keep the commit history and
network graph <https://github.com/ranaroussi/yfinance/network>_ compact, give your commits a very short summary then description:.. code-block:: bash
git commit -m "short sentence summary" -m "full commit message"
Long message can be multiple lines (tip: copy-paste)
Open a pull request on Github <https://github.com/ranaroussi/yfinance/pulls>_.
Running a branch
Please see this page </development/running.html>_.
Git stuff
You might be asked to move your branch from
maintodev. This is agit rebase. Remember to update all branches involved... code-block:: bash
update all branches:
git checkout main
git pull
git checkout dev
git pullrebase from main to dev:
git checkout {your branch}
git pull
git rebase --onto dev main {your branch}
git push --force-with-lease origin {your branch}git rebasecan also be used to update your branch with new commits from base, but without adding a commit to your branch history like git merge does. This keeps history clean and avoids future merge problems... code-block:: bash
git checkout {base branch e.g. dev}
git pull
git checkout {your branch}
git rebase {base}
git push --force-with-lease origin {your branch}git squashtiny or negligible commits with meaningful ones, or to combine successive related commits.git squash guide <https://docs.gitlab.com/ee/topics/git/git_rebase.html#interactive-rebase>_.. code-block:: bash
git rebase -i HEAD~2
git push --force-with-lease origin {your branch}
Doc Source Development Documentation (`doc/source/development/documentation.rst`)
Documentation
.. contents:: Documentation:
:local:
About documentation
- yfinance documentation is written in reStructuredText (rst) and built using Sphinx.
- The documentation file is in
doc/source/... - Most of the notes under API References read from class and methods docstrings. These documentations, found in
doc/source/reference/apiis autogenerated by Sphinx and not included in git.
Building documentation locally
To build the documentation locally, follow these steps:
Install Required Dependencies:
- Install the package along with all development dependencies (includes Sphinx and related tools):
.. code-block:: bash
pip install -e ".[dev]"
Build with Sphinx:
- After dependencies are installed, use the sphinx-build command to generate HTML documentation.
.. code-block:: bash
sphinx-build -b html doc/source doc/_build/html
View Documentation Locally:
.. code-block:: bash
python -m http.server -d ./doc/_build/html
Then open "localhost:8000" in browser
Publishing documentation
Merge into main branch triggers auto-generating documentation by action .github/workflows/deploy_doc.yml.
This publishes the generated HTML into branch documentation.
Review the changes locally and push to
dev.When
devgets merged tomain, GitHub Actions workflow is automated to build documentation.
Doc Source Development Index (`doc/source/development/index.rst`)
=========== Development
yfinance relies on the community to investigate bugs and contribute code. Here's how you can help:
.. toctree::
:maxdepth: 1
code
running
documentation
testing
Doc Source Development Running (`doc/source/development/running.rst`)
Running a branch
With PIP
.. code-block:: bash
pip install git+https://github.com/{user}/{repo}.git@{branch}
E.g.:
.. code-block:: bash
pip install git+https://github.com/ranaroussi/yfinance.git@feature/name
With Git
1: Download from GitHub:
.. code-block:: bash
git clone https://github.com/ranaroussi/yfinance.git
cd yfinance
pip install -e ".[dev]"
Or if a specific branch:
.. code-block:: bash
git clone -b {branch} https://github.com/ranaroussi/yfinance.git
cd yfinance
pip install -e ".[dev]"
.. NOTE::
Only do the next part if you are installing globally
If you are installing for 1 specific project, then you can skip this step
and just `git clone` in the project directory- Add download location to Python search path
Two different ways, choose one:
Add path to
PYTHONPATHenvironment variableAdd to top of Python file:
.. code-block:: python
import sys
sys.path.insert(0, "path/to/downloaded/yfinance")
3: Verify
.. code-block:: python
import yfinance
print(yfinance)
Output should be:
<module 'yfinance' from 'path/to/downloaded/yfinance/yfinance/__init__.py'>
If output looks like this then you did step 2 wrong
<module 'yfinance' from '.../lib/python3.10/site-packages/yfinance/__init__.py'>
Doc Source Development Testing (`doc/source/development/testing.rst`)
Unit Tests
Tests are written using pytest. Install dev dependencies first if you haven't already:
.. code-block:: bash
pip install -e ".[dev]"
Here are some ways to run tests:
Run all tests:
.. code-block:: bash
pytest
Run all tests in a file:
.. code-block:: bash
pytest tests/test_prices.py
Run a specific test:
.. code-block:: bash
pytest tests/test_ticker.py::TestTicker::test_ticker_missing
General command:
.. code-block:: bash
pytest tests/{file}.py::{class}::{method}
.. note::
The tests are currently failing already
Standard result:
**Failures:** 11
**Errors:** 93
**Skipped:** 1.. seealso::
See the `pytest documentation <https://docs.pytest.org/>`_ for more information.Doc Source Reference Index (`doc/source/reference/index.rst`)
============= API Reference
Overview
The yfinance package provides easy access to Yahoo! Finance's API to retrieve market data. It includes classes and functions for downloading historical market data, accessing ticker information, managing cache, and more.
Public API
The following are the publicly available classes, and functions exposed by the yfinance package:
- :attr:
Ticker <yfinance.Ticker>: Class for accessing single ticker data. - :attr:
Tickers <yfinance.Tickers>: Class for handling multiple tickers. - :doc:
Market <yfinance.market>: Class for accessing market summary. - :attr:
Calendars <yfinance.Calendars>: Class for accessing calendar events data. - :attr:
download <yfinance.download>: Function to download market data for multiple tickers. - :attr:
Search <yfinance.Search>: Class for accessing search results. - :attr:
Lookup <yfinance.Lookup>: Class for looking up tickers. - :class:
WebSocket <yfinance.WebSocket>: Class for synchronously streaming live market data. - :class:
AsyncWebSocket <yfinance.AsyncWebSocket>: Class for asynchronously streaming live market data. - :attr:
Sector <yfinance.Sector>: Domain class for accessing sector information. - :attr:
Industry <yfinance.Industry>: Domain class for accessing industry information. - :attr:
EquityQuery <yfinance.EquityQuery>: Class to build equity query filters. - :attr:
FundQuery <yfinance.FundQuery>: Class to build fund query filters. - :attr:
ETFQuery <yfinance.ETFQuery>: Class to build ETF query filters. - :attr:
screen <yfinance.screen>: Run equity/fund queries. - :attr:
Auth <yfinance.Auth>: Class for handling Yahoo Finance authentication. - :attr:
config.debug.logging <yfinance.config>: Enable verbose debug logging (yf.config.debug.logging = True). - :attr:
set_tz_cache_location <yfinance.set_tz_cache_location>: Function to set the timezone cache location.
.. toctree::
:maxdepth: 1
:hidden:
yfinance.ticker_tickers
yfinance.stock
yfinance.market
yfinance.calendars
yfinance.financials
yfinance.analysis
yfinance.search
yfinance.lookup
yfinance.websocket
yfinance.sector_industry
yfinance.screener
yfinance.auth
yfinance.functions
yfinance.funds_data
yfinance.price_history
Doc Source Reference Yfinance.Analysis (`doc/source/reference/yfinance.analysis.rst`)
=================== Analysis & Holdings
.. currentmodule:: yfinance.Ticker
Analysis
.. autosummary::
:toctree: api/
:recursive:
get_recommendations
recommendations
get_recommendations_summary
recommendations_summary
get_upgrades_downgrades
upgrades_downgrades
get_sustainability
sustainability
get_analyst_price_targets
analyst_price_targets
get_earnings_estimate
earnings_estimate
get_revenue_estimate
revenue_estimate
get_earnings_history
earnings_history
get_eps_trend
eps_trend
get_eps_revisions
eps_revisions
get_growth_estimates
growth_estimates
Holdings
.. autosummary::
:toctree: api/
:recursive:
get_funds_data
funds_data
.. seealso::
:meth:yfinance.scrapers.funds.FundsData
.. autosummary::
:toctree: api/
:recursive:
get_insider_purchases
insider_purchases
get_insider_transactions
insider_transactions
get_insider_roster_holders
insider_roster_holders
get_major_holders
major_holders
get_institutional_holders
institutional_holders
get_mutualfund_holders
mutualfund_holders
Doc Source Reference Yfinance.Auth (`doc/source/reference/yfinance.auth.rst`)
===================== Authentication
.. currentmodule:: yfinance
.. note::
The Auth module cannot automate login using a username and password
because Yahoo Finance requires solving a reCAPTCHA, which blocks automation.
You must manually obtain and set the authentication cookies.
Class
The Auth module lets you log in to Yahoo! Finance, check the login state and
read the account's subscription tier.
.. autosummary::
:toctree: api/
Auth
Auth Sample Code
Logging in with browser cookies, then checking the login state and subscription tier:
.. literalinclude:: examples/auth.py
:language: python
Obtaining Yahoo Finance Cookies
To authenticate with Yahoo Finance, you need to obtain specific cookies. Follow these steps:
.. rubric:: Steps to Obtain the Cookies
Open your browser (e.g., Chrome, Firefox).
Log in to
Yahoo Finance <https://finance.yahoo.com>_.Open the browser's Developer Tools:
- Press
F12orCtrl + Shift + I(Windows/Linux) - Press
Cmd + Option + I(Mac)
- Press
Navigate to the Application tab (Chrome) or Storage tab (Firefox).
In the Cookies section, select
https://finance.yahoo.com.Locate the cookies named T and Y.
Copy the values of these cookies and pass them to the authentication function.
Doc Source Reference Yfinance.Calendars (`doc/source/reference/yfinance.calendars.rst`)
===================== Calendars
.. currentmodule:: yfinance
Class
The Calendars class allows you to get information about upcoming events, for example, earning events.
.. autosummary::
:toctree: api/
Calendars
Sample Code
.. literalinclude:: examples/calendars.py
:language: python
Doc Source Reference Yfinance.Financials (`doc/source/reference/yfinance.financials.rst`)
========== Financials
.. currentmodule:: yfinance.Ticker
.. autosummary::
:toctree: api/
:recursive:
get_income_stmt
income_stmt
quarterly_income_stmt
ttm_income_stmt
get_balance_sheet
balance_sheet
get_cashflow
cashflow
quarterly_cashflow
ttm_cashflow
get_earnings
earnings
calendar
get_earnings_dates
earnings_dates
get_sec_filings
sec_filings
Doc Source Reference Yfinance.Functions (`doc/source/reference/yfinance.functions.rst`)
========================= Functions and Utilities
.. currentmodule:: yfinance
Download Market Data
The `download` function allows you to retrieve market data for multiple tickers at once.
.. autosummary::
:toctree: api/
download
Enable Debug Mode
~~~~~~~~~~~~~~~~~
Enables logging of debug information for the `yfinance` package.
.. autosummary::
:toctree: api/
enable_debug_mode
Set Timezone Cache LocationSets the cache location for timezone data.
.. autosummary::
:toctree: api/
set_tz_cache_location
Doc Source Reference Yfinance.Funds Data (`doc/source/reference/yfinance.funds_data.rst`)
==================== `FundsData` class
.. currentmodule:: yfinance.scrapers.funds
.. autosummary::
:toctree: api/
:recursive:
FundsData
Doc Source Reference Yfinance.Market (`doc/source/reference/yfinance.market.rst`)
===================== Market
.. currentmodule:: yfinance
Class
The Market class, allows you to access market data in a Pythonic way.
.. autosummary::
:toctree: api/
Market
Market Sample Code
.. literalinclude:: examples/market.py
:language: python
Markets
There are 8 different markets available in Yahoo Finance.
- US
- GB
\
- ASIA
- EUROPE
\
- RATES
- COMMODITIES
- CURRENCIES
- CRYPTOCURRENCIES
.. note::
Only Market.summary returns regional data for all of the values above.
Market.status is backed by Yahoo's markettime endpoint, which currently
ignores the market parameter and only returns U.S. data; for any non-US
market, status will therefore be None and a warning is logged.
Doc Source Reference Yfinance.Price History (`doc/source/reference/yfinance.price_history.rst`)
==================== `PriceHistory` class
.. currentmodule:: yfinance.scrapers.history
.. autoclass:: PriceHistory
:members:
:undoc-members:
Doc Source Reference Yfinance.Screener (`doc/source/reference/yfinance.screener.rst`)
========================= Screener & Query
.. currentmodule:: yfinance
Query Market Data
The `Sector` and `Industry` modules allow you to access the sector and industry information.
.. autosummary::
:toctree: api/
EquityQuery
FundQuery
ETFQuery
screen
.. seealso::
:attr:`EquityQuery.valid_fields <yfinance.EquityQuery.valid_fields>`
supported operand values for query
:attr:`EquityQuery.valid_values <yfinance.EquityQuery.valid_values>`
supported `EQ query operand parameters`
:attr:`FundQuery.valid_fields <yfinance.FundQuery.valid_fields>`
supported operand values for query
:attr:`FundQuery.valid_values <yfinance.FundQuery.valid_values>`
supported `EQ query operand parameters`
:attr:`ETFQuery.valid_fields <yfinance.ETFQuery.valid_fields>`
supported operand values for query
:attr:`ETFQuery.valid_values <yfinance.ETFQuery.valid_values>`
supported `EQ query operand parameters`
---
### Doc Source Reference Yfinance.Search (`doc/source/reference/yfinance.search.rst`)
=====================
Search & Lookup
=====================
.. currentmodule:: yfinance
Class
------------
The `Search` module, allows you to access search data in a Pythonic way.
.. autosummary::
:toctree: api/
Search
The `Lookup` module, allows you to look up tickers in a Pythonic way.
.. autosummary::
:toctree: api/
Lookup
Sample Code
------------------
The `Search` module, allows you to access search data in a Pythonic way.
.. literalinclude:: examples/search.py
:language: python
The `Lookup` module, allows you to look up tickers in a Pythonic way.
.. literalinclude:: examples/lookup.py
:language: python
---
### Doc Source Reference Yfinance.Sector Industry (`doc/source/reference/yfinance.sector_industry.rst`)
=======================
Sector and Industry
=======================
.. currentmodule:: yfinance
Sector class
--------------
The `Sector` and `Industry` modules provide access to the Sector and Industry information.
.. autosummary::
:toctree: api/
:recursive:
Sector
Industry
.. seealso::
:attr:`Sector.industries <yfinance.Sector.industries>`
Map of sector and industry
Sample Code
---------------------
To initialize, use the relevant sector or industry key as below.
.. literalinclude:: examples/sector_industry.py
:language: python
The modules can be chained with Ticker as below.
.. literalinclude:: examples/sector_industry_ticker.py
:language: python
Region scoping
--------------
By default ``Sector`` and ``Industry`` return U.S. data. Pass a Yahoo region
(ISO 3166-1 alpha-2 country code, case-insensitive) to scope ``top_companies``,
``top_etfs``, ``top_mutual_funds`` and the industry top performing/growth lists::
yf.Sector("technology", region="GB").top_companies # UK
yf.Sector("technology", region="DE").top_companies # Germany
yf.Industry("software-infrastructure", region="JP") # Japan
---
### Doc Source Reference Yfinance.Stock (`doc/source/reference/yfinance.stock.rst`)
=====
Stock
=====
.. currentmodule:: yfinance.Ticker
Ticker stock methods
--------------------
.. autosummary::
:toctree: api/
:recursive:
get_isin
isin
history
.. seealso::
:meth:`yfinance.scrapers.history.PriceHistory.history`
Documentation for history
:doc:`../advanced/price_repair`
Documentation for price repair
.. autosummary::
:toctree: api/
:recursive:
get_history_metadata
get_dividends
dividends
get_splits
splits
get_actions
actions
get_capital_gains
capital_gains
get_shares_full
get_info
info
get_fast_info
fast_info
get_news
news
---
### Doc Source Reference Yfinance.Ticker Tickers (`doc/source/reference/yfinance.ticker_tickers.rst`)
=====================
Ticker and Tickers
=====================
.. currentmodule:: yfinance
Class
------------
The `Ticker` module, allows you to access ticker data in a Pythonic way.
.. autosummary::
:toctree: api/
Ticker
Tickers
Ticker Sample Code
------------------
The `Ticker` module, allows you to access ticker data in a Pythonic way.
.. literalinclude:: examples/ticker.py
:language: python
To initialize multiple `Ticker` objects, use
.. literalinclude:: examples/tickers.py
:language: python
For tickers that are ETFs/Mutual Funds, `Ticker.funds_data` provides access to fund related data.
Funds' Top Holdings and other data with category average is returned as `pd.DataFrame`.
.. literalinclude:: examples/funds_data.py
:language: python
If you want to use a proxy server for downloading data, use:
.. literalinclude:: examples/proxy.py
:language: python
To initialize multiple `Ticker` objects, use `Tickers` module
.. literalinclude:: examples/tickers.py
:language: python
---
### Doc Source Reference Yfinance.Websocket (`doc/source/reference/yfinance.websocket.rst`)
=====================
WebSocket
=====================
.. currentmodule:: yfinance
The `WebSocket` module allows you to stream live price data from Yahoo Finance using both synchronous and asynchronous clients.
Classes
------------
.. autosummary::
:toctree: api/
WebSocket
AsyncWebSocket
Synchronous WebSocket
----------------------
The `WebSocket` class provides a synchronous interface for subscribing to price updates.
Sample Code:
.. literalinclude:: examples/live_sync.py
:language: python
Asynchronous WebSocket
-----------------------
The `AsyncWebSocket` class provides an asynchronous interface for subscribing to price updates.
Sample Code:
.. literalinclude:: examples/live_async.py
:language: python
.. note::
If you're running asynchronous code in a Jupyter notebook, you may encounter issues with event loops. To resolve this, you need to import and apply `nest_asyncio` to allow nested event loops.
Add the following code before running asynchronous operations:
.. code-block:: python
import nest_asyncio
nest_asyncio.apply()
---
### Doc Source Templates Autosummary Class (`doc/source/_templates/autosummary/class.rst`)
:orphan:
{{ objname | escape | underline }}
.. currentmodule:: {{ module }}
.. autoclass:: {{ objname }}
:exclude-members: {% for item in attributes %}{{ item }}{% if not loop.last %}, {% endif %}{% endfor %}
{% block attributes %}
{% if attributes %}
.. rubric:: Attributes
{% for item in attributes %}
.. autoattribute:: {{ item }}
:noindex:
{%- endfor %}
{% endif %}
{% endblock attributes %}
{% block methods %}
{% if methods %}
.. rubric:: Methods
{% for item in methods %}
.. automethod:: {{ item }}
:noindex:
{%- endfor %}
{% endif %}
{% endblock methods %}
---
--- METRICS ---
- Files Extracted: 30
- Estimated Token Budget: ~10607 tokens
- Canonical Reference: https://codewiki.google/github.com/ranaroussi/yfinance