【yfinance API解説】Part3 Tickers, Search, and Others編
yfinanceのTicker以外のClassについて解説します。(執筆: 2025/02/12)
1. Tickers Class
Tickerオブジェクトを複数扱うことができる。
使い方はTickerクラスとほぼ同じためサンプルコードは省略。
class yfinance.Tickers(tickers, session=None)
メソッド一覧
__init__(tickers, session=None)
download(period='1mo', interval='1d', start=None, end=None, prepost=False, actions=True, auto_adjust=True, repair=False, proxy=None, threads=True, group_by='column', progress=True, timeout=10, **kwargs)
history(period='1mo', interval='1d', start=None, end=None, prepost=False, actions=True, auto_adjust=True, repair=False, proxy=None, threads=True, group_by='column', progress=True, timeout=10, **kwargs)
news()
2. Search Class
yahoo finance上の情報を検索できる。
Tickerクラスにもget_news()
メソッドがあるが、Tickerクラスではその企業に関するニュースを取得するのに対して、Searchクラスでは一般的な検索結果(yahoo finace上で"apple"と検索した場合)としてのニュース記事を返す。
企業のニュース以外にも、その企業に関連するETFやオプションなどその他の金融商品のニュースが含まれる可能性もある。
・Sample Code
import yfinance as yf
# get list of quotes
quotes = yf.Search("AAPL", max_results=10).quotes # 金融商品の情報
# get list of news
news = yf.Search("Google", news_count=10).news # ニュース
# get list of related research
research = yf.Search("apple", include_research=True).research # 分析リポートなど
・output
# quotes
[{'exchange': 'NMS',
'shortname': 'Apple Inc.',
'quoteType': 'EQUITY',
'symbol': 'AAPL',
'index': 'quotes',
'score': 3555100.0,
'typeDisp': 'Equity',
'longname': 'Apple Inc.',
'exchDisp': 'NASDAQ',
'sector': 'Technology',
'sectorDisp': 'Technology',
'industry': 'Consumer Electronics',
'industryDisp': 'Consumer Electronics',
'dispSecIndFlag': True,
'isYahooFinance': True},
{'exchange': 'NGM',
...
# news
[{'uuid': 'e6de7a56-1f24-370d-8a68-5cf5f8875564',
'title': 'Google changed the Gulf of Mexico to the Gulf of America on Maps',
'publisher': 'TechCrunch',
'link': 'https://finance.yahoo.com/m/e6de7a56-1f24-370d-8a68-5cf5f8875564/google-changed-the-gulf-of.html',
'providerPublishTime': 1739239062,
'type': 'STORY',
'thumbnail': {'resolutions': [{'url': 'https://s.yimg.com/uu/api/res/1.2/SMBFgrZMf0_Y6NAPWSHDiQ--~B/aD0zNzE7dz02Nzk7YXBwaWQ9eXRhY2h5b24-/https://media.zenfs.com/en/techcrunch_for_finance_733/180d9c6c3ca4bd6e633dec33e340e7ba',
'width': 679,
'height': 371,
'tag': 'original'},
{'url': 'https://s.yimg.com/uu/api/res/1.2/gM7s4Bzmd6E6N2yTd3B5Eg--~B/Zmk9ZmlsbDtoPTE0MDtweW9mZj0wO3c9MTQwO2FwcGlkPXl0YWNoeW9u/https://media.zenfs.com/en/techcrunch_for_finance_733/180d9c6c3ca4bd6e633dec33e340e7ba',
'width': 140,
'height': 140,
'tag': '140x140'}]},
'relatedTickers': ['GOOG']},
# research
[{'reportHeadline': 'February Can Be a Tough Month',
'reportDate': 1738670405000,
'id': 'ARGUS_42563_MarketOutlook_1738670405000',
'provider': 'Argus'},
...
Searchクラスの引数詳細
class yfinance.Search(query, max_results=8, news_count=8, lists_count=8, include_cb=True, include_nav_links=False, include_research=False, include_cultural_assets=False, enable_fuzzy_query=False, recommended=8, session=None, proxy=None, timeout=30, raise_errors=True)
3. Sector Class
セクターや産業に関する情報を取得できる。
ticker情報はETFなど、該当セクターの情報を表している。
・Sample Code
import yfinance as yf
tech = yf.Sector('technology')
software = yf.Industry('software-infrastructure')
# Common information
tech.key # 分類情報
tech.name
tech.symbol
tech.ticker
tech.overview # 概要
tech.top_companies # トップ企業
tech.research_reports # セクターに関するレポート
# Sector information
tech.top_etfs # ETF
tech.top_mutual_funds # 投資信託
tech.industries # 産業情報(techの中のsemiconductorsなど)
# Industry information
software.sector_key
software.sector_name
software.top_performing_companies # 株価上昇率の良い企業
software.top_growth_companies # 株価成長が予期される企業
・output
# top_performing_companies
name ytd return last price target price
symbol
EXOD Exodus Movement, Inc. 0.6682 51.18 50.000
NET Cloudflare, Inc. 0.6019 172.49 140.773
PLTR Palantir Technologies Inc. 0.5424 116.65 82.845
ALLT Allot Ltd. 0.4975 8.91 13.000
PGY Pagaya Technologies Ltd. 0.4004 13.01 20.350
# top_growth_companies
name ytd return growth estimate
symbol
CFLT Confluent, Inc. 0.1252 5.500000
AVDX AvidXchange Holdings, Inc. -0.0174 3.000000
OSPN OneSpan Inc. 0.0615 2.000000
GB Global Blue Group Holding AG -0.0433 1.809818
IOT Samsara Inc. 0.2593 1.428571
tech: overview, top_companies, research_reports
software: top_XXX
のデータは使えそう。
Tickerとして利用する例
import yfinance as yf
# Ticker to Sector and Industry
msft = yf.Ticker('MSFT')
tech = yf.Sector(msft.info.get('sectorKey'))
software = yf.Industry(msft.info.get('industryKey'))
# Sector and Industry to Ticker
tech_ticker = tech.ticker
tech_ticker.info
software_ticker = software.ticker
software_ticker.history()
4. Screener & Query Class
クラス
EquityQuery(...): 地域やセクター、取引所等によって株式のフィルターを構築できる。
FundQuery(...): 地域やセクター、取引所等によって投資信託のフィルターを構築できる。
screen(query[, offset, size, sortField, ...]): クエリやフィルターを実行する
4.1 EquityQuery Class
株式検索に使用するクエリを定義できる。
・Examle
from yfinance import EquityQuery
EQuery = EquityQuery('and', [
EquityQuery('is-in', ['exchange', 'NMS', 'NYQ']),
EquityQuery('lt', ["epsgrowth.lasttwelvemonths", 15])
])
Edict = EQuery.to_dict()
4.2 FundQuery Class
投資信託検索に使用するクエリを定義できる。
・Example
from yfinance import FundQuery
FQuery = FundQuery('and', [
FundQuery('eq', ['categoryname', 'Large Growth']),
FundQuery('is-in', ['performanceratingoverall', 4, 5]),
FundQuery('lt', ['initialinvestment', 100001]),
FundQuery('lt', ['annualreturnnavy1categoryrank', 50]),
FundQuery('eq', ['exchange', 'NAS'])
])
Fdict = FQuery.to_dict()
4.3 screen Class
クエリや文に合致する企業、およびその企業の情報を取得できる。
strで指定する場合、公式docにあるkey
から指定でき、対応するvalue
のクエリを使用する。
もしくは事前に定義したクエリをそのまま使用できる。クエリの書き方もdocを参考。
・Example
import yfinance as yf
response = yf.screen("aggressive_small_caps")
・output
{'id': 'af57f75b-eb22-4565-a604-5eb8744dd35c',
'title': 'Aggresive small cap stocks',
'description': 'Small cap stocks with high earnings growth rates',
'canonicalName': 'AGGRESSIVE_SMALL_CAPS',
'criteriaMeta': {'size': 25,
'offset': 0,
'sortField': 'eodvolume',
'sortType': 'DESC',
'quoteType': 'EQUITY',
'criteria': [{'field': 'epsgrowth.lasttwelvemonths',
'subField': None,
'operators': ['GT'],
...
あまり使わなさそうな気がします。
特定の条件でソートした企業のみ分析するとか、その企業群から情報を抽出するとか、知識が増えてからのアドバンスドな前処理としての利用が主になりそうな雰囲気。
5. FundsData Class
FundsDataクラスは、ETFや投資信託に関する各種データを取得できる。
Yahoo Finance から取得したファンド関連の情報(例:資産配分、保有銘柄、運用概要など)を扱う。
ファンドのパフォーマンスに関しては、より詳細な「history」データが利用可能なため、専用モジュールとしては実装されていない。
・Class
class yfinance.scrapers.funds.FundsData(data: YfData, symbol: str, proxy=None)
・例
import yfinance as yf
from yfinance.scrapers.funds import FundsData
# Ticker オブジェクトを作成すると内部で YfData が生成される
ticker = yf.Ticker("SPY")
# 内部の YfData オブジェクトは通常、ticker._data で保持
yf_data = ticker._data # ※これは内部実装なので、通常は直接触る必要はない
# FundsData クラスに YfData オブジェクトとシンボルを渡して初期化
funds_data = FundsData(data=yf_data, symbol="SPY")
# ファンド概要
overview = funds_data.fund_overview
print("Fund Overview:", overview)
Attributes
-
asset_classes:
ファンドの資産クラス(例:株式、債券など)の割合を辞書形式 (Dict[str, float]
) で返す。 -
bond_holdings:
ファンドの債券保有情報を Pandas DataFrame として返す。 -
bond_ratings:
債券の評価情報(格付けなど)を辞書形式で返す。 -
description:
ファンドの説明文を文字列 (str
) で返す。 -
equity_holdings:
ファンドの株式保有情報を DataFrame として返す。 -
fund_operations:
ファンドの運用状況や取引履歴などの情報を DataFrame として返す。 -
fund_overview:
ファンドの概要情報(運用方針、費用構造など)を辞書形式 (Dict[str, Optional[str]]
) で返す。 -
sector_weightings:
セクター別のウェイト(比率)を辞書形式で返す。 -
top_holdings:
ファンドが保有する上位銘柄の情報を DataFrame として返す。
Methods
-
quote_type() → str
ファンドの種類(例:ETF やミューチュアルファンドなど)を示す文字列を返します。
description
, overview
, sector_weightings
, top_holdings
, quote_type()
は利用できそうな雰囲気。
6. PriceHistory Class
・Class
class yfinance.scrapers.history.PriceHistory(data, ticker, tz, session=None, proxy=None)
・例
import yfinance as yf
from yfinance.data import YfData
from yfinance.scrapers.history import PriceHistory
# YfData インスタンスを明示的に作成 (通常はTickerオブジェクト作成時に内部で自動作成される)
data_instance = YfData(session=None)
ticker_symbol = "AAPL"
timezone = "US/Eastern"
# PriceHistory クラスのインスタンスを生成する際に、data_instance を data 引数として渡す
price_history = PriceHistory(data_instance, ticker_symbol, timezone)
# 過去1ヶ月分の歴史的株価データを取得
history_df = price_history.history(period="1mo")
display(history_df)
・output
Open High Low Close Volume Dividends Stock Splits
Date
2025-01-13 00:00:00-05:00 233.273523 234.412271 229.467710 234.142563 49630700 0.00 0.0
2025-01-14 00:00:00-05:00 234.492175 235.860666 232.214681 233.023788 39435300 0.00 0.0
2025-01-15 00:00:00-05:00 234.382301 238.697564 234.172525 237.608749 39832000 0.00 0.0
Methods
- get_actions(proxy=None) → Series
- get_capital_gains(proxy=None) → Series
- get_dividends(proxy=None) → Series
- get_history_metadata(proxy=None) → dict
- get_splits(proxy=None) → Series
- history(period='1mo', interval='1d', start=None, end=None, prepost=False, actions=True, auto_adjust=True, back_adjust=False, repair=False, keepna=False, proxy=None, rounding=False, timeout=10, raise_errors=False) → DataFrame
基本的に、Tickerクラスで利用できるものと同じなので、詳細はTicker編を見ていただくと良いと思います。
・PriceHistory Classについて
PriceHistoryクラスの機能はほとんどがTicker.history()で利用することができるため、データをDataFrameではなく個別のSeriesとして取得したい場合や、クラスの継承によるカスタマイズ、より明示的にコーディングしたい場合を除き、使わなくても良いのではないかと思います。
今回はここまでです。
読んでいただきありがとうございます。
References
[1] 公式ドキュメント
Discussion