損したくない人必見!Python yfinanceで財務情報を取得する方法|データ収集と投資分析

Pythonのyfinanceは、企業の詳細な財務データを取得できる便利なライブラリです。
この記事では、収益、純利益、キャッシュフロー、時価総額、PER、PBRなどのデータを収集する具体的な方法について解説します。

Code(コード)セクション

yfinanceを使用して企業の財務情報を収集する方法をサンプルコードで紹介します。収益、純利益、キャッシュフロー、時価総額、PER、PBRといった財務指標を含む情報の取得方法です。

yfinanceのインストールとインポート

まず、yfinanceをインストールし、Pythonコードにインポートします。

pip install yfinance
import yfinance as yf

単一銘柄の基本的な財務データの取得

損益計算書の取得

損益計算書(Income Statement)は、企業の収益や費用、利益を示す重要な財務諸表です。`yfinance`ライブラリを使用して簡単に取得できます。以下は、Apple(AAPL)の損益計算書を取得するコードです。

import yfinance as yf
# ティッカーシンボルを指定してデータを取得
ticker = yf.Ticker("AAPL")
# 損益計算書を取得
income_statement = ticker.financials
# 損益計算書を表示
print("損益計算書:")
print(income_statement)
  • 売上総利益(Gross Profit)

    売上総利益は総収益(売上高)から売上原価を差し引いたもので、企業の収益性を示す指標です。

    計算式: 売上総利益 = 総収益 - 売上原価

    import yfinance as yf
    # ティッカーシンボルを指定
    ticker = yf.Ticker("AAPL")
    # 総収益と売上原価を取得
    total_revenue = ticker.financials.loc['Total Revenue'][0]
    cost_of_revenue = ticker.financials.loc['Cost Of Revenue'][0]
    # 売上総利益の計算
    gross_profit = total_revenue - cost_of_revenue
    print("売上総利益:", gross_profit)
  • 営業利益(Operating Income)

    営業利益は、売上総利益から営業費用を引いたもので、企業の本業による利益を示します。

    計算式: 営業利益 = 売上総利益 - 営業費用

    # 売上総利益と営業費用を取得
    operating_expense = ticker.financials.loc['Operating Expense'][0]
    # 営業利益の計算
    operating_income = gross_profit - operating_expense
    print("営業利益:", operating_income)
  • 税引前利益(Net Income Before Taxes)

    税引前利益は、営業利益から支払利息を差し引いた後の利益です。

    計算式: 税引前利益 = 営業利益 - 支払利息

    # 支払利息を取得
    interest_expense = ticker.financials.loc['Interest Expense'][0]
    # 税引前利益の計算
    net_income_before_taxes = operating_income - interest_expense
    print("税引前利益:", net_income_before_taxes)
  • 純利益(Net Income)

    純利益は、税引前利益から法人税を差し引いたもので、企業の最終的な利益を示します。

    計算式: 純利益 = 税引前利益 - 法人税

    # 法人税を取得
    income_tax_expense = ticker.financials.loc['Income Tax Expense'][0]
    # 純利益の計算
    net_income = net_income_before_taxes - income_tax_expense
    print("純利益:", net_income)
  • EBITDA(利払い・税金・減価償却前営業利益)

    EBITDAは、企業のキャッシュフローを見るために利用される指標で、利息、税金、減価償却費を加えた利益です。

    計算式: EBITDA = 営業利益 + 減価償却費 + 支払利息

    # 減価償却費と支払利息を取得
    depreciation_amortization = ticker.financials.loc['Depreciation & Amortization'][0]
    # EBITDAの計算
    ebitda = operating_income + depreciation_amortization + interest_expense
    print("EBITDA:", ebitda)
  • 1株当たり利益(EPS)

    EPSは、純利益を発行済株式数で割ったもので、1株あたりの収益力を示します。

    計算式: EPS = 純利益 / 発行済株式数

    # 発行済株式数を取得
    shares_outstanding = ticker.info['sharesOutstanding']
    # EPSの計算
    eps = net_income / shares_outstanding
    print("1株当たり利益 (EPS):", eps)

貸借対照表の取得

貸借対照表(Balance Sheet)は、企業の資産、負債、純資産を示す財務諸表です。以下のコードを使って、貸借対照表データを取得できます。

# 貸借対照表を取得
balance_sheet = ticker.balance_sheet
# 貸借対照表を表示
print("貸借対照表:")
print(balance_sheet)
  • 総資産(Total Assets)

    総資産は、企業が保有するすべての資産の合計を表します。

    import yfinance as yf
    # ティッカーシンボルを指定
    ticker = yf.Ticker("AAPL")
    # 貸借対照表から総資産を取得
    total_assets = ticker.balance_sheet.loc['Total Assets'][0]
    print("総資産:", total_assets)
  • 総負債(Total Liabilities)

    総負債は、企業が負っているすべての負債の合計を表します。

    # 貸借対照表から総負債を取得
    total_liabilities = ticker.balance_sheet.loc['Total Liabilities'][0]
    print("総負債:", total_liabilities)
  • 株主資本(Total Stockholder Equity)

    株主資本は、企業の純資産であり、総資産から総負債を差し引いたものです。

    計算式: 株主資本 = 総資産 - 総負債

    # 貸借対照表から株主資本を取得
    stockholder_equity = ticker.balance_sheet.loc['Total Stockholder Equity'][0]
    print("株主資本:", stockholder_equity)
  • 現金および現金同等物(Cash And Cash Equivalents)

    企業がすぐに利用できる現金や、短期間で現金化できる資産の合計です。

    # 貸借対照表から現金および現金同等物を取得
    cash_and_cash_equivalents = ticker.balance_sheet.loc['Cash And Cash Equivalents'][0]
    print("現金および現金同等物:", cash_and_cash_equivalents)
  • 売掛金(Net Receivables)

    売掛金は、企業が顧客に対して持っている未回収の売上債権を示します。

    # 貸借対照表から売掛金を取得
    net_receivables = ticker.balance_sheet.loc['Net Receivables'][0]
    print("売掛金:", net_receivables)
  • 棚卸資産(Inventory)

    棚卸資産は、販売のために保有している商品や原材料などの資産です。

    # 貸借対照表から棚卸資産を取得
    inventory = ticker.balance_sheet.loc['Inventory'][0]
    print("棚卸資産:", inventory)
  • 短期負債(Current Liabilities)

    短期負債は、1年以内に支払う必要のある負債の合計です。

    # 貸借対照表から短期負債を取得
    current_liabilities = ticker.balance_sheet.loc['Current Liabilities'][0]
    print("短期負債:", current_liabilities)
  • 長期負債(Long Term Debt)

    長期負債は、1年以上の返済期間がある負債の合計です。

    # 貸借対照表から長期負債を取得
    long_term_debt = ticker.balance_sheet.loc['Long Term Debt'][0]
    print("長期負債:", long_term_debt)
  • 純資産(Net Assets)

    純資産は、総資産から総負債を引いたものです。これは企業の純粋な資産額を示します。

    計算式: 純資産 = 総資産 - 総負債

    # 純資産の計算
    net_assets = total_assets - total_liabilities
    print("純資産:", net_assets)

キャッシュフロー計算書の取得

キャッシュフロー計算書(Cash Flow Statement)は、企業の現金収支に関する情報を示します。以下のコードを使ってキャッシュフロー計算書を取得します。

# キャッシュフロー計算書を取得
cash_flow = ticker.cashflow
# キャッシュフロー計算書を表示
print("キャッシュフロー計算書:")
print(cash_flow)
  • 営業活動によるキャッシュフロー(Operating Cash Flow)

    企業の営業活動から得られた現金収支で、コアなビジネスによるキャッシュフローを示します。

    import yfinance as yf
    # ティッカーシンボルを指定
    ticker = yf.Ticker("AAPL")
    # キャッシュフロー計算書から営業活動によるキャッシュフローを取得
    operating_cash_flow = ticker.cashflow.loc['Operating Cash Flow'][0]
    print("営業活動によるキャッシュフロー:", operating_cash_flow)
  • 投資活動によるキャッシュフロー(Investing Cash Flow)

    投資活動(例:設備投資や資産売却)による現金収支を示します。

    # キャッシュフロー計算書から投資活動によるキャッシュフローを取得
    investing_cash_flow = ticker.cashflow.loc['Investing Cash Flow'][0]
    print("投資活動によるキャッシュフロー:", investing_cash_flow)
  • 財務活動によるキャッシュフロー(Financing Cash Flow)

    財務活動(例:株式発行や借入金の返済)による現金収支を示します。

    # キャッシュフロー計算書から財務活動によるキャッシュフローを取得
    financing_cash_flow = ticker.cashflow.loc['Financing Cash Flow'][0]
    print("財務活動によるキャッシュフロー:", financing_cash_flow)
  • キャッシュフローの純増減(Net Cash Flow)

    営業活動、投資活動、財務活動のキャッシュフローの合計で、期間内のキャッシュフローの純増減を示します。

    計算式: キャッシュフローの純増減 = 営業活動によるキャッシュフロー + 投資活動によるキャッシュフロー + 財務活動によるキャッシュフロー

    # キャッシュフローの純増減の計算
    net_cash_flow = operating_cash_flow + investing_cash_flow + financing_cash_flow
    print("キャッシュフローの純増減:", net_cash_flow)
  • 資本的支出(Capital Expenditures)

    企業が設備や資産に投資するために支出した費用を示します。

    # キャッシュフロー計算書から資本的支出を取得
    capital_expenditures = ticker.cashflow.loc['Capital Expenditures'][0]
    print("資本的支出:", capital_expenditures)
  • フリーキャッシュフロー(Free Cash Flow)

    営業活動によるキャッシュフローから資本的支出を差し引いたもので、企業が自由に使えるキャッシュフローを示します。

    計算式: フリーキャッシュフロー = 営業活動によるキャッシュフロー - 資本的支出

    # フリーキャッシュフローの計算
    free_cash_flow = operating_cash_flow - capital_expenditures
    print("フリーキャッシュフロー:", free_cash_flow)

Appleの収益や純利益の情報を取得する例です。

ticker = yf.Ticker("AAPL")
income_statement = ticker.financials
print("収益:", income_statement.loc["Total Revenue"])
print("純利益:", income_statement.loc["Net Income"])

時価総額、PER、PBRなどの財務指標の取得

株式投資に役立つ時価総額やPER、PBRの情報を取得します。

info = ticker.info
print("時価総額:", info["marketCap"])
print("PER:", info["trailingPE"])
print("PBR:", info["priceToBook"])

5. 取得したデータの整形・加工

Pandasと連携し、取得したデータを扱いやすいデータフレーム形式で整形します。

import pandas as pd
df = pd.DataFrame(ticker.financials)
print(df.T) # 行列を転置して見やすく表示

Use Case(ユースケース)セクション

yfinanceを使って企業の財務データを収集することが役立つシナリオを具体的に紹介します。投資分析における利用方法とデータの取得例を説明します。

1. 企業の財務状況や成長性の分析

企業の成長を判断するために、収益や純利益の推移を調べます。

income_statement = ticker.financials
print("収益の推移:", income_statement.loc["Total Revenue"])
print("純利益の推移:", income_statement.loc["Net Income"])

財務指標を定期的に収集し、投資判断をサポート

PER、PBRなどの指標を定期的に取得して監視し、投資判断のサポートに役立てる方法です。

info = ticker.info
print("時価総額:", info["marketCap"])
print("PER:", info["trailingPE"])
print("PBR:", info["priceToBook"])

PandasやMatplotlibとの連携

PandasやMatplotlibを使い、収益や純利益の推移を可視化します。

株価データの取得と可視化

# ティッカーシンボルの設定とデータ取得
ticker_symbol = "AAPL"
ticker = yf.Ticker(ticker_symbol)
# 過去1年間の株価データを取得
data = ticker.history(period="1y")
# 株価の終値をプロット
plt.figure(figsize=(10, 5))
plt.plot(data.index, data['Close'], label='終値')
plt.title("Appleの株価推移(過去1年)")
plt.xlabel("日付")
plt.ylabel("株価(USD)")
plt.legend()
plt.grid()
plt.show()

3. 売上成長率の計算とプロット

損益計算書から売上成長率を計算し、過去数年間の成長率を棒グラフでプロットします。

# 損益計算書のデータを取得
income_statement = ticker.financials
# 売上成長率の計算
revenue = income_statement.loc['Total Revenue']
revenue_growth = revenue.pct_change() * 100 # 前年比成長率(%)
# 売上成長率をプロット
plt.figure(figsize=(10, 5))
revenue_growth.plot(kind='bar', color='skyblue')
plt.title("Appleの売上成長率(前年比)")
plt.xlabel("会計年度")
plt.ylabel("売上成長率(%)")
plt.grid(axis='y')
plt.show()

4. 営業キャッシュフローとフリーキャッシュフローの比較

キャッシュフロー計算書から営業キャッシュフローとフリーキャッシュフローを取得し、折れ線グラフで比較します。

# キャッシュフロー計算書のデータを取得
cash_flow = ticker.cashflow
# 営業キャッシュフローとフリーキャッシュフローの抽出
operating_cash_flow = cash_flow.loc['Operating Cash Flow']
capital_expenditures = cash_flow.loc['Capital Expenditures']
free_cash_flow = operating_cash_flow + capital_expenditures
# 営業キャッシュフローとフリーキャッシュフローをプロット
plt.figure(figsize=(10, 5))
plt.plot(operating_cash_flow.index, operating_cash_flow, label="営業キャッシュフロー", marker='o')
plt.plot(free_cash_flow.index, free_cash_flow, label="フリーキャッシュフロー", marker='o')
plt.title("Appleのキャッシュフロー(過去数年)")
plt.xlabel("会計年度")
plt.ylabel("キャッシュフロー(USD)")
plt.legend()
plt.grid()
plt.show()

Information Type(取得可能な情報の種類)セクション

yfinanceで取得できる財務データの詳細な情報について、各情報タイプの具体例を挙げて説明します。

基本的な財務データ

収益や純利益などの企業財務情報を取得する方法です。

financials = ticker.financials
print("収益:", financials.loc["Total Revenue"])
print("純利益:", financials.loc["Net Income"])

拡張的な財務指標

時価総額、PER、PBRなど、企業の価値や投資判断に役立つデータも取得できます。

info = ticker.info
print("時価総額:", info["marketCap"])
print("PER:", info["trailingPE"])
print("PBR:", info["priceToBook"])

特定期間のキャッシュフローや利益率

特定期間のキャッシュフローや利益率の推移を確認します。

cashflow = ticker.cashflow
print("営業キャッシュフロー:", cashflow.loc["Total Cash From Operating Activities"])
print("フリーキャッシュフロー:", cashflow.loc["Free Cash Flow"])

Steps(手順)セクション

yfinanceを用いた財務データの詳細情報の取得方法について、初心者でもわかりやすい手順を説明します。

yfinanceのインストール方法

yfinanceをインストールするには以下のコマンドを使用します。

pip install yfinance

まとめ

新NISAのスタートで投資に興味を持つ方も多いと思います。yfinanceは、企業の財務データを手軽に収集・分析できる強力なツールです。
本記事のサンプルコードを参考に、収益やキャッシュフローなどの詳細データを取得し、投資判断に役立ててください。

コメント

  1. nim he より:

    Hmm it looks like your website ate my first comment (it was extremely long) so I guess I’ll
    just sum it up what I wrote and say, I’m thoroughly enjoying your blog.
    I too am an aspiring blog blogger but I’m still new to everything.
    Do you have any tips for novice blog writers?

    I’d definitely appreciate it.

  2. yota より:

    Thank you for reading my blog! I really appreciate your first comment!

    I’m also a beginner at blogging, so I may not be able to give precise advice, but here are two things I’ve realized while writing my blog:

    1. Focus on one keyword per article
    Rather than trying to include multiple keywords in a single article in the hopes of ranking for various search terms, I’ve found that focusing on one keyword per article tends to be more effective for SEO. In fact, the articles I wrote with a single keyword in mind have ranked higher in search results.

    2. Don’t get too caught up in page views when starting out
    In the early stages of blogging, articles often don’t get evaluated quickly, don’t appear in top search results, and PV (page view) numbers may not grow as expected. However, this is simply a matter of waiting for Google’s crawlers to assess your content. Instead of worrying about PV numbers, I believe it’s important to focus on consistently writing and improving your articles.

    I look forward to staying connected! Let’s keep working hard together!

タイトルとURLをコピーしました