投資のためのデータサイエンス

個人の投資活動に役立つデータ分析にまつわる話題を綴ります。

Yahoo Finaceからのデータの取得と分析

(補足)日本の株価データを参照する場合は、4ケタのコードの後ろに「.T」をつけた文字列をシンボルとして指定します。これはライブラリyfinanceでもyahooqueryでも同じです。

投資のためのデータ分析をするにあたり、まず以下の書籍を参考にすることとした。

Satoshi著「Pythonで米国株をデータ分析:-40%ルール、PSR、株価成長率を見ていこう- (Amazon Kindle)

この書籍ではYahoo Financeからのデータの取得に"yahoo_fin"というライブラリを用いている。しかしこのライブラリは最近更新されておらず、本で参照されているコードはエラーで動かない。webサイトでこのライブラリの代替として紹介されているもののうち"yfinance"というライブラリを試してみたが、これも過去の株価データ参照はできるものの、財務諸表の取得などはエラーでできない。もう一つ紹介されているのが"yahooquery"というライブラリである。これは現状(2023年4月末)で全ての機能がエラーなく動く。以下はこの"yahooquery"の使い方に関するメモである。

リンク先のサイトにはドキュメント・デモなどへのリンクが掲載されている。まず、Pythonの然るべき環境にyahooqueryをインストールする。私の場合はWindowsPCに最新のAnacondaをインストールし、Anaconda promptで「$ pip install yahooquery」を実行した。

次にPythonコードを記述する。まず、ライブラリをインポートする:

# ライブラリのインポート
import numpy as np
import pandas as pd
from yahooquery import Ticker

次に、分析したい銘柄のティッカーコードを指定してTickerクラスを呼び出す:

# 米国アマゾン社を指定
ticker = Ticker('amzn')

Tickerクラスで利用可能なモジュールを調べる:

# View available modules on the Ticker class
cmodule = [i for i in Ticker.__dict__.keys() 
 if "_" not in i[:2] ]
print(cmodule)

結果は以下のようになる:
['all_modules', 'get_modules', 'asset_profile', 'calendar_events', 'earnings', 'earnings_trend', 'esg_scores', 'financial_data', 'news', 'index_trend', 'industry_trend', 'key_stats', 'major_holders', 'page_views', 'price', 'quote_type', 'quotes', 'recommendations', 'share_purchase_activity', 'summary_detail', 'summary_profile', 'technical_insights', 'all_financial_data', 'get_financial_data', 'corporate_events', 'corporate_guidance', 'valuation_measures', 'balance_sheet', 'cash_flow', 'company_officers', 'earning_history', 'fund_ownership', 'grading_history', 'income_statement', 'insider_holders', 'insider_transactions', 'institution_ownership', 'recommendation_trend', 'sec_filings', 'fund_bond_holdings', 'fund_category_holdings', 'fund_equity_holdings', 'fund_performance', 'fund_profile', 'fund_holding_info', 'fund_top_holdings', 'fund_bond_ratings', 'fund_sector_weightings', 'dividend_history', 'history', 'option_chain']

次に、四半期の損益計算書を出力してみる:

ticker.income_statement('q') # 四半期の損益計算書

以下の表が出力される(表の列は右側に続いている):

次に、株価の時系列データを出力してみる:

# 株価の時系列データ
ticker.history(start='2019-05-01')  # デフォルトの終了日は現在

以下のデータフレームが生成される:

列"close"を折れ線グラフにしてみる:

ticker.history(start='2019-05-01').close.plot()

以下の図が出力される: