Skip to content

Repository files navigation

Download market data from Yahoo! Finance's API

*** 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, 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.


Python versionPyPi versionPyPi statusPyPi downloadsTravis-CI build statusCodeFactorStar this repoFollow me on twitter

yfinance offers a threaded and Pythonic way to download market data from Yahoo!Ⓡ finance.

→ Check out this Blog post for a detailed tutorial with code examples.

Changelog »


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

importyfinanceasyfmsft=yf.Ticker("MSFT")
# get stock infomsft.info# get historical market datahist=msft.history(period="max")
# show actions (dividends, splits)msft.actions# show dividendsmsft.dividends# show splitsmsft.splits# show share countmsft.shares# show income statementmsft.income_stmtmsft.quarterly_income_stmt# show balance sheetmsft.balance_sheetmsft.quarterly_balance_sheet# show cash flow statementmsft.cashflowmsft.quarterly_cashflow# show major holdersmsft.major_holders# show institutional holdersmsft.institutional_holders# show mutualfund holdersmsft.mutualfund_holders# show earningsmsft.earningsmsft.quarterly_earnings# show sustainabilitymsft.sustainability# show analysts recommendationsmsft.recommendationsmsft.recommendations_summary# show analysts other workmsft.analyst_price_targetmfst.revenue_forecastsmfst.earnings_forecastsmfst.earnings_trend# show next event (earnings, etc)msft.calendar# show all earnings datesmsft.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.puts

If 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_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

To use a custom requests session (for example to cache calls to the API or customize the User-agent header), pass a session= argument to the Ticker constructor.

importrequests_cachesession=requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] ='my-program/1.0'ticker=yf.Ticker('msft aapl goog', session=session)
# The scraped response will be stored in the cacheticker.actions

To initialize multiple Ticker objects, use

importyfinanceasyftickers=yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects# access each ticker using (example)tickers.tickers['MSFT'].infotickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

Fetching data for multiple tickers

importyfinanceasyfdata=yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

I've also added some options to make life easier :)

data=yf.download( # or pdr.get_data_yahoo(...# tickers list or string as welltickers="SPY AAPL MSFT",
# use "period" instead of start/end# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max# (optional, default is '1mo')period="ytd",
# fetch data by interval (including intraday if period < 60 days)# valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo# (optional, default is '1d')interval="1m",
# Whether to ignore timezone when aligning ticker data from # different timezones. Default is True. False may be useful for # minute/hourly data.ignore_tz=False,
# group by ticker (to access via data['SPY'])# (optional, default is 'column')group_by='ticker',
# adjust all OHLC automatically# (optional, default is False)auto_adjust=True,
# identify and attempt repair of currency unit mixups e.g. $/centsrepair=False,
# download pre/post regular market hours data# (optional, default is False)prepost=True,
# use threads for mass downloading? (True/False/Integer)# (optional, default is True)threads=True,
# proxy URL scheme use use when downloading?# (optional, default is None)proxy=None
)

Timezone cache store

When fetching price data, all dates are localized to stock exchange timezone. But timezone retrieval is relatively slow, so yfinance attemps to cache them in your users cache folder. You can direct cache to use a different location with set_tz_cache_location():

importyfinanceasyfyf.set_tz_cache_location("custom/cache/location")
...

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with 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 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

pandas_datareader override

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_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")

Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

To install yfinance using conda, see this.

Requirements

Optional (if you want to use pandas_datareader)


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 detailes on your rights to use the actual data downloaded.


P.S.

Please drop me an note with any feedback you have.

Ran Aroussi

About

Download market data from Yahoo! Finance's API

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Add copy buttons to all
 blocks
(function() {
function addCopyButtons() {
document.querySelectorAll('pre code').forEach(function(codeBlock) {
if (codeBlock.parentElement.hasAttribute('data-copy-added')) return;
codeBlock.parentElement.setAttribute('data-copy-added', 'true');
var btn = document.createElement('button');
btn.textContent = 'Copy';
btn.style.cssText = 'position:absolute;top:4px;right:4px;padding:2px 8px;font-size:11px;background:#4ecdc4;border:none;border-radius:4px;color:#1a1a2e;cursor:pointer;opacity:0.7;transition:opacity 0.2s;';
btn.onmouseover = function() { this.style.opacity = '1'; };
btn.onmouseout = function() { this.style.opacity = '0.7'; };
btn.onclick = function() {
navigator.clipboard.writeText(codeBlock.textContent).then(function() {
btn.textContent = 'Copied!';
setTimeout(function() { btn.textContent = 'Copy'; }, 1500);
});
};
codeBlock.parentElement.style.position = 'relative';
codeBlock.parentElement.appendChild(btn);
});
}
addCopyButtons();
// Re-run on dynamic content
var observer = new MutationObserver(addCopyButtons);
observer.observe(document.body, { childList: true, subtree: true });
})();
}
} catch(__e) { console.warn('[Userscript:Add Copy Buttons to Code Blocks]', __e); }
})();
(function(){
try {
var __m = "github.com";
var __re = new RegExp('^' + "github\\.com" + '
GitHub - CheyneyComputerScience/yfinance: Download market data from Yahoo! Finance's API · GitHub
Skip to content

Repository files navigation

Download market data from Yahoo! Finance's API

*** 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, 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.


Python versionPyPi versionPyPi statusPyPi downloadsTravis-CI build statusCodeFactorStar this repoFollow me on twitter

yfinance offers a threaded and Pythonic way to download market data from Yahoo!Ⓡ finance.

→ Check out this Blog post for a detailed tutorial with code examples.

Changelog »


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

importyfinanceasyfmsft=yf.Ticker("MSFT")
# get stock infomsft.info# get historical market datahist=msft.history(period="max")
# show actions (dividends, splits)msft.actions# show dividendsmsft.dividends# show splitsmsft.splits# show share countmsft.shares# show income statementmsft.income_stmtmsft.quarterly_income_stmt# show balance sheetmsft.balance_sheetmsft.quarterly_balance_sheet# show cash flow statementmsft.cashflowmsft.quarterly_cashflow# show major holdersmsft.major_holders# show institutional holdersmsft.institutional_holders# show mutualfund holdersmsft.mutualfund_holders# show earningsmsft.earningsmsft.quarterly_earnings# show sustainabilitymsft.sustainability# show analysts recommendationsmsft.recommendationsmsft.recommendations_summary# show analysts other workmsft.analyst_price_targetmfst.revenue_forecastsmfst.earnings_forecastsmfst.earnings_trend# show next event (earnings, etc)msft.calendar# show all earnings datesmsft.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.puts

If 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_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

To use a custom requests session (for example to cache calls to the API or customize the User-agent header), pass a session= argument to the Ticker constructor.

importrequests_cachesession=requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] ='my-program/1.0'ticker=yf.Ticker('msft aapl goog', session=session)
# The scraped response will be stored in the cacheticker.actions

To initialize multiple Ticker objects, use

importyfinanceasyftickers=yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects# access each ticker using (example)tickers.tickers['MSFT'].infotickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

Fetching data for multiple tickers

importyfinanceasyfdata=yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

I've also added some options to make life easier :)

data=yf.download( # or pdr.get_data_yahoo(...# tickers list or string as welltickers="SPY AAPL MSFT",
# use "period" instead of start/end# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max# (optional, default is '1mo')period="ytd",
# fetch data by interval (including intraday if period < 60 days)# valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo# (optional, default is '1d')interval="1m",
# Whether to ignore timezone when aligning ticker data from # different timezones. Default is True. False may be useful for # minute/hourly data.ignore_tz=False,
# group by ticker (to access via data['SPY'])# (optional, default is 'column')group_by='ticker',
# adjust all OHLC automatically# (optional, default is False)auto_adjust=True,
# identify and attempt repair of currency unit mixups e.g. $/centsrepair=False,
# download pre/post regular market hours data# (optional, default is False)prepost=True,
# use threads for mass downloading? (True/False/Integer)# (optional, default is True)threads=True,
# proxy URL scheme use use when downloading?# (optional, default is None)proxy=None
)

Timezone cache store

When fetching price data, all dates are localized to stock exchange timezone. But timezone retrieval is relatively slow, so yfinance attemps to cache them in your users cache folder. You can direct cache to use a different location with set_tz_cache_location():

importyfinanceasyfyf.set_tz_cache_location("custom/cache/location")
...

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with 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 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

pandas_datareader override

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_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")

Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

To install yfinance using conda, see this.

Requirements

Optional (if you want to use pandas_datareader)


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 detailes on your rights to use the actual data downloaded.


P.S.

Please drop me an note with any feedback you have.

Ran Aroussi

About

Download market data from Yahoo! Finance's API

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Force GitHub README to respect dark mode (function() { var style = document.createElement('style'); style.textContent = ' .markdown-body { color-scheme: dark light; } .markdown-body pre { background: #161b22 !important; } .markdown-body code { background: rgba(110, 118, 129, 0.4) !important; } .markdown-body table th, .markdown-body table td { border-color: #30363d !important; } .markdown-body img { background: #0d1117; } .markdown-body blockquote { border-left-color: #8b949e; } .markdown-body hr { border-color: #30363d; } '; document.head.appendChild(style); })(); } } catch(__e) { console.warn('[Userscript:GitHub Dark Mode README Fix]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - CheyneyComputerScience/yfinance: Download market data from Yahoo! Finance's API · GitHub
Skip to content

Repository files navigation

Download market data from Yahoo! Finance's API

*** 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, 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.


Python versionPyPi versionPyPi statusPyPi downloadsTravis-CI build statusCodeFactorStar this repoFollow me on twitter

yfinance offers a threaded and Pythonic way to download market data from Yahoo!Ⓡ finance.

→ Check out this Blog post for a detailed tutorial with code examples.

Changelog »


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

importyfinanceasyfmsft=yf.Ticker("MSFT")
# get stock infomsft.info# get historical market datahist=msft.history(period="max")
# show actions (dividends, splits)msft.actions# show dividendsmsft.dividends# show splitsmsft.splits# show share countmsft.shares# show income statementmsft.income_stmtmsft.quarterly_income_stmt# show balance sheetmsft.balance_sheetmsft.quarterly_balance_sheet# show cash flow statementmsft.cashflowmsft.quarterly_cashflow# show major holdersmsft.major_holders# show institutional holdersmsft.institutional_holders# show mutualfund holdersmsft.mutualfund_holders# show earningsmsft.earningsmsft.quarterly_earnings# show sustainabilitymsft.sustainability# show analysts recommendationsmsft.recommendationsmsft.recommendations_summary# show analysts other workmsft.analyst_price_targetmfst.revenue_forecastsmfst.earnings_forecastsmfst.earnings_trend# show next event (earnings, etc)msft.calendar# show all earnings datesmsft.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.puts

If 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_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

To use a custom requests session (for example to cache calls to the API or customize the User-agent header), pass a session= argument to the Ticker constructor.

importrequests_cachesession=requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] ='my-program/1.0'ticker=yf.Ticker('msft aapl goog', session=session)
# The scraped response will be stored in the cacheticker.actions

To initialize multiple Ticker objects, use

importyfinanceasyftickers=yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects# access each ticker using (example)tickers.tickers['MSFT'].infotickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

Fetching data for multiple tickers

importyfinanceasyfdata=yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

I've also added some options to make life easier :)

data=yf.download( # or pdr.get_data_yahoo(...# tickers list or string as welltickers="SPY AAPL MSFT",
# use "period" instead of start/end# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max# (optional, default is '1mo')period="ytd",
# fetch data by interval (including intraday if period < 60 days)# valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo# (optional, default is '1d')interval="1m",
# Whether to ignore timezone when aligning ticker data from # different timezones. Default is True. False may be useful for # minute/hourly data.ignore_tz=False,
# group by ticker (to access via data['SPY'])# (optional, default is 'column')group_by='ticker',
# adjust all OHLC automatically# (optional, default is False)auto_adjust=True,
# identify and attempt repair of currency unit mixups e.g. $/centsrepair=False,
# download pre/post regular market hours data# (optional, default is False)prepost=True,
# use threads for mass downloading? (True/False/Integer)# (optional, default is True)threads=True,
# proxy URL scheme use use when downloading?# (optional, default is None)proxy=None
)

Timezone cache store

When fetching price data, all dates are localized to stock exchange timezone. But timezone retrieval is relatively slow, so yfinance attemps to cache them in your users cache folder. You can direct cache to use a different location with set_tz_cache_location():

importyfinanceasyfyf.set_tz_cache_location("custom/cache/location")
...

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with 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 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

pandas_datareader override

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_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")

Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

To install yfinance using conda, see this.

Requirements

Optional (if you want to use pandas_datareader)


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 detailes on your rights to use the actual data downloaded.


P.S.

Please drop me an note with any feedback you have.

Ran Aroussi

About

Download market data from Yahoo! Finance's API

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Highlight search terms from Google/DuckDuckGo/Bing referrer (function() { var ref = document.referrer; var terms = []; if (ref.includes('google.com') || ref.includes('duckduckgo.com') || ref.includes('bing.com')) { var url = new URL(ref); var q = url.searchParams.get('q') || url.searchParams.get('p'); if (q) { terms = q.split(/\s+/).filter(function(t) { return t.length > 2; }); } } if (terms.length === 0) return; var style = document.createElement('style'); style.textContent = '.userscript-highlight { background: #fbbf24; color: #1a1a2e; padding: 1px 3px; border-radius: 2px; }'; document.head.appendChild(style); function highlight(node) { if (node.nodeType === 3) { // text node var text = node.textContent; var found = false; terms.forEach(function(term) { var regex = new RegExp('(' + term.replace(/[.*+?^${}()|[\]\\]/g, '\\') + ')', 'gi'); if (regex.test(text)) { found = true; var frag = document.createDocumentFragment(); var parts = text.split(regex); parts.forEach(function(part, i) { if (i % 2 === 0) { frag.appendChild(document.createTextNode(part)); } else { var span = document.createElement('span'); span.className = 'userscript-highlight'; span.textContent = part; frag.appendChild(span); } }); node.parentNode.replaceChild(frag, node); } }); } else if (node.nodeType === 1 && node.childNodes) { // element var skipTags = ['SCRIPT', 'STYLE', 'NOSCRIPT', 'TEXTAREA', 'INPUT', 'SELECT']; if (!skipTags.includes(node.tagName)) { Array.from(node.childNodes).forEach(highlight); } } } highlight(document.body); // Re-highlight on dynamic content var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1 || node.nodeType === 3) highlight(node); }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Highlight Search Terms]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - CheyneyComputerScience/yfinance: Download market data from Yahoo! Finance's API · GitHub
Skip to content

Repository files navigation

Download market data from Yahoo! Finance's API

*** 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, 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.


Python versionPyPi versionPyPi statusPyPi downloadsTravis-CI build statusCodeFactorStar this repoFollow me on twitter

yfinance offers a threaded and Pythonic way to download market data from Yahoo!Ⓡ finance.

→ Check out this Blog post for a detailed tutorial with code examples.

Changelog »


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

importyfinanceasyfmsft=yf.Ticker("MSFT")
# get stock infomsft.info# get historical market datahist=msft.history(period="max")
# show actions (dividends, splits)msft.actions# show dividendsmsft.dividends# show splitsmsft.splits# show share countmsft.shares# show income statementmsft.income_stmtmsft.quarterly_income_stmt# show balance sheetmsft.balance_sheetmsft.quarterly_balance_sheet# show cash flow statementmsft.cashflowmsft.quarterly_cashflow# show major holdersmsft.major_holders# show institutional holdersmsft.institutional_holders# show mutualfund holdersmsft.mutualfund_holders# show earningsmsft.earningsmsft.quarterly_earnings# show sustainabilitymsft.sustainability# show analysts recommendationsmsft.recommendationsmsft.recommendations_summary# show analysts other workmsft.analyst_price_targetmfst.revenue_forecastsmfst.earnings_forecastsmfst.earnings_trend# show next event (earnings, etc)msft.calendar# show all earnings datesmsft.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.puts

If 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_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

To use a custom requests session (for example to cache calls to the API or customize the User-agent header), pass a session= argument to the Ticker constructor.

importrequests_cachesession=requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] ='my-program/1.0'ticker=yf.Ticker('msft aapl goog', session=session)
# The scraped response will be stored in the cacheticker.actions

To initialize multiple Ticker objects, use

importyfinanceasyftickers=yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects# access each ticker using (example)tickers.tickers['MSFT'].infotickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

Fetching data for multiple tickers

importyfinanceasyfdata=yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

I've also added some options to make life easier :)

data=yf.download( # or pdr.get_data_yahoo(...# tickers list or string as welltickers="SPY AAPL MSFT",
# use "period" instead of start/end# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max# (optional, default is '1mo')period="ytd",
# fetch data by interval (including intraday if period < 60 days)# valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo# (optional, default is '1d')interval="1m",
# Whether to ignore timezone when aligning ticker data from # different timezones. Default is True. False may be useful for # minute/hourly data.ignore_tz=False,
# group by ticker (to access via data['SPY'])# (optional, default is 'column')group_by='ticker',
# adjust all OHLC automatically# (optional, default is False)auto_adjust=True,
# identify and attempt repair of currency unit mixups e.g. $/centsrepair=False,
# download pre/post regular market hours data# (optional, default is False)prepost=True,
# use threads for mass downloading? (True/False/Integer)# (optional, default is True)threads=True,
# proxy URL scheme use use when downloading?# (optional, default is None)proxy=None
)

Timezone cache store

When fetching price data, all dates are localized to stock exchange timezone. But timezone retrieval is relatively slow, so yfinance attemps to cache them in your users cache folder. You can direct cache to use a different location with set_tz_cache_location():

importyfinanceasyfyf.set_tz_cache_location("custom/cache/location")
...

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with 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 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

pandas_datareader override

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_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")

Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

To install yfinance using conda, see this.

Requirements

Optional (if you want to use pandas_datareader)


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 detailes on your rights to use the actual data downloaded.


P.S.

Please drop me an note with any feedback you have.

Ran Aroussi

About

Download market data from Yahoo! Finance's API

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Strip utm_, fbclid, gclid, etc. from all links on page (function() { var trackingParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'fbclid', 'gclid', 'dclid', 'msclkid', 'yclid', 'ref', 'ref_src', 'source', 'medium', 'campaign']; function cleanUrl(url) { try { var u = new URL(url, window.location.origin); var changed = false; trackingParams.forEach(function(p) { if (u.searchParams.has(p)) { u.searchParams.delete(p); changed = true; } }); return changed ? u.toString() : url; } catch (e) { return url; } } function cleanLinks() { document.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } cleanLinks(); var observer = new MutationObserver(function(mutations) { mutations.forEach(function(m) { m.addedNodes.forEach(function(node) { if (node.nodeType === 1) { if (node.tagName === 'A') cleanLinks(); node.querySelectorAll('a[href]').forEach(function(a) { var clean = cleanUrl(a.href); if (clean !== a.href) a.href = clean; }); } }); }); }); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:Remove Tracking Parameters from Links]', __e); } })(); (function(){ try { var __m = "youtube.com"; var __re = new RegExp('^' + "youtube\\.com" + ' GitHub - CheyneyComputerScience/yfinance: Download market data from Yahoo! Finance's API · GitHub
Skip to content

Repository files navigation

Download market data from Yahoo! Finance's API

*** 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, 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.


Python versionPyPi versionPyPi statusPyPi downloadsTravis-CI build statusCodeFactorStar this repoFollow me on twitter

yfinance offers a threaded and Pythonic way to download market data from Yahoo!Ⓡ finance.

→ Check out this Blog post for a detailed tutorial with code examples.

Changelog »


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

importyfinanceasyfmsft=yf.Ticker("MSFT")
# get stock infomsft.info# get historical market datahist=msft.history(period="max")
# show actions (dividends, splits)msft.actions# show dividendsmsft.dividends# show splitsmsft.splits# show share countmsft.shares# show income statementmsft.income_stmtmsft.quarterly_income_stmt# show balance sheetmsft.balance_sheetmsft.quarterly_balance_sheet# show cash flow statementmsft.cashflowmsft.quarterly_cashflow# show major holdersmsft.major_holders# show institutional holdersmsft.institutional_holders# show mutualfund holdersmsft.mutualfund_holders# show earningsmsft.earningsmsft.quarterly_earnings# show sustainabilitymsft.sustainability# show analysts recommendationsmsft.recommendationsmsft.recommendations_summary# show analysts other workmsft.analyst_price_targetmfst.revenue_forecastsmfst.earnings_forecastsmfst.earnings_trend# show next event (earnings, etc)msft.calendar# show all earnings datesmsft.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.puts

If 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_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

To use a custom requests session (for example to cache calls to the API or customize the User-agent header), pass a session= argument to the Ticker constructor.

importrequests_cachesession=requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] ='my-program/1.0'ticker=yf.Ticker('msft aapl goog', session=session)
# The scraped response will be stored in the cacheticker.actions

To initialize multiple Ticker objects, use

importyfinanceasyftickers=yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects# access each ticker using (example)tickers.tickers['MSFT'].infotickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

Fetching data for multiple tickers

importyfinanceasyfdata=yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

I've also added some options to make life easier :)

data=yf.download( # or pdr.get_data_yahoo(...# tickers list or string as welltickers="SPY AAPL MSFT",
# use "period" instead of start/end# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max# (optional, default is '1mo')period="ytd",
# fetch data by interval (including intraday if period < 60 days)# valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo# (optional, default is '1d')interval="1m",
# Whether to ignore timezone when aligning ticker data from # different timezones. Default is True. False may be useful for # minute/hourly data.ignore_tz=False,
# group by ticker (to access via data['SPY'])# (optional, default is 'column')group_by='ticker',
# adjust all OHLC automatically# (optional, default is False)auto_adjust=True,
# identify and attempt repair of currency unit mixups e.g. $/centsrepair=False,
# download pre/post regular market hours data# (optional, default is False)prepost=True,
# use threads for mass downloading? (True/False/Integer)# (optional, default is True)threads=True,
# proxy URL scheme use use when downloading?# (optional, default is None)proxy=None
)

Timezone cache store

When fetching price data, all dates are localized to stock exchange timezone. But timezone retrieval is relatively slow, so yfinance attemps to cache them in your users cache folder. You can direct cache to use a different location with set_tz_cache_location():

importyfinanceasyfyf.set_tz_cache_location("custom/cache/location")
...

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with 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 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

pandas_datareader override

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_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")

Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

To install yfinance using conda, see this.

Requirements

Optional (if you want to use pandas_datareader)


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 detailes on your rights to use the actual data downloaded.


P.S.

Please drop me an note with any feedback you have.

Ran Aroussi

About

Download market data from Yahoo! Finance's API

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Auto-enable theater mode on YouTube (function() { function tryTheater() { var btn = document.querySelector('button[aria-label="Theater mode"], ytd-player #player button[title="Theater mode"]'); if (btn && !btn.classList.contains('activated')) { btn.click(); } } // Try immediately tryTheater(); // Try after navigation (SPA) var lastUrl = location.href; setInterval(function() { if (location.href !== lastUrl) { lastUrl = location.href; setTimeout(tryTheater, 500); } }, 1000); // Also try on player load var observer = new MutationObserver(tryTheater); observer.observe(document.body, { childList: true, subtree: true }); })(); } } catch(__e) { console.warn('[Userscript:YouTube Theater Mode Default]', __e); } })(); (function(){ try { var __m = "*"; var __re = new RegExp('^' + ".*" + ' GitHub - CheyneyComputerScience/yfinance: Download market data from Yahoo! Finance's API · GitHub
Skip to content

Repository files navigation

Download market data from Yahoo! Finance's API

*** 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, 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.


Python versionPyPi versionPyPi statusPyPi downloadsTravis-CI build statusCodeFactorStar this repoFollow me on twitter

yfinance offers a threaded and Pythonic way to download market data from Yahoo!Ⓡ finance.

→ Check out this Blog post for a detailed tutorial with code examples.

Changelog »


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

importyfinanceasyfmsft=yf.Ticker("MSFT")
# get stock infomsft.info# get historical market datahist=msft.history(period="max")
# show actions (dividends, splits)msft.actions# show dividendsmsft.dividends# show splitsmsft.splits# show share countmsft.shares# show income statementmsft.income_stmtmsft.quarterly_income_stmt# show balance sheetmsft.balance_sheetmsft.quarterly_balance_sheet# show cash flow statementmsft.cashflowmsft.quarterly_cashflow# show major holdersmsft.major_holders# show institutional holdersmsft.institutional_holders# show mutualfund holdersmsft.mutualfund_holders# show earningsmsft.earningsmsft.quarterly_earnings# show sustainabilitymsft.sustainability# show analysts recommendationsmsft.recommendationsmsft.recommendations_summary# show analysts other workmsft.analyst_price_targetmfst.revenue_forecastsmfst.earnings_forecastsmfst.earnings_trend# show next event (earnings, etc)msft.calendar# show all earnings datesmsft.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.puts

If 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_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

To use a custom requests session (for example to cache calls to the API or customize the User-agent header), pass a session= argument to the Ticker constructor.

importrequests_cachesession=requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] ='my-program/1.0'ticker=yf.Ticker('msft aapl goog', session=session)
# The scraped response will be stored in the cacheticker.actions

To initialize multiple Ticker objects, use

importyfinanceasyftickers=yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects# access each ticker using (example)tickers.tickers['MSFT'].infotickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

Fetching data for multiple tickers

importyfinanceasyfdata=yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

I've also added some options to make life easier :)

data=yf.download( # or pdr.get_data_yahoo(...# tickers list or string as welltickers="SPY AAPL MSFT",
# use "period" instead of start/end# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max# (optional, default is '1mo')period="ytd",
# fetch data by interval (including intraday if period < 60 days)# valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo# (optional, default is '1d')interval="1m",
# Whether to ignore timezone when aligning ticker data from # different timezones. Default is True. False may be useful for # minute/hourly data.ignore_tz=False,
# group by ticker (to access via data['SPY'])# (optional, default is 'column')group_by='ticker',
# adjust all OHLC automatically# (optional, default is False)auto_adjust=True,
# identify and attempt repair of currency unit mixups e.g. $/centsrepair=False,
# download pre/post regular market hours data# (optional, default is False)prepost=True,
# use threads for mass downloading? (True/False/Integer)# (optional, default is True)threads=True,
# proxy URL scheme use use when downloading?# (optional, default is None)proxy=None
)

Timezone cache store

When fetching price data, all dates are localized to stock exchange timezone. But timezone retrieval is relatively slow, so yfinance attemps to cache them in your users cache folder. You can direct cache to use a different location with set_tz_cache_location():

importyfinanceasyfyf.set_tz_cache_location("custom/cache/location")
...

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with 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 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

pandas_datareader override

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_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")

Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

To install yfinance using conda, see this.

Requirements

Optional (if you want to use pandas_datareader)


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 detailes on your rights to use the actual data downloaded.


P.S.

Please drop me an note with any feedback you have.

Ran Aroussi

About

Download market data from Yahoo! Finance's API

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages

, 'i'); if (__m === '*' || __re.test(location.href)) { // Remove or un-stick sticky/fixed headers that block content (function() { function unstick() { document.querySelectorAll('header, nav, [role="banner"], .header, .navbar, .sticky, .fixed-top, [style*="position: fixed"], [style*="position:sticky"]').forEach(function(el) { if (el.style.position === 'fixed' || el.style.position === 'sticky' || getComputedStyle(el).position === 'fixed' || getComputedStyle(el).position === 'sticky') { el.style.position = 'static'; el.style.top = 'auto'; el.style.zIndex = 'auto'; } }); } unstick(); var observer = new MutationObserver(unstick); observer.observe(document.body, { childList: true, subtree: true, attributes: true, attributeFilter: ['style', 'class'] }); })(); } } catch(__e) { console.warn('[Userscript:Kill Sticky Headers]', __e); } })(); })(); GitHub - CheyneyComputerScience/yfinance: Download market data from Yahoo! Finance's API · GitHub
Skip to content

Repository files navigation

Download market data from Yahoo! Finance's API

*** 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, 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.


Python versionPyPi versionPyPi statusPyPi downloadsTravis-CI build statusCodeFactorStar this repoFollow me on twitter

yfinance offers a threaded and Pythonic way to download market data from Yahoo!Ⓡ finance.

→ Check out this Blog post for a detailed tutorial with code examples.

Changelog »


Quick Start

The Ticker module

The Ticker module, which allows you to access ticker data in a more Pythonic way:

importyfinanceasyfmsft=yf.Ticker("MSFT")
# get stock infomsft.info# get historical market datahist=msft.history(period="max")
# show actions (dividends, splits)msft.actions# show dividendsmsft.dividends# show splitsmsft.splits# show share countmsft.shares# show income statementmsft.income_stmtmsft.quarterly_income_stmt# show balance sheetmsft.balance_sheetmsft.quarterly_balance_sheet# show cash flow statementmsft.cashflowmsft.quarterly_cashflow# show major holdersmsft.major_holders# show institutional holdersmsft.institutional_holders# show mutualfund holdersmsft.mutualfund_holders# show earningsmsft.earningsmsft.quarterly_earnings# show sustainabilitymsft.sustainability# show analysts recommendationsmsft.recommendationsmsft.recommendations_summary# show analysts other workmsft.analyst_price_targetmfst.revenue_forecastsmfst.earnings_forecastsmfst.earnings_trend# show next event (earnings, etc)msft.calendar# show all earnings datesmsft.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.puts

If 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_balance_sheet(proxy="PROXY_SERVER")
msft.get_cashflow(proxy="PROXY_SERVER")
msft.option_chain(..., proxy="PROXY_SERVER")
...

To use a custom requests session (for example to cache calls to the API or customize the User-agent header), pass a session= argument to the Ticker constructor.

importrequests_cachesession=requests_cache.CachedSession('yfinance.cache')
session.headers['User-agent'] ='my-program/1.0'ticker=yf.Ticker('msft aapl goog', session=session)
# The scraped response will be stored in the cacheticker.actions

To initialize multiple Ticker objects, use

importyfinanceasyftickers=yf.Tickers('msft aapl goog')
# ^ returns a named tuple of Ticker objects# access each ticker using (example)tickers.tickers['MSFT'].infotickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

Fetching data for multiple tickers

importyfinanceasyfdata=yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

I've also added some options to make life easier :)

data=yf.download( # or pdr.get_data_yahoo(...# tickers list or string as welltickers="SPY AAPL MSFT",
# use "period" instead of start/end# valid periods: 1d,5d,1mo,3mo,6mo,1y,2y,5y,10y,ytd,max# (optional, default is '1mo')period="ytd",
# fetch data by interval (including intraday if period < 60 days)# valid intervals: 1m,2m,5m,15m,30m,60m,90m,1h,1d,5d,1wk,1mo,3mo# (optional, default is '1d')interval="1m",
# Whether to ignore timezone when aligning ticker data from # different timezones. Default is True. False may be useful for # minute/hourly data.ignore_tz=False,
# group by ticker (to access via data['SPY'])# (optional, default is 'column')group_by='ticker',
# adjust all OHLC automatically# (optional, default is False)auto_adjust=True,
# identify and attempt repair of currency unit mixups e.g. $/centsrepair=False,
# download pre/post regular market hours data# (optional, default is False)prepost=True,
# use threads for mass downloading? (True/False/Integer)# (optional, default is True)threads=True,
# proxy URL scheme use use when downloading?# (optional, default is None)proxy=None
)

Timezone cache store

When fetching price data, all dates are localized to stock exchange timezone. But timezone retrieval is relatively slow, so yfinance attemps to cache them in your users cache folder. You can direct cache to use a different location with set_tz_cache_location():

importyfinanceasyfyf.set_tz_cache_location("custom/cache/location")
...

Managing Multi-Level Columns

The following answer on Stack Overflow is for How to deal with multi-level column names downloaded with yfinance?

  • yfinance returns a pandas.DataFrame with 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 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

pandas_datareader override

If your code uses pandas_datareader and you want to download data faster, you can "hijack" pandas_datareader.data.get_data_yahoo() method to use yfinance while making sure the returned data is in the same format as pandas_datareader's get_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")

Installation

Install yfinance using pip:

$ pip install yfinance --upgrade --no-cache-dir

To install yfinance using conda, see this.

Requirements

Optional (if you want to use pandas_datareader)


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 detailes on your rights to use the actual data downloaded.


P.S.

Please drop me an note with any feedback you have.

Ran Aroussi

About

Download market data from Yahoo! Finance's API

Resources

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages