Package: yfinance
Download market data from Yahoo! Finance's API*** IMPORTANT LEGAL DISCLAIMER ***Yahoo!, Y!Finance, and Yahoo! finance are registered trademarks of
Yahoo, Inc.yfinance isnotaffiliated, 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, andhere)for
details on your rights to use the actual data downloaded. Remember - the
Yahoo! finance API is intended for personal use only.yfinanceoffers a threaded and Pythonic way to download market data fromYahoo!Ⓡ finance.→ Check out thisBlog postfor a detailed tutorial with code examples.Changelog »InstallationInstallyfinanceusingpip:$ pip install yfinance --upgrade --no-cache-dirWith Conda.To install with optional dependencies, replaceoptionalwith:nospamforcaching-requests,repairforprice repair, ornospam,repairfor both:$ pip install "yfinance[optional]"Required dependencies,all dependencies.Quick StartThe Ticker moduleTheTickermodule, which allows you to access ticker data in a more Pythonic way:importyfinanceasyfmsft=yf.Ticker("MSFT")# get all stock infomsft.info# get historical market datahist=msft.history(period="1mo")# show meta information about the history (requires history() to be called first)msft.history_metadata# show actions (dividends, splits, capital gains)msft.actionsmsft.dividendsmsft.splitsmsft.capital_gains# only for mutual funds & etfs# show share countmsft.get_shares_full(start="2022-01-01",end=None)# show financials:# - income statementmsft.income_stmtmsft.quarterly_income_stmt# - balance sheetmsft.balance_sheetmsft.quarterly_balance_sheet# - cash flow statementmsft.cashflowmsft.quarterly_cashflow# see `Ticker.get_income_stmt()` for more options# show holdersmsft.major_holdersmsft.institutional_holdersmsft.mutualfund_holdersmsft.insider_transactionsmsft.insider_purchasesmsft.insider_roster_holders# show recommendationsmsft.recommendationsmsft.recommendations_summarymsft.upgrades_downgrades# Show future and historic earnings dates, returns at most next 4 quarters and last 8 quarters by default.# Note: If more are needed use msft.get_earnings_dates(limit=XX) with increased limit argument.msft.earnings_dates# show ISIN code - *experimental*# ISIN = International Securities Identification Numbermsft.isin# show options expirationsmsft.options# show newsmsft.news# get option chain for specific expirationopt=msft.option_chain('YYYY-MM-DD')# data available via: opt.calls, opt.putsIf you want to use a proxy server for downloading data, use:importyfinanceasyfmsft=yf.Ticker("MSFT")msft.history(...,proxy="PROXY_SERVER")msft.get_actions(proxy="PROXY_SERVER")msft.get_dividends(proxy="PROXY_SERVER")msft.get_splits(proxy="PROXY_SERVER")msft.get_capital_gains(proxy="PROXY_SERVER")msft.get_balance_sheet(proxy="PROXY_SERVER")msft.get_cashflow(proxy="PROXY_SERVER")msft.option_chain(...,proxy="PROXY_SERVER")...Multiple tickersTo initialize multipleTickerobjects, useimportyfinanceasyftickers=yf.Tickers('msft aapl goog')# access each ticker using (example)tickers.tickers['MSFT'].infotickers.tickers['AAPL'].history(period="1mo")tickers.tickers['GOOG'].actionsTo download price history into one table:importyfinanceasyfdata=yf.download("SPY AAPL",period="1mo")yf.download()andTicker.history()have many options for configuring fetching and processing.Review the Wikifor more options and detail.Loggingyfinancenow uses theloggingmodule to handle messages, default behaviour is only print errors. If debugging, useyf.enable_debug_mode()to switch logging to debug with custom formatting.Smarter scrapingInstall thenospampackages for smarter scraping usingpip(seeInstallation). These packages help cache calls such that Yahoo is not spammed with requests.To use a customrequestssession, pass asession=argument to
the Ticker constructor. This allows for caching calls to the API as well as a custom way to modify requests via  theUser-agentheader.importrequests_cachesession=requests_cache.CachedSession('yfinance.cache')session.headers['User-agent']='my-program/1.0'ticker=yf.Ticker('msft',session=session)# The scraped response will be stored in the cacheticker.actionsCombinerequests_cachewith rate-limiting to avoid triggering Yahoo's rate-limiter/blocker that can corrupt data.fromrequestsimportSessionfromrequests_cacheimportCacheMixin,SQLiteCachefromrequests_ratelimiterimportLimiterMixin,MemoryQueueBucketfrompyrate_limiterimportDuration,RequestRate,LimiterclassCachedLimiterSession(CacheMixin,LimiterMixin,Session):passsession=CachedLimiterSession(limiter=Limiter(RequestRate(2,Duration.SECOND*5)),# max 2 requests per 5 secondsbucket_class=MemoryQueueBucket,backend=SQLiteCache("yfinance.cache"),)Managing Multi-Level ColumnsThe following answer on Stack Overflow is forHow to deal with
multi-level column names downloaded with
yfinance?yfinancereturns apandas.DataFramewith multi-level column
names, with a level for the ticker and a level for the stock price
dataThe answer discusses:How to correctly read the the multi-level columns after
saving the dataframe to a csv withpandas.DataFrame.to_csvHow to download single or multiple tickers into a single
dataframe with single level column names and a ticker columnpandas_datareaderoverrideIf your code usespandas_datareaderand you want to download data
faster, you can "hijack"pandas_datareader.data.get_data_yahoo()method to useyfinancewhile making sure the returned data is in the
same format aspandas_datareader'sget_data_yahoo().frompandas_datareaderimportdataaspdrimportyfinanceasyfyf.pdr_override()# <== that's all it takes :-)# download dataframedata=pdr.get_data_yahoo("SPY",start="2017-01-01",end="2017-04-30")Persistent cache storeTo reduce Yahoo, yfinance store some data locally: timezones to localize dates, and cookie. Cache location is:Windows = C:/Users/<USER>/AppData/Local/py-yfinanceLinux = /home/<USER>/.cache/py-yfinanceMacOS = /Users/<USER>/Library/Caches/py-yfinanceYou can direct cache to use a different location withset_tz_cache_location():importyfinanceasyfyf.set_tz_cache_location("custom/cache/location")...Developers: want to contribute?yfinancerelies on community to investigate bugs and contribute code. Developer guide:https://github.com/ranaroussi/yfinance/discussions/1084Legal Stuffyfinanceis distributed under theApache Software License. See
theLICENSE.txtfile in the release for details.AGAIN - yfinance isnotaffiliated, 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, andhere) for
detailes on your rights to use the actual data downloaded.P.S.Please drop me an note with any feedback you have.Ran Aroussi