重要な法的免責事項***ヤフー!ファイナンスおよびYahoo!ファイナンスは、 ヤフー株式会社 yfinanceは、Yahoo, Inc.と提携、承認、または精査されていません。それは Yahooの公開されているAPIを使用するオープンソースツールであり、 研究および教育目的を目的としています。 Yahoo!の利用規約(ここ、ここ、ここ)を参照してください。 ダウンロードした実際のデータを使用する権利の詳細。覚えておいてください - Yahoo! ファイナンス API は、個人使用のみを目的としています。 |
yfinanceは、Yahoo!(R)ファイナンスから市場データをダウンロードするためのスレッド化されたPythonicな方法を提供します。
→ コード例を含む詳細なチュートリアルについては、このブログ投稿をご覧ください。
2022年<>月以降、Yahooは非市場データをスクレイピングするWebデータを暗号化しています。幸いなことに、復号化キーは利用可能ですが、Yahooはそれらを数回移動/変更したため、数回破損しました。 Yahooによる将来の変更に備えて準備が整いました。
yfinance
yfinance
yfinance
なぜYahooはこれをしているのですか?私たちにはわかりません。スクレーパーを止めることですか?たぶん、Yahooの負荷を軽減するための変更を実装しました。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またはヘッダーをカスタマイズする)、引数をに渡します ティッカーコンストラクタ。
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")
...
スタックオーバーフローに関する次の回答は、対処方法に関するものです 複数レベルの列名 でダウンロードされました yファイナンス?
yfinance複数レベルの列を持つ を返します。 ティッカーのレベルと株価のレベルを含む名前 データ
pandas.DataFrame
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
pandas_datareader)
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.
Please drop me an note with any feedback you have.
Ran Aroussi