使用 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())

显示在 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())
    

显示不同行业各年份平均流动比率,已追加到 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 分析财务报表

Passons à la pratique !

用 Python 分析财务报表

Preparing Video For Download...