yfinance - 从 Yahoo! 下载市场数据 财务API

Created at: 2017-05-21 18:16:15
Language: Python
License: Apache-2.0

从雅虎财经的API下载市场数据

重要法律免责声明 ***


雅虎!,Y!Finance和Yahoo!财经是Yahoo, Inc.的注册商标。

yfinance不是雅虎公司的附属公司,认可或审查。它是一个开源工具,使用雅虎公开可用的API,用于研究和教育目的。

你应该参阅 Yahoo! 的使用条款(此处、此处和此处),了解有关你使用下载的实际数据的权利的详细信息。请记住 - 雅虎财经 API 仅供个人使用。


 anaconda 版本 皮皮版本 皮皮状态 PyPi 下载 特拉维斯-孔子学院构建状态 代码因子 为本存储库加注星标 在推特上关注我

yfinance提供了一种线程和Pythonic的方式来从Yahoo!(R)财经下载市场数据。

→ 查看此博客文章,获取包含代码示例的详细教程。

更新日志 »


新闻 [2023-01-27]

自 2022 年 12 月以来,雅虎一直在加密抓取非市场数据的网络数据。幸运的是,解密密钥是可用的,尽管雅虎多次移动/更改它们,因此多次中断。 现在为雅虎未来的任何变化做好了更好的准备。

yfinance
yfinance
yfinance

雅虎为什么要这样做?不知道。是为了阻止 Scraping 刀吗?也许吧,所以我们实施了更改以减少雅虎的负载。12 月,我们推出了具有优化抓取功能的 0.2 版。然后在 0.2.6 中引入,尽可能更快地访问某些元素,例如价格统计并强制用户切换(对不起,但我们认为有必要)。 只要存在没有快速替代方案的元素,就会继续存在。

Ticker.fast_info
info
info

快速入门

自动收报机模块

该模块允许你以更 Python 的方式访问股票代码数据:

Ticker

import yfinance as yf

msft = yf.Ticker("MSFT")

# get all stock info (slow)
msft.info
# fast access to subset of stock info (opportunistic)
msft.fast_info

# get historical market data
hist = 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.actions
msft.dividends
msft.splits
msft.capital_gains  # only for mutual funds & etfs

# show share count
# - yearly summary:
msft.shares
# - accurate time-series count:
msft.get_shares_full(start="2022-01-01", end=None)

# show financials:
# - income statement
msft.income_stmt
msft.quarterly_income_stmt
# - balance sheet
msft.balance_sheet
msft.quarterly_balance_sheet
# - cash flow statement
msft.cashflow
msft.quarterly_cashflow
# see `Ticker.get_income_stmt()` for more options

# show holders
msft.major_holders
msft.institutional_holders
msft.mutualfund_holders

# show earnings
msft.earnings
msft.quarterly_earnings

# show sustainability
msft.sustainability

# show analysts recommendations
msft.recommendations
msft.recommendations_summary
# show analysts other work
msft.analyst_price_target
msft.revenue_forecasts
msft.earnings_forecasts
msft.earnings_trend

# show next event (earnings, etc)
msft.calendar

# 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 Number
msft.isin

# show options expirations
msft.options

# show news
msft.news

# get option chain for specific expiration
opt = msft.option_chain('YYYY-MM-DD')
# data available via: opt.calls, opt.puts

如果要使用代理服务器下载数据,请使用:

import yfinance as yf

msft = 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")
...

若要使用自定义会话(例如缓存对 API 的调用或自定义标头),请将参数传递给 Ticker 构造函数。

requests
User-agent
session=

import requests_cache
session = 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 cache
ticker.actions

要初始化多个对象,请使用

Ticker

import yfinance as yf

tickers = yf.Tickers('msft aapl goog')

# access each ticker using (example)
tickers.tickers['MSFT'].info
tickers.tickers['AAPL'].history(period="1mo")
tickers.tickers['GOOG'].actions

获取多个股票代码的数据

import yfinance as yf
data = yf.download("SPY AAPL", start="2017-01-01", end="2017-04-30")

我还添加了一些选项,使生活更轻松:)

data = yf.download(  # or pdr.get_data_yahoo(...
        # tickers list or string as well
        tickers = "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 = "5d",

        # Whether to ignore timezone when aligning ticker data from 
        # different timezones. Default is False.
        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,

        # attempt repair of missing data or currency mixups e.g. $/cents
        repair = 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
    )

时区缓存存储

获取价格数据时,所有日期都本地化为证券交易所时区。但是时区检索相对较慢,因此yfinance想将它们缓存在你的用户缓存文件夹中。你可以指示缓存以使用其他位置:

set_tz_cache_location()

import yfinance as yf
yf.set_tz_cache_location("custom/cache/location")
...

管理多级列

以下关于堆栈溢出的答案是如何处理使用 yfinance 下载的多级列名?

  • yfinance
    返回具有多级列名称的 a,其中级别用于股票代码,一个级别用于股票价格数据
    pandas.DataFrame
    • 答案讨论:
      • 将数据帧保存到csv后如何正确读取多级列
        pandas.DataFrame.to_csv
      • 如何将单个或多个股票代码下载到具有单级列名称和股票代码列的单个数据帧中

pandas_datareader
覆盖

如果你的代码使用并且你想更快地下载数据,你可以“劫持”方法来使用yfinance,同时确保返回的数据与pandas_datareader的格式相同。

pandas_datareader
pandas_datareader.data.get_data_yahoo()
get_data_yahoo()

from pandas_datareader import data as pdr

import yfinance as yf
yf.pdr_override() # <== that's all it takes :-)

# download dataframe
data = pdr.get_data_yahoo("SPY", start="2017-01-01", end="2017-04-30")

安装

安装 :

yfinance
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