可视化
概述
可视化是财报分析的重要环节,将复杂的财务数据转化为直观的图表,帮助用户快速理解关键信息。
工具选择
| 工具 | 特点 | 适用场景 |
|---|---|---|
| Matplotlib | 基础、灵活 | 静态图表 |
| Plotly | 交互式 | Web 展示 |
| Seaborn | 美观、统计 | 数据分析 |
核心图表
1. 营收利润趋势图
python
import matplotlib.pyplot as plt
import pandas as pd
def plot_revenue_trend(financials):
"""绘制营收利润趋势图"""
fig, ax = plt.subplots(figsize=(10, 6))
years = financials.columns
revenue = financials.loc["Total Revenue"] / 1e9
profit = financials.loc["Net Income"] / 1e9
x = range(len(years))
ax.bar(x, revenue, label="营收", alpha=0.7)
ax.plot(x, profit, "ro-", label="净利润", linewidth=2)
ax.set_xlabel("年份")
ax.set_ylabel("金额(十亿美元)")
ax.set_title("营收与净利润趋势")
ax.legend()
plt.tight_layout()
return fig2. 财务指标雷达图
python
import numpy as np
def plot_radar_chart(metrics, title="财务指标雷达图"):
"""绘制财务指标雷达图"""
categories = list(metrics.keys())
values = list(metrics.values())
# 闭合图形
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_xticks(angles[:-1])
ax.set_xticklabels(categories)
ax.set_title(title)
return fig3. 同业对比柱状图
python
def plot_peer_comparison(df, metric, title):
"""同业对比柱状图"""
fig, ax = plt.subplots(figsize=(10, 6))
companies = df["公司"]
values = df[metric]
bars = ax.bar(companies, values, color=["#4CAF50", "#2196F3", "#FF9800", "#9C27B0"])
ax.set_ylabel(metric)
ax.set_title(title)
# 添加数值标签
for bar, val in zip(bars, values):
ax.text(bar.get_x() + bar.get_width()/2, bar.get_height(),
f"{val:.2f}", ha="center", va="bottom")
return figPlotly 交互图表
python
import plotly.graph_objects as go
def create_interactive_chart(financials):
"""创建交互式图表"""
fig = go.Figure()
fig.add_trace(go.Bar(
name="营收",
x=financials.columns,
y=financials.loc["Total Revenue"] / 1e9
))
fig.add_trace(go.Scatter(
name="净利润",
x=financials.columns,
y=financials.loc["Net Income"] / 1e9,
mode="lines+markers"
))
fig.update_layout(
title="财务趋势(交互式)",
xaxis_title="年份",
yaxis_title="金额(十亿美元)"
)
return fig报告导出
PDF 导出
python
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
def export_to_pdf(analysis_result, charts, output_path):
"""导出 PDF 报告"""
c = canvas.Canvas(output_path, pagesize=A4)
# 标题
c.setFont("Helvetica-Bold", 18)
c.drawString(50, 800, f"{analysis_result['company']} 财务分析报告")
# 内容
c.setFont("Helvetica", 12)
y = 750
for key, value in analysis_result.items():
c.drawString(50, y, f"{key}: {value}")
y -= 20
c.save()HTML 导出
python
def export_to_html(analysis, charts, output_path):
"""导出 HTML 报告"""
html_content = f"""
<!DOCTYPE html>
<html>
<head>
<title>{analysis['company']} 分析报告</title>
<style>
body {{ font-family: Arial; max-width: 800px; margin: 0 auto; }}
.metric {{ background: #f5f5f5; padding: 10px; margin: 10px 0; }}
</style>
</head>
<body>
<h1>{analysis['company']} 财务分析报告</h1>
<div class="metric">
<h3>财务健康评分: {analysis['health_score']}/100</h3>
</div>
<h2>投资建议</h2>
<p>{analysis['recommendation']}</p>
</body>
</html>
"""
with open(output_path, "w", encoding="utf-8") as f:
f.write(html_content)下一步
可视化完成,开始部署上线。