yfinance基本面分析:财务报表分析和估值模型
还在为获取上市公司财务数据而烦恼吗?yfinance作为Python生态中最强大的金融数据获取库,提供了完整的财务报表分析和估值建模能力。本文将深入解析如何使用yfinance进行专业的基本面分析,从财务报表提取到估值模型构建,一文解决你的投资分析需求。
读完本文你能得到
- ✅ 掌握yfinance财务报表数据获取的完整方法
- ✅ 学会三大财务报表(利润表、资产负债表、现金流量表)的分析技巧
- ✅ 构建专业的财务比率分析体系
- ✅ 实现基于财务数据的估值模型
- ✅ 获得完整的Python代码示例和实战案例
yfinance财务报表数据获取
基础配置与安装
首先确保安装yfinance库:
pip install yfinance pandas numpy matplotlib
获取完整财务报表数据
yfinance提供了丰富的财务报表接口,支持年度和季度数据:
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
# 创建股票对象
ticker = yf.Ticker("MSFT") # 微软公司
# 获取三大财务报表
income_stmt = ticker.income_stmt # 利润表
balance_sheet = ticker.balance_sheet # 资产负债表
cash_flow = ticker.cash_flow # 现金流量表
# 获取季度数据
quarterly_income = ticker.quarterly_income_stmt
quarterly_balance = ticker.quarterly_balance_sheet
quarterly_cashflow = ticker.quarterly_cash_flow
print("利润表结构:")
print(income_stmt.head())
print("\n资产负债表结构:")
print(balance_sheet.head())
print("\n现金流量表结构:")
print(cash_flow.head())
财务报表深度分析
利润表关键指标分析
def analyze_income_statement(income_df):
"""利润表深度分析"""
analysis = {}
# 收入增长分析
revenue = income_df.loc['Total Revenue']
analysis['revenue_growth'] = revenue.pct_change().dropna() * 100
# 盈利能力分析
gross_profit = income_df.loc['Gross Profit']
net_income = income_df.loc['Net Income']
analysis['gross_margin'] = (gross_profit / revenue) * 100
analysis['net_margin'] = (net_income / revenue) * 100
# 运营效率分析
operating_income = income_df.loc['Operating Income']
analysis['operating_margin'] = (operating_income / revenue) * 100
return pd.DataFrame(analysis)
# 执行利润表分析
income_analysis = analyze_income_statement(income_stmt)
print("利润表分析结果:")
print(income_analysis)
资产负债表健康度评估
def analyze_balance_sheet(balance_df):
"""资产负债表健康度分析"""
analysis = {}
total_assets = balance_df.loc['Total Assets']
total_liabilities = balance_df.loc['Total Liabilities Net Minority Interest']
total_equity = balance_df.loc['Total Equity Gross Minority Interest']
# 财务杠杆比率
analysis['debt_to_equity'] = (total_liabilities / total_equity) * 100
analysis['debt_to_assets'] = (total_liabilities / total_assets) * 100
# 流动性比率
current_assets = balance_df.loc['Current Assets']
current_liabilities = balance_df.loc['Current Liabilities']
analysis['current_ratio'] = current_assets / current_liabilities
# 营运资本
analysis['working_capital'] = current_assets - current_liabilities
return pd.DataFrame(analysis)
balance_analysis = analyze_balance_sheet(balance_sheet)
print("资产负债表分析结果:")
print(balance_analysis)
现金流量表质量分析
def analyze_cash_flow(cashflow_df):
"""现金流量表质量分析"""
analysis = {}
operating_cashflow = cashflow_df.loc['Operating Cash Flow']
investing_cashflow = cashflow_df.loc['Investing Cash Flow']
financing_cashflow = cashflow_df.loc['Financing Cash Flow']
free_cashflow = cashflow_df.loc['Free Cash Flow']
# 现金流质量指标
analysis['cash_flow_margin'] = (operating_cashflow / income_stmt.loc['Total Revenue']) * 100
analysis['fcf_to_revenue'] = (free_cashflow / income_stmt.loc['Total Revenue']) * 100
# 现金流结构分析
total_cashflow = operating_cashflow + investing_cashflow + financing_cashflow
analysis['operating_cash_ratio'] = (operating_cashflow / total_cashflow.abs()) * 100
return pd.DataFrame(analysis)
cashflow_analysis = analyze_cash_flow(cash_flow)
print("现金流量表分析结果:")
print(cashflow_analysis)
财务比率分析体系
盈利能力比率
def profitability_ratios(income_df, balance_df):
"""盈利能力比率分析"""
ratios = {}
revenue = income_df.loc['Total Revenue']
net_income = income_df.loc['Net Income']
total_assets = balance_df.loc['Total Assets']
total_equity = balance_df.loc['Total Equity Gross Minority Interest']
# 核心盈利能力指标
ratios['roa'] = (net_income / total_assets) * 100 # 总资产收益率
ratios['roe'] = (net_income / total_equity) * 100 # 净资产收益率
ratios['gross_margin'] = (income_df.loc['Gross Profit'] / revenue) * 100
ratios['operating_margin'] = (income_df.loc['Operating Income'] / revenue) * 100
ratios['net_margin'] = (net_income / revenue) * 100
return pd.DataFrame(ratios)
profit_ratios = profitability_ratios(income_stmt, balance_sheet)
偿债能力比率
def solvency_ratios(balance_df, income_df):
"""偿债能力比率分析"""
ratios = {}
total_debt = balance_df.loc['Total Debt']
total_equity = balance_df.loc['Total Equity Gross Minority Interest']
ebit = income_df.loc['Operating Income'] # 息税前利润
# 杠杆比率
ratios['debt_to_equity'] = (total_debt / total_equity) * 100
ratios['debt_to_assets'] = (total_debt / balance_df.loc['Total Assets']) * 100
ratios['interest_coverage'] = ebit / income_df.loc['Interest Expense']
return pd.DataFrame(ratios)
solvency_ratios = solvency_ratios(balance_sheet, income_stmt)
营运能力比率
def efficiency_ratios(income_df, balance_df):
"""营运能力比率分析"""
ratios = {}
revenue = income_df.loc['Total Revenue']
cogs = income_df.loc['Cost Of Revenue']
inventory = balance_df.loc['Inventory']
receivables = balance_df.loc['Accounts Receivable']
# 营运效率指标
ratios['asset_turnover'] = revenue / balance_df.loc['Total Assets']
ratios['inventory_turnover'] = cogs / inventory
ratios['receivables_turnover'] = revenue / receivables
ratios['days_sales_outstanding'] = 365 / ratios['receivables_turnover']
return pd.DataFrame(ratios)
efficiency_ratios = efficiency_ratios(income_stmt, balance_sheet)
估值模型构建
相对估值模型
def relative_valuation(ticker_obj, peers):
"""相对估值模型"""
valuation = {}
# 获取当前股票信息
info = ticker_obj.info
current_pe = info.get('trailingPE')
current_pb = info.get('priceToBook')
# 获取同行业公司估值
peer_valuations = []
for peer in peers:
peer_ticker = yf.Ticker(peer)
peer_info = peer_ticker.info
peer_valuations.append({
'ticker': peer,
'pe': peer_info.get('trailingPE'),
'pb': peer_info.get('priceToBook')
})
peer_df = pd.DataFrame(peer_valuations)
# 计算相对估值
valuation['pe_vs_peer_avg'] = current_pe / peer_df['pe'].mean()
valuation['pb_vs_peer_avg'] = current_pb / peer_df['pb'].mean()
return valuation, peer_df
# 科技股同行业公司
tech_peers = ['AAPL', 'GOOGL', 'AMZN', 'META', 'NVDA']
relative_val, peer_data = relative_valuation(ticker, tech_peers)
绝对估值模型(现金流折现模型)
def dcf_valuation(ticker_obj, discount_rate=0.1, growth_rate=0.03, terminal_growth=0.02):
"""现金流折现估值模型"""
# 获取财务数据
cashflow = ticker_obj.cash_flow.loc['Free Cash Flow']
latest_fcf = cashflow.iloc[0]
# 估算未来5年自由现金流
forecast_years = 5
forecast_cashflows = []
for year in range(1, forecast_years + 1):
forecast_fcf = latest_fcf * (1 + growth_rate) ** year
discounted_fcf = forecast_fcf / (1 + discount_rate) ** year
forecast_cashflows.append(discounted_fcf)
# 计算终值
terminal_fcf = forecast_cashflows[-1] * (1 + terminal_growth)
terminal_value = terminal_fcf / (discount_rate - terminal_growth)
discounted_terminal = terminal_value / (1 + discount_rate) ** forecast_years
# 计算企业价值
enterprise_value = sum(forecast_cashflows) + discounted_terminal
# 获取当前信息
info = ticker_obj.info
cash = info.get('totalCash', 0)
debt = info.get('totalDebt', 0)
# 计算股权价值
equity_value = enterprise_value - debt + cash
shares_outstanding = info.get('sharesOutstanding', 1)
# 计算每股价值
intrinsic_value = equity_value / shares_outstanding
current_price = info.get('currentPrice', 0)
return {
'intrinsic_value': intrinsic_value,
'current_price': current_price,
'margin_of_safety': (intrinsic_value - current_price) / intrinsic_value * 100,
'enterprise_value': enterprise_value,
'equity_value': equity_value
}
dcf_result = dcf_valuation(ticker)
print("DCF估值结果:")
print(dcf_result)
财务数据可视化分析
财务趋势图表
def plot_financial_trends(ticker_obj):
"""财务趋势可视化"""
fig, axes = plt.subplots(2, 2, figsize=(15, 10))
# 收入与利润趋势
income = ticker_obj.income_stmt
revenue = income.loc['Total Revenue']
net_income = income.loc['Net Income']
axes[0, 0].plot(revenue.index, revenue.values, 'b-', label='Revenue')
axes[0, 0].plot(net_income.index, net_income.values, 'r-', label='Net Income')
axes[0, 0].set_title('Revenue vs Net Income Trend')
axes[0, 0].legend()
axes[0, 0].grid(True)
# 利润率趋势
gross_margin = (income.loc['Gross Profit'] / revenue) * 100
net_margin = (net_income / revenue) * 100
axes[0, 1].plot(gross_margin.index, gross_margin.values, 'g-', label='Gross Margin')
axes[0, 1].plot(net_margin.index, net_margin.values, 'orange', label='Net Margin')
axes[0, 1].set_title('Profit Margin Trend (%)')
axes[0, 1].legend()
axes[0, 1].grid(True)
# 现金流趋势
cashflow = ticker_obj.cash_flow
operating_cf = cashflow.loc['Operating Cash Flow']
free_cf = cashflow.loc['Free Cash Flow']
axes[1, 0].plot(operating_cf.index, operating_cf.values, 'purple', label='Operating CF')
axes[1, 0].plot(free_cf.index, free_cf.values, 'cyan', label='Free CF')
axes[1, 0].set_title('Cash Flow Trend')
axes[1, 0].legend()
axes[1, 0].grid(True)
# ROE与ROA趋势
balance = ticker_obj.balance_sheet
roe = (net_income / balance.loc['Total Equity Gross Minority Interest']) * 100
roa = (net_income / balance.loc['Total Assets']) * 100
axes[1, 1].plot(roe.index, roe.values, 'brown', label='ROE')
axes[1, 1].plot(roa.index, roa.values, 'pink', label='ROA')
axes[1, 1].set_title('Return on Equity & Assets (%)')
axes[1, 1].legend()
axes[1, 1].grid(True)
plt.tight_layout()
plt.show()
plot_financial_trends(ticker)
财务比率雷达图
def plot_financial_radar(ratios_df):
"""财务比率雷达图"""
categories = list(ratios_df.columns)
values = ratios_df.iloc[0].values.tolist()
values += values[:1] # 闭合雷达图
angles = np.linspace(0, 2*np.pi, len(categories), endpoint=False).tolist()
angles += angles[:1]
fig, ax = plt.subplots(figsize=(8, 8), subplot_kw=dict(polar=True))
ax.plot(angles, values, 'o-', linewidth=2)
ax.fill(angles, values, alpha=0.25)
ax.set_thetagrids(np.degrees(angles[:-1]), categories)
ax.set_title('Financial Ratios Radar Chart', size=16, y=1.1)
ax.grid(True)
plt.show()
# 选择关键比率绘制雷达图
key_ratios = profit_ratios[['roa', 'roe', 'net_margin']].join(
solvency_ratios[['debt_to_equity']]).join(
efficiency_ratios[['asset_turnover']])
plot_financial_radar(key_ratios)
完整的财务分析流水线
class FinancialAnalyzer:
"""完整的财务分析流水线"""
def __init__(self, ticker_symbol):
self.ticker = yf.Ticker(ticker_symbol)
self.income_stmt = self.ticker.income_stmt
self.balance_sheet = self.ticker.balance_sheet
self.cash_flow = self.ticker.cash_flow
self.info = self.ticker.info
def comprehensive_analysis(self):
"""执行全面财务分析"""
analysis = {}
# 盈利能力分析
analysis['profitability'] = profitability_ratios(self.income_stmt, self.balance_sheet)
# 偿债能力分析
analysis['solvency'] = solvency_ratios(self.balance_sheet, self.income_stmt)
# 营运能力分析
analysis['efficiency'] = efficiency_ratios(self.income_stmt, self.balance_sheet)
# 现金流分析
analysis['cashflow'] = analyze_cash_flow(self.cash_flow)
# 估值分析
analysis['dcf_valuation'] = dcf_valuation(self.ticker)
return analysis
def generate_report(self):
"""生成财务分析报告"""
analysis = self.comprehensive_analysis()
report = f"""
Financial Analysis Report for {self.ticker.ticker}
{'='*50}
1. Profitability Analysis:
{analysis['profitability'].to_string()}
2. Solvency Analysis:
{analysis['solvency'].to_string()}
3. Efficiency Analysis:
{analysis['efficiency'].to_string()}
4. Cash Flow Analysis:
{analysis['cashflow'].to_string()}
5. DCF Valuation:
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考



