使用 pandas 計算財務比率

使用 Python 分析財務報表

Rohan Chatterjee

Risk Modeler

資產負債表資料結構

  • 已將資產負債表資料載入為 pandas 的 DataFrame,名稱為 balance_sheet

 


----CODE_GLUE----
```print(balance_sheet.head())

----CODE_GLUE---- ` 顯示名為 balance_sheet 的 DataFrame 前幾列的圖片。

使用 Python 分析財務報表

計算流動比率

balance_sheet["current_ratio"] = balance_sheet["Total Current Assets"] / 
                                 balance_sheet["Total Current Liabilities"]
print(balance_sheet.head())

顯示在 DataFrame balance_sheet 新增 current_ratio 欄位的圖片。

使用 Python 分析財務報表

用 .groupby() 取得分組結果

  • 取得各產業的平均流動比率:
    balance_sheet.groupby("comp_type")["current_ratio"].mean()
    
    顯示不同產業平均流動比率的圖片。
使用 Python 分析財務報表

用 .groupby() 取得分組結果

balance_sheet.groupby(["Year","comp_type"])["current_ratio"].mean()

顯示各年份各產業平均流動比率的圖片。

使用 Python 分析財務報表

使用 groupby().transform()

  • .transform() 可在 .groupby() 之後使用,依每列所屬群組,將分組結果回填到各列。
    balance_sheet["industry_curr_ratio"] = 
              balance_sheet.groupby([
              "Year","comp_type"])["current_ratio"].transform("mean")
    print(balance_sheet.head())
    

顯示各年份各產業平均流動比率,並已回填到 DataFrame balance_sheet 的圖片。

使用 Python 分析財務報表

使用 .groupby().transform()

balance_sheet["relative_diff"] = 
                            (balance_sheet["current_ratio"] / 
                             balance_sheet["industry_curr_ratio"]) - 1

顯示公司流動比率與其產業流動比率之相對差異的 DataFrame。

使用 Python 分析財務報表

使用 .isin()

  • 使用 .isin() 篩選要分析的資料。
  • 範例:篩出 2019 與 2020 年的 fmcgtech 公司:
fmcg_2019 = balance_sheet.loc[
            (balance_sheet["Year"].isin([2019,2020])) &
            (balance_sheet["comp_type"].isin(["tech","fmcg"]))
                            ]
使用 Python 分析財務報表

一起來練習吧!

使用 Python 分析財務報表

Preparing Video For Download...