aoi学院

Aisaka's Blog, School of Aoi, Aisaka University

Python-第12篇《制作你的第一个数据报告》

📖 开篇语

还记得你第一次向领导汇报财务数据的情景吗?

Excel表格做好了,但老板说:“这些数据我看不懂,给我做个图表!”
于是你开始学习插入图表、调整颜色、设置格式…
做完后发现:数据更新了,图表又要重新做一遍!

今天我们要学的,就是让Python帮你自动生成专业的数据报告。
数据更新了?运行一下代码,全新的报告就生成了!

你会发现:

  • 几行代码就能生成漂亮的图表
  • Excel能做的图表,Python都能做,而且更好看
  • 可以一键导出PDF、Excel、PPT等多种格式

🎯 今日学习目标

  • 学会用Python生成各种图表(柱状图、折线图、饼图)
  • 掌握数据报告的导出方法
  • 实战制作个人理财年度报告

📊 图表生成:让数据“可视化”

准备工作:安装必要的库

1
2
# 安装绘图库
pip install matplotlib seaborn openpyxl

创建示例数据:个人理财数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
from datetime import datetime, timedelta
import warnings
warnings.filterwarnings('ignore')

# 设置中文字体(解决中文显示问题)
plt.rcParams['font.sans-serif'] = ['SimHei'] # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False # 用来正常显示负号

# 创建2024年个人理财数据
print("=== 创建个人理财数据 ===")

# 生成12个月的收入和支出数据
月份列表 = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']

# 月度收入数据(工资+投资收益+其他)
月度收入 = pd.DataFrame({
'月份': 月份列表,
'工资收入': [15000, 15000, 15000, 15000, 15000, 15000, 15000, 15000, 15000, 15000, 15000, 15000],
'投资收益': [1200, 800, 1500, 2000, 1800, 2200, 2500, 1800, 1600, 2100, 1900, 2300],
'其他收入': [500, 300, 800, 600, 400, 700, 900, 500, 600, 800, 700, 1000],
'总收入': 0 # 待计算
})

# 计算总收入
月度收入['总收入'] = 月度收入[['工资收入', '投资收益', '其他收入']].sum(axis=1)

# 月度支出数据
月度支出 = pd.DataFrame({
'月份': 月份列表,
'生活费用': [6000, 5500, 5800, 6200, 5900, 6100, 6300, 6000, 5800, 6200, 6000, 6500],
'房租/房贷': [3500, 3500, 3500, 3500, 3500, 3500, 3500, 3500, 3500, 3500, 3500, 3500],
'交通费用': [800, 750, 820, 900, 780, 850, 920, 800, 760, 880, 820, 950],
'娱乐消费': [1200, 1000, 1500, 1800, 1300, 1600, 2000, 1400, 1200, 1700, 1500, 2200],
'学习培训': [500, 800, 600, 1200, 700, 900, 1100, 600, 800, 1000, 900, 1300],
'其他支出': [300, 200, 400, 500, 350, 450, 600, 350, 300, 500, 400, 700],
'总支出': 0 # 待计算
})

# 计算总支出
月度支出['总支出'] = 月度支出[['生活费用', '房租/房贷', '交通费用', '娱乐消费', '学习培训', '其他支出']].sum(axis=1)

# 计算月度结余
月度结余 = pd.DataFrame({
'月份': 月份列表,
'总收入': 月度收入['总收入'],
'总支出': 月度支出['总支出'],
'月度结余': 月度收入['总收入'] - 月度支出['总支出'],
'结余率': (月度收入['总收入'] - 月度支出['总支出']) / 月度收入['总收入'] * 100
})

print("✅ 个人理财数据创建完成!")
print("月度结余预览:")
print(月度结余.head())

基础图表制作(比Excel更专业)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
print("\n=== 基础图表制作 ===")

# 设置图表样式
plt.style.use('seaborn-v0_8') # 使用专业图表样式
sns.set_palette("husl") # 设置颜色方案

# 1. 月度收支折线图
plt.figure(figsize=(12, 6))
plt.plot(月度收入['月份'], 月度收入['总收入'], marker='o', linewidth=3, label='总收入', color='#2E8B57')
plt.plot(月度支出['月份'], 月度支出['总支出'], marker='s', linewidth=3, label='总支出', color='#DC143C')
plt.plot(月度结余['月份'], 月度结余['月度结余'], marker='^', linewidth=3, label='月度结余', color='#4169E1')

plt.title('2024年月度收支情况', fontsize=16, fontweight='bold', pad=20)
plt.xlabel('月份', fontsize=12)
plt.ylabel('金额(元)', fontsize=12)
plt.legend(fontsize=12)
plt.grid(True, alpha=0.3)
plt.xticks(rotation=45)

# 添加数值标签
for i, (月份, 收入, 支出, 结余) in enumerate(zip(月度收入['月份'], 月度收入['总收入'], 月度支出['总支出'], 月度结余['月度结余'])):
plt.annotate(f'{收入:,}', (i, 收入), textcoords="offset points", xytext=(0,10), ha='center', fontsize=9)
plt.annotate(f'{支出:,}', (i, 支出), textcoords="offset points", xytext=(0,-15), ha='center', fontsize=9)

plt.tight_layout()
plt.savefig('月度收支折线图.png', dpi=300, bbox_inches='tight')
plt.show()

print("✅ 月度收支折线图已生成!")

# 2. 支出分类柱状图
plt.figure(figsize=(12, 8))

# 准备数据
支出明细 = 月度支出.drop(['月份', '总支出'], axis=1)
支出分类 = 支出明细.sum().sort_values(ascending=False)

# 创建柱状图
bars = plt.bar(支出分类.index, 支出分类.values, color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3'])

# 添加数值标签
for bar, 数值 in zip(bars, 支出分类.values):
plt.annotate(f'{数值:,}', (bar.get_x() + bar.get_width()/2, bar.get_height() + 200),
ha='center', va='bottom', fontsize=11, fontweight='bold')

plt.title('2024年各类支出总额', fontsize=16, fontweight='bold', pad=20)
plt.xlabel('支出类别', fontsize=12)
plt.ylabel('支出金额(元)', fontsize=12)
plt.xticks(rotation=45, ha='right')

# 添加总计
总计 = 支出分类.sum()
plt.text(0.02, 0.98, f'总支出:{总计:,}元', transform=plt.gca().transAxes,
fontsize=12, fontweight='bold', verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='wheat', alpha=0.8))

plt.tight_layout()
plt.savefig('支出分类柱状图.png', dpi=300, bbox_inches='tight')
plt.show()

print("✅ 支出分类柱状图已生成!")

高级图表(Excel做不到的图表)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
print("\n=== 高级图表制作 ===")

# 3. 收入结构堆叠面积图
plt.figure(figsize=(12, 6))

# 准备堆叠数据
收入数据 = 月度收入[['月份', '工资收入', '投资收益', '其他收入']].set_index('月份')

# 创建堆叠面积图
plt.stackplot(收入数据.index,
收入_data['工资收入'],
收入_data['投资收益'],
收入_data['其他收入'],
labels=['工资收入', '投资收益', '其他收入'],
colors=['#3498DB', '#2ECC71', '#F39C12'],
alpha=0.8)

plt.title('2024年月度收入结构分析', fontsize=16, fontweight='bold', pad=20)
plt.xlabel('月份', fontsize=12)
plt.ylabel('收入金额(元)', fontsize=12)
plt.legend(loc='upper left', fontsize=11)
plt.grid(True, alpha=0.3)

# 添加总计标签
for i, 月份 in enumerate(收入数据.index):
总计 = 收入数据.iloc[i].sum()
plt.annotate(f'{总计:,}', (i, 总计), textcoords="offset points", xytext=(0,10),
ha='center', va='bottom', fontsize=9, fontweight='bold')

plt.tight_layout()
plt.savefig('收入结构堆叠图.png', dpi=300, bbox_inches='tight')
plt.show()

print("✅ 收入结构堆叠图已生成!")

# 4. 结余率仪表盘式图表
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 6))

# 左侧:结余率柱状图
bars = ax1.bar(月度结余['月份'], 月度结余['结余率'],
color=['#2ECC71' if x >= 20 else '#F39C12' if x >= 10 else '#E74C3C' for x in 月度结余['结余率']])

ax1.set_title('月度结余率', fontsize=14, fontweight='bold')
ax1.set_xlabel('月份', fontsize=12)
ax1.set_ylabel('结余率(%)', fontsize=12)
ax1.axhline(y=20, color='green', linestyle='--', alpha=0.7, label='目标结余率(20%)')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 添加数值标签
for bar, 数值 in zip(bars, 月度结余['结余率']):
ax1.annotate(f'{数值:.1f}%', (bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5),
ha='center', va='bottom', fontsize=10, fontweight='bold')

# 右侧:年度平均结余率饼图
年度平均结余率 = 月度结余['结余率'].mean()
其他占比 = 100 - 年度平均结余率

ax2.pie([年度平均结余率, 其他占比],
labels=[f'结余\n{年度平均结余率:.1f}%', f'支出\n{其他占比:.1f}%'],
colors=['#2ECC71', '#E74C3C'],
startangle=90,
autopct='')

ax2.set_title(f'年度平均结余率\n{年度平均结余率:.1f}%', fontsize=14, fontweight='bold')

# 根据结余率显示评价
if 年度平均结余率 >= 25:
评价 = "优秀 🏆"
颜色 = "#2ECC71"
elif 年度平均结余率 >= 20:
评价 = "良好 👍"
颜色 = "#F39C12"
elif 年度平均结余率 >= 15:
评价 = "一般 ⚠️"
颜色 = "#E67E22"
else:
评价 = "需改善 💔"
颜色 = "#E74C3C"

plt.figtext(0.5, 0.02, f'财务健康度:{评价}', ha='center', fontsize=16,
fontweight='bold', color=颜色, transform=fig.transFigure)

plt.tight_layout()
plt.savefig('结余率分析图.png', dpi=300, bbox_inches='tight')
plt.show()

print("✅ 结余率分析图已生成!")

热力图(专业财务分析图)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# 6. 月度收支热力图
plt.figure(figsize=(12, 8))

# 创建月度数据矩阵
月度数据 = pd.merge(月度收入, 月度支出, on='月份')
收支明细 = 月度数据.drop(['月份', '总收入', '总支出', '月度结余', '结余率'], axis=1)

# 转置数据以便绘制热力图
热力图数据 = 收支明细.T

# 创建热力图
sns.heatmap(热力图数据,
annot=True,
fmt='d',
cmap='RdYlGn_r', # 红-黄-绿色谱,红色表示高值
cbar_kws={'label': '金额(元)'},
linewidths=0.5)

plt.title('2024年月度收支热力图', fontsize=16, fontweight='bold', pad=20)
plt.xlabel('月份', fontsize=12)
plt.ylabel('收支项目', fontsize=12)
plt.xticks(rotation=0)
plt.yticks(rotation=0)

# 添加注释
plt.figtext(0.02, 0.02, '颜色越深表示金额越高', fontsize=10,
transform=plt.gca().transFigure, style='italic')

plt.tight_layout()
plt.savefig('月度收支热力图.png', dpi=300, bbox_inches='tight')
plt.show()

print("✅ 月度收支热力图已生成!")

💾 数据导出:多种格式输出

导出到Excel(最常用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
print("\n=== 数据导出 ===")

# 1. 导出到Excel
def 导出到Excel(数据字典, 文件名="个人理财报告.xlsx"):
"""将多个数据表导出到Excel文件"""

print(f"📊 正在导出到Excel:{文件名}...")

with pd.ExcelWriter(文件名, engine='openpyxl') as writer:
# 导出各个数据表
月度收入.to_excel(writer, sheet_name='月度收入', index=False)
月度支出.to_excel(writer, sheet_name='月度支出', index=False)
月度结余.to_excel(writer, sheet_name='月度结余', index=False)

# 创建汇总表
汇总表 = pd.DataFrame({
'项目': ['年度总收入', '年度总支出', '年度总结余', '平均月结余', '平均结余率'],
'金额': [
月度收入['总收入'].sum(),
月度支出['总支出'].sum(),
月度结余['月度结余'].sum(),
月度结余['月度结余'].mean(),
月度结余['结余率'].mean()
],
'单位': ['元', '元', '元', '元', '%']
})
汇总表.to_excel(writer, sheet_name='年度汇总', index=False)

# 创建年度对比表
年度对比 = pd.DataFrame({
'月份': 月度结余['月份'],
'收入': 月度收入['总收入'],
'支出': 月度支出['总支出'],
'结余': 月度结余['月度结余'],
'结余率': 月度结余['结余率']
})
年度对比.to_excel(writer, sheet_name='年度对比', index=False)

print("✅ Excel文件导出完成!")

# 使用函数导出
导出到Excel({
'月度收入': 月度收入,
'月度支出': 月度支出,
'月度结余': 月度结余
}, "个人理财报告_基础版.xlsx")

导出到CSV(通用格式)

1
2
3
4
5
6
7
8
9
10
# 2. 导出到CSV
def 导出到CSV(数据表, 文件名):
"""导出数据到CSV文件"""
数据表.to_csv(文件名, index=False, encoding='utf-8')
print(f"✅ CSV文件导出完成:{文件名}")

# 导出主要数据
导出到CSV(月度结余, "月度结余明细.csv")
导出到CSV(月度收入, "月度收入明细.csv")
导出到CSV(月度支出, "月度支出明细.csv")

导出到PDF(专业报告)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
# 3. 生成PDF报告
from matplotlib.backends.backend_pdf import PdfPages

def 生成PDF报告(文件名="个人理财年度报告.pdf"):
"""生成包含多个图表的PDF报告"""

print(f"📄 正在生成PDF报告:{文件名}...")

with PdfPages(文件名) as pdf:
# 第一页:封面
fig = plt.figure(figsize=(8.27, 11.69)) # A4尺寸
plt.text(0.5, 0.7, '个人理财年度报告', ha='center', va='center',
fontsize=32, fontweight='bold', transform=fig.transFigure)
plt.text(0.5, 0.5, f'2024年度财务分析报告', ha='center', va='center',
fontsize=20, transform=fig.transFigure)
plt.text(0.5, 0.3, f'生成时间:{datetime.now().strftime("%Y年%m月%d日")}',
ha='center', va='center', fontsize=14, transform=fig.transFigure)
plt.text(0.5, 0.2, f'年度总结余:{月度结余["月度结余"].sum():,.2f}元',
ha='center', va='center', fontsize=16, color='#2ECC71',
transform=fig.transFigure, fontweight='bold')
plt.axis('off')
pdf.savefig(fig, bbox_inches='tight')
plt.close()

# 第二页:收支总览
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(11.69, 8.27))

# 收支折线图
ax1.plot(月度收入['月份'], 月度收入['总收入'], marker='o', linewidth=3, label='总收入', color='#2E8B57')
ax1.plot(月度支出['月份'], 月度支出['总支出'], marker='s', linewidth=3, label='总支出', color='#DC143C')
ax1.set_title('月度收支情况', fontsize=14, fontweight='bold')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 收入饼图
年度收入结构 = 月度收入[['工资收入', '投资收益', '其他收入']].sum()
ax2.pie(年度收入结构.values, labels=年度收入结构.index, autopct='%1.1f%%', startangle=90)
ax2.set_title('年度收入结构', fontsize=14, fontweight='bold')

# 支出饼图
年度支出结构 = 月度支出.drop(['月份', '总支出'], axis=1).sum()
ax3.pie(年度支出结构.values, labels=年度支出结构.index, autopct='%1.1f%%', startangle=90)
ax3.set_title('年度支出结构', fontsize=14, fontweight='bold')

# 结余率柱状图
bars = ax4.bar(月度结余['月份'], 月度结余['结余率'],
color=['#2ECC71' if x >= 20 else '#F39C12' if x >= 10 else '#E74C3C' for x in 月度结余['结余率']])
ax4.set_title('月度结余率', fontsize=14, fontweight='bold')
ax4.axhline(y=20, color='green', linestyle='--', alpha=0.7, label='目标结余率')
ax4.legend()

plt.suptitle('2024年度财务总览', fontsize=18, fontweight='bold', y=0.95)
plt.tight_layout()
pdf.savefig(fig, bbox_inches='tight')
plt.close()

# 第三页:详细分析
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(11.69, 8.27))

# 月度结余趋势
ax1.bar(月度结余['月份'], 月度结余['月度结余'],
color=['#2ECC71' if x >= 0 else '#E74C3C' for x in 月度结余['月度结余']])
ax1.set_title('月度结余', fontsize=14, fontweight='bold')
ax1.axhline(y=0, color='black', linestyle='-', alpha=0.5)

# 收入堆叠图
收入数据 = 月度收入[['月份', '工资收入', '投资收益', '其他收入']].set_index('月份')
ax2.stackplot(收入数据.index, 收入数据['工资收入'], 收入数据['投资收益'], 收入数据['其他收入'],
labels=['工资收入', '投资收益', '其他收入'], alpha=0.8)
ax2.set_title('收入结构变化', fontsize=14, fontweight='bold')
ax2.legend(loc='upper left')

# 支出堆叠图
支出数据 = 月度支出[['月份', '生活费用', '房租/房贷', '交通费用', '娱乐消费', '学习培训', '其他支出']].set_index('月份')
ax3.stackplot(支出数据.index,
支出数据['生活费用'], 支出数据['房租/房贷'], 支出数据['交通费用'],
支出数据['娱乐消费'], 支出数据['学习培训'], 支出数据['其他支出'],
labels=['生活费用', '房租/房贷', '交通费用', '娱乐消费', '学习培训', '其他支出'], alpha=0.8)
ax3.set_title('支出结构变化', fontsize=14, fontweight='bold')
ax3.legend(loc='upper left', bbox_to_anchor=(1, 1))

# 热力图
收支明细 = 月度支出.drop(['月份', '总支出'], axis=1)
sns.heatmap(收支明细.T, annot=True, fmt='d', cmap='RdYlGn_r', ax=ax4, cbar_kws={'label': '金额(元)'})
ax4.set_title('月度支出热力图', fontsize=14, fontweight='bold')

plt.suptitle('2024年度财务详细分析', fontsize=16, fontweight='bold', y=0.95)
plt.tight_layout()
pdf.savefig(fig, bbox_inches='tight')
plt.close()

print("✅ PDF报告生成完成!")

# 生成PDF报告
生成PDF报告("个人理财年度报告_完整版.pdf")

版本1.0:基础年度报告
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
# 个人理财年度报告 - 基础版
print("=== 个人理财年度报告生成器 ===")

def 生成基础年报():
"""生成基础版年度报告"""

print("📊 开始生成基础年度报告...")

# 1. 计算年度关键指标
年度指标 = {
'年度总收入': 月度收入['总收入'].sum(),
'年度总支出': 月度支出['总支出'].sum(),
'年度总结余': 月度结余['月度结余'].sum(),
'平均月结余': 月度结余['月度结余'].mean(),
'平均结余率': 月度结余['结余率'].mean(),
'最高月结余': 月度结余['月度结余'].max(),
'最低月结余': 月度结余['月度结余'].min(),
'最高结余率': 月度结余['结余率'].max(),
'最低结余率': 月度结余['结余率'].min()
}

print("\n📈 年度财务概况:")
print(f" 年度总收入:{年度指标['年度总收入']:,}元")
print(f" 年度总支出:{年度指标['年度总支出']:,}元")
print(f" 年度总结余:{年度指标['年度总结余']:,}元")
print(f" 平均结余率:{年度指标['平均结余率']:.1f}%")

# 2. 生成年度分析报告
报告内容 = f"""
═══════════════════════════════════════════════════════════════
个人理财年度报告
2024年度
═══════════════════════════════════════════════════════════════

📊 年度财务概况
───────────────────────────────────────────────────────────────
• 年度总收入:{年度指标['年度总收入']:,}
• 年度总支出:{年度指标['年度总支出']:,}
• 年度总结余:{年度指标['年度总结余']:,}
• 平均月结余:{年度指标['平均月结余']:,.2f}
• 平均结余率:{年度指标['平均结余率']:.1f}%

📈 收入分析
───────────────────────────────────────────────────────────────
• 工资收入:{月度收入['工资收入'].sum():,}元(占比{月度收入['工资收入'].sum()/年度指标['年度总收入']*100:.1f}%)
• 投资收益:{月度收入['投资收益'].sum():,}元(占比{月度收入['投资收益'].sum()/年度指标['年度总收入']*100:.1f}%)
• 其他收入:{月度收入['其他收入'].sum():,}元(占比{月度收入['其他收入'].sum()/年度指标['年度总收入']*100:.1f}%)

💰 支出分析
───────────────────────────────────────────────────────────────
• 生活费用:{月度支出['生活费用'].sum():,}元(占比{月度支出['生活费用'].sum()/年度指标['年度总支出']*100:.1f}%)
• 房租/房贷:{月度支出['房租/房贷'].sum():,}元(占比{月度支出['房租/房贷'].sum()/年度指标['年度总支出']*100:.1f}%)
• 交通费用:{月度支出['交通费用'].sum():,}元(占比{月度支出['交通费用'].sum()/年度指标['年度总支出']*100:.1f}%)
• 娱乐消费:{月度支出['娱乐消费'].sum():,}元(占比{月度支出['娱乐消费'].sum()/年度指标['年度总支出']*100:.1f}%)
• 学习培训:{月度支出['学习培训'].sum():,}元(占比{月度支出['学习培训'].sum()/年度指标['年度总支出']*100:.1f}%)
• 其他支出:{月度支出['其他支出'].sum():,}元(占比{月度支出['其他支出'].sum()/年度指标['年度总支出']*100:.1f}%)

📊 结余情况
───────────────────────────────────────────────────────────────
• 最高月结余:{年度指标['最高月结余']:,}元({月度结余[月度结余['月度结余']==年度指标['最高月结余']]['月份'].values[0]}
• 最低月结余:{年度指标['最低月结余']:,}元({月度结余[月度结余['月度结余']==年度指标['最低月结余']]['月份'].values[0]}
• 最高结余率:{年度指标['最高结余率']:.1f}%({月度结余[月度结余['结余率']==年度指标['最高结余率']]['月份'].values[0]}
• 最低结余率:{年度指标['最低结余率']:.1f}%({月度结余[月度结余['结余率']==年度指标['最低结余率']]['月份'].values[0]}

💡 财务健康度评估
───────────────────────────────────────────────────────────────
"""

# 根据结余率评估财务健康度
if 年度指标['平均结余率'] >= 25:
健康评价 = "优秀 🏆"
建议 = "您的财务状况非常健康!建议继续保持良好的储蓄习惯,并考虑增加投资以实现财富增值。"
elif 年度指标['平均结余率'] >= 20:
健康评价 = "良好 👍"
建议 = "您的财务状况良好!建议继续保持,可以适当增加投资或应急储备。"
elif 年度指标['平均结余率'] >= 15:
健康评价 = "一般 ⚠️"
建议 = "您的财务状况一般,建议适当控制支出,提高储蓄率。"
else:
健康评价 = "需改善 💔"
建议 = "您的财务状况需要改善,建议详细分析支出结构,制定严格的预算计划。"

报告内容 += f"""
• 财务健康度:{健康评价}
• 平均结余率:{年度指标['平均结余率']:.1f}%

💰 理财建议
───────────────────────────────────────────────────────────────
{建议}

🎯 明年目标建议
───────────────────────────────────────────────────────────────
• 目标结余率:≥25%
• 建议增加投资收入占比
• 控制非必要支出
• 建立应急基金(6个月生活费)

📅 报告生成时间:{datetime.now().strftime('%Y年%m月%d日 %H:%M')}
═══════════════════════════════════════════════════════════════
"""

return 报告内容

# 生成基础报告
基础报告 = 生成基础年报()

# 保存到文件
with open("个人理财年度报告_基础版.txt", "w", encoding="utf-8") as f:
f.write(基础报告)

print("✅ 基础年度报告已生成:个人理财年度报告_基础版.txt")
版本2.0:可视化年度报告
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
# 可视化年度报告
print("\n=== 可视化年度报告 ===")

def 生成可视化年报():
"""生成包含丰富图表的年度报告"""

print("📊 开始生成可视化年度报告...")

# 创建大型图表组合
fig = plt.figure(figsize=(16, 12))

# 创建网格布局
gs = fig.add_gridspec(3, 3, hspace=0.3, wspace=0.3)

# 1. 年度收支总览(大图,占据2x2区域)
ax1 = fig.add_subplot(gs[0, :2])
ax1.plot(月度收入['月份'], 月度收入['总收入'], marker='o', linewidth=4,
label='总收入', color='#2E8B57', markersize=8)
ax1.plot(月度支出['月份'], 月度支出['总支出'], marker='s', linewidth=4,
label='总支出', color='#DC143C', markersize=8)
ax1.fill_between(月度收入['月份'], 月度收入['总收入'], alpha=0.3, color='#2E8B57')
ax1.fill_between(月度支出['月份'], 月度支出['总支出'], alpha=0.3, color='#DC143C')

# 添加年度总计
年度总收入 = 月度收入['总收入'].sum()
年度总支出 = 月度支出['总支出'].sum()
ax1.text(0.02, 0.98, f'年度总收入:{年度总收入:,}元', transform=ax1.transAxes,
fontsize=12, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.7))
ax1.text(0.02, 0.88, f'年度总支出:{年度总支出:,}元', transform=ax1.transAxes,
fontsize=12, verticalalignment='top', bbox=dict(boxstyle='round', facecolor='lightcoral', alpha=0.7))

ax1.set_title('2024年度收支总览', fontsize=18, fontweight='bold', pad=20)
ax1.set_xlabel('月份', fontsize=12)
ax1.set_ylabel('金额(元)', fontsize=12)
ax1.legend(fontsize=12, loc='upper right')
ax1.grid(True, alpha=0.3)

# 2. 收入结构饼图
ax2 = fig.add_subplot(gs[0, 2])
年度收入结构 = 月度收入[['工资收入', '投资收益', '其他收入']].sum()
colors = ['#3498DB', '#2ECC71', '#F39C12']
wedges, texts, autotexts = ax2.pie(年度收入结构.values, labels=年度收入结构.index,
autopct='%1.1f%%', startangle=90, colors=colors)
ax2.set_title('年度收入结构', fontsize=14, fontweight='bold')

# 美化饼图文字
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontweight('bold')

# 3. 支出结构堆叠图
ax3 = fig.add_subplot(gs[1, :])
支出数据 = 月度支出[['月份', '生活费用', '房租/房贷', '交通费用', '娱乐消费', '学习培训', '其他支出']].set_index('月份')

ax3.stackplot(支出数据.index,
支出数据['生活费用'], 支出数据['房租/房贷'], 支出数据['交通费用'],
支出数据['娱乐消费'], 支出数据['学习培训'], 支出数据['其他支出'],
labels=['生活费用', '房租/房贷', '交通费用', '娱乐消费', '学习培训', '其他支出'],
colors=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3'],
alpha=0.8)

ax3.set_title('月度支出结构变化', fontsize=16, fontweight='bold')
ax3.set_xlabel('月份', fontsize=12)
ax3.set_ylabel('支出金额(元)', fontsize=12)
ax3.legend(loc='upper left', bbox_to_anchor=(1, 1))
ax3.grid(True, alpha=0.3)

# 4. 结余率分析
ax4 = fig.add_subplot(gs[2, 0])
bars = ax4.bar(月度结余['月份'], 月度结余['结余率'],
color=['#2ECC71' if x >= 20 else '#F39C12' if x >= 10 else '#E74C3C' for x in 月度结余['结余率']])

ax4.set_title('月度结余率', fontsize=14, fontweight='bold')
ax4.set_xlabel('月份', fontsize=12)
ax4.set_ylabel('结余率(%)', fontsize=12)
ax4.axhline(y=20, color='green', linestyle='--', alpha=0.7, label='目标结余率')
ax4.legend()

# 添加数值标签
for bar, 数值 in zip(bars, 月度结余['结余率']):
ax4.annotate(f'{数值:.1f}%', (bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5),
ha='center', va='bottom', fontsize=9, fontweight='bold')

# 5. 收入对比柱状图
ax5 = fig.add_subplot(gs[2, 1])
收入对比 = 月度收入.set_index('月份')[['工资收入', '投资收益', '其他收入']]

收入对比.plot(kind='bar', ax=ax5, color=['#3498DB', '#2ECC71', '#F39C12'], width=0.8)
ax5.set_title('各类收入月度对比', fontsize=14, fontweight='bold')
ax5.set_xlabel('月份', fontsize=12)
ax5.set_ylabel('收入金额(元)', fontsize=12)
ax5.legend(fontsize=10)
ax5.tick_params(axis='x', rotation=45)

# 6. 热力图
ax6 = fig.add_subplot(gs[2, 2])
收支明细 = 月度支出.drop(['月份', '总支出'], axis=1)
热力图数据 = 收支明细.T

sns.heatmap(热力图数据, annot=True, fmt='d', cmap='RdYlGn_r', ax=ax6,
cbar_kws={'label': '金额(元)'}, linewidths=0.5)
ax6.set_title('月度支出热力图', fontsize=14, fontweight='bold')
ax6.set_xlabel('月份', fontsize=12)
ax6.set_ylabel('支出类别', fontsize=12)

# 整体标题
fig.suptitle('个人理财年度报告 2024', fontsize=24, fontweight='bold', y=0.98)

# 添加页脚信息
fig.text(0.5, 0.02,
f'报告生成时间:{datetime.now().strftime("%Y年%m月%d日 %H:%M")} | ' +
f'年度总结余:{月度结余["月度结余"].sum():,}元 | ' +
f'平均结余率:{月度结余["结余率"].mean():.1f}%',
ha='center', fontsize=12, style='italic',
bbox=dict(boxstyle='round,pad=0.5', facecolor='lightgray', alpha=0.8))

plt.tight_layout()

# 保存图表
plt.savefig('个人理财年度报告_完整版.png', dpi=300, bbox_inches='tight', facecolor='white')
plt.show()

print("✅ 可视化年度报告已生成:个人理财年度报告_完整版.png")

return fig

# 生成可视化年报
可视化年报 = 生成可视化年报()
版本3.0:专业年度报告系统
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
# 专业年度报告系统
print("\n=== 专业年度报告系统 ===")

class 年度报告生成器:
"""专业年度报告生成器"""

def __init__(self):
self.年度数据 = None
self.分析报告 = {}
self.图表文件 = []

def 加载数据(self, 收入数据, 支出数据, 结余数据):
"""加载年度财务数据"""
self.年度收入 = 收入数据
self.年度支出 = 支出数据
self.年度结余 = 结余数据

# 计算年度汇总
self.计算年度汇总()

print("✅ 年度数据加载完成")

def 计算年度汇总(self):
"""计算年度关键指标"""
self.年度汇总 = {
'年度总收入': self.年度收入['总收入'].sum(),
'年度总支出': self.年度支出['总支出'].sum(),
'年度总结余': self.年度结余['月度结余'].sum(),
'平均月结余': self.年度结余['月度结余'].mean(),
'平均结余率': self.年度结余['结余率'].mean(),
'收入结构': self.年度收入[['工资收入', '投资收益', '其他收入']].sum(),
'支出结构': self.年度支出.drop(['月份', '总支出'], axis=1).sum()
}

# 计算排名和占比
self.计算详细分析()

def 计算详细分析(self):
"""进行详细的数据分析"""

# 月度排名
self.月度排名 = {
'收入最高月份': self.年度收入.loc[self.年度收入['总收入'].idxmax(), '月份'],
'收入最低月份': self.年度收入.loc[self.年度收入['总收入'].idxmin(), '月份'],
'支出最高月份': self.年度支出.loc[self.年度支出['总支出'].idxmax(), '月份'],
'支出最低月份': self.年度支出.loc[self.年度支出['总支出'].idxmin(), '月份'],
'结余最高月份': self.年度结余.loc[self.年度结余['月度结余'].idxmax(), '月份'],
'结余最低月份': self.年度结余.loc[self.年度结余['月度结余'].idxmin(), '月份']
}

# 趋势分析
self.趋势分析 = {
'收入趋势': '上升' if self.年度收入['总收入'].iloc[-1] > self.年度收入['总收入'].iloc[0] else '下降',
'支出趋势': '上升' if self.年度支出['总支出'].iloc[-1] > self.年度支出['总支出'].iloc[0] else '下降',
'结余趋势': '改善' if self.年度结余['月度结余'].iloc[-1] > self.年度结余['月度结余'].iloc[0] else '恶化'
}

# 健康度评估
self.健康度评估()

def 健康度评估(self):
"""评估财务健康度"""
平均结余率 = self.年度汇总['平均结余率']

# 基础健康度评分
if 平均结余率 >= 25:
self.健康等级 = "优秀"
self.健康得分 = 90
self.健康建议 = "您的财务状况非常优秀!建议继续保持,并考虑增加投资。"
elif 平均结余率 >= 20:
self.健康等级 = "良好"
self.健康得分 = 80
self.健康建议 = "您的财务状况良好!建议适当优化支出结构,提高储蓄效率。"
elif 平均结余率 >= 15:
self.健康等级 = "一般"
self.健康得分 = 70
self.健康建议 = "您的财务状况一般,建议控制非必要支出,提高结余率。"
else:
self.健康等级 = "需改善"
self.健康得分 = 60
self.健康建议 = "您的财务状况需要改善,建议制定严格的预算计划,减少不必要的开支。"

# 详细健康指标
self.健康指标 = {
'结余率得分': min(100, 平均结余率 * 4),
'收入稳定性得分': max(0, 100 - (self.年度收入['总收入'].std() / self.年度收入['总收入'].mean() * 100)),
'支出控制得分': max(0, 100 - (self.年度支出['总支出'].std() / self.年度支出['总支出'].mean() * 100)),
}

self.健康指标['综合得分'] = sum(self.健康指标.values()) / len(self.健康指标)

def 生成图表集(self):
"""生成完整的图表集"""

print("📊 生成专业图表集...")

# 创建大型图表组合
self.图表集 = plt.figure(figsize=(20, 16))
gs = self.图表集.add_gridspec(4, 4, hspace=0.4, wspace=0.3)

# 1. 年度总览(大图)
ax1 = self.图表集.add_subplot(gs[0, :2])
self._绘制年度总览(ax1)

# 2. 收入结构环形图
ax2 = self.图表集.add_subplot(gs[0, 2])
self._绘制收入结构(ax2)

# 3. 支出结构饼图
ax3 = self.图表集.add_subplot(gs[0, 3])
self._绘制支出结构(ax3)

# 4. 月度趋势对比
ax4 = self.图表集.add_subplot(gs[1, :2])
self._绘制月度趋势(ax4)

# 5. 收支热力图
ax5 = self.图表集.add_subplot(gs[1, 2:])
self._绘制热力图(ax5)

# 6. 结余率分析
ax6 = self.图表集.add_subplot(gs[2, :2])
self._绘制结余率分析(ax6)

# 7. 收入对比
ax7 = self.图表集.add_subplot(gs[2, 2])
self._绘制收入对比(ax7)

# 8. 支出对比
ax8 = self.图表集.add_subplot(gs[2, 3])
self._绘制支出对比(ax8)

# 9. 健康度雷达图
ax9 = self.图表集.add_subplot(gs[3, :2])
self._绘制健康度雷达图(ax9)

# 10. 关键指标仪表盘
ax10 = self.图表集.add_subplot(gs[3, 2:])
self._绘制关键指标(ax10)

# 整体标题
self.图表集.suptitle(f'个人理财年度报告 2024\n财务健康度:{self.健康等级}{self.健康得分}分)',
fontsize=28, fontweight='bold', y=0.98)

# 页脚信息
self.图表集.text(0.5, 0.02,
f'报告生成时间:{datetime.now().strftime("%Y年%m月%d日 %H:%M")} | ' +
f'年度总结余:{self.年度汇总["年度总结余"]:,}元 | ' +
f'平均结余率:{self.年度汇总["平均结余率"]:.1f}%',
ha='center', fontsize=14, style='italic',
bbox=dict(boxstyle='round,pad=0.5', facecolor='lightgray', alpha=0.8),
transform=self.图表集.transFigure)

plt.tight_layout()

# 保存图表
图表文件 = '个人理财年度报告_专业版.png'
plt.savefig(图表文件, dpi=300, bbox_inches='tight', facecolor='white')
plt.show()

self.图表文件.append(图表文件)

print("✅ 专业图表集已生成!")

return 图表文件

def _绘制年度总览(self, ax):
"""绘制年度总览图"""
ax.plot(self.年度收入['月份'], self.年度收入['总收入'],
marker='o', linewidth=4, label='总收入', color='#2E8B57', markersize=8)
ax.plot(self.年度支出['月份'], self.年度支出['总支出'],
marker='s', linewidth=4, label='总支出', color='#DC143C', markersize=8)
ax.fill_between(self.年度收入['月份'], self.年度收入['总收入'], alpha=0.3, color='#2E8B57')
ax.fill_between(self.年度支出['月份'], self.年度支出['总支出'], alpha=0.3, color='#DC143C')

# 添加总计注释
ax.text(0.02, 0.98, f'总收入:{self.年度汇总["年度总收入"]:,}元',
transform=ax.transAxes, fontsize=12, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8))
ax.text(0.02, 0.88, f'总支出:{self.年度汇总["年度总支出"]:,}元',
transform=ax.transAxes, fontsize=12, verticalalignment='top',
bbox=dict(boxstyle='round', facecolor='lightcoral', alpha=0.8))

ax.set_title('年度收支总览', fontsize=16, fontweight='bold')
ax.set_xlabel('月份', fontsize=12)
ax.set_ylabel('金额(元)', fontsize=12)
ax.legend(fontsize=12, loc='upper right')
ax.grid(True, alpha=0.3)

def _绘制收入结构(self, ax):
"""绘制收入结构图"""
收入结构 = self.年度汇总['收入结构']
wedges, texts, autotexts = ax.pie(收入结构.values, labels=收入结构.index,
autopct='%1.1f%%', startangle=90,
colors=['#3498DB', '#2ECC71', '#F39C12'])

ax.set_title('年度收入结构', fontsize=14, fontweight='bold')

# 美化文字
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontweight('bold')

def _绘制支出结构(self, ax):
"""绘制支出结构图"""
支出结构 = self.年度汇总['支出结构']
wedges, texts, autotexts = ax.pie(支出结构.values, labels=支出结构.index,
autopct='%1.1f%%', startangle=90,
colors=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3'])

ax.set_title('年度支出结构', fontsize=14, fontweight='bold')

# 美化文字
for autotext in autotexts:
autotext.set_color('white')
autotext.set_fontweight('bold')

def _绘制月度趋势(self, ax):
"""绘制月度趋势对比图"""
收支对比 = pd.DataFrame({
'月份': self.年度收入['月份'],
'收入': self.年度收入['总收入'],
'支出': self.年度支出['总支出'],
'结余': self.年度结余['月度结余']
})

# 绘制双轴图
ax_twin = ax.twinx()

# 收入和支出
收支对比.plot(x='月份', y=['收入', '支出'], kind='line', ax=ax,
color=['#2E8B57', '#DC143C'], linewidth=3, marker='o', markersize=6)

# 结余(使用右侧坐标轴)
ax_twin.plot(收支对比['月份'], 收支对比['结余'], color='#4169E1',
linewidth=3, marker='^', markersize=6, label='结余')

ax.set_title('月度收支趋势对比', fontsize=16, fontweight='bold')
ax.set_xlabel('月份', fontsize=12)
ax.set_ylabel('收入/支出(元)', fontsize=12)
ax_twin.set_ylabel('结余(元)', fontsize=12)

ax.legend(loc='upper left')
ax_twin.legend(loc='upper right')
ax.grid(True, alpha=0.3)

def _绘制热力图(self, ax):
"""绘制收支热力图"""
支出明细 = self.年度支出.drop(['月份', '总支出'], axis=1)
热力图数据 = 支出明细.T

sns.heatmap(热力图数据, annot=True, fmt='d', cmap='RdYlGn_r', ax=ax,
cbar_kws={'label': '金额(元)'}, linewidths=0.5)

ax.set_title('月度支出热力图', fontsize=16, fontweight='bold')
ax.set_xlabel('月份', fontsize=12)
ax.set_ylabel('支出类别', fontsize=12)

def _绘制结余率分析(self, ax):
"""绘制结余率分析图"""
bars = ax.bar(self.年度结余['月份'], self.年度结余['结余率'],
color=['#2ECC71' if x >= 20 else '#F39C12' if x >= 10 else '#E74C3C' for x in self.年度结余['结余率']])

ax.set_title('月度结余率分析', fontsize=16, fontweight='bold')
ax.set_xlabel('月份', fontsize=12)
ax.set_ylabel('结余率(%)', fontsize=12)
ax.axhline(y=20, color='green', linestyle='--', alpha=0.7, label='目标结余率(20%)')
ax.axhline(y=self.年度汇总['平均结余率'], color='blue', linestyle='--', alpha=0.7, label=f'平均结余率({self.年度汇总["平均结余率"]:.1f}%)')
ax.legend()

# 添加数值标签
for bar, 数值 in zip(bars, self.年度结余['结余率']):
ax.annotate(f'{数值:.1f}%', (bar.get_x() + bar.get_width()/2, bar.get_height() + 0.5),
ha='center', va='bottom', fontsize=10, fontweight='bold')

def _绘制收入对比(self, ax):
"""绘制收入对比图"""
收入对比 = self.年度收入.set_index('月份')[['工资收入', '投资收益', '其他收入']]

收入对比.plot(kind='bar', ax=ax, color=['#3498DB', '#2ECC71', '#F39C12'], width=0.8)
ax.set_title('各类收入月度对比', fontsize=14, fontweight='bold')
ax.set_xlabel('月份', fontsize=12)
ax.set_ylabel('收入金额(元)', fontsize=12)
ax.legend(fontsize=10)
ax.tick_params(axis='x', rotation=45)
ax.grid(True, alpha=0.3)

def _绘制支出对比(self, ax):
"""绘制支出对比图"""
支出对比 = self.年度支出.set_index('月份').drop(['总支出'], axis=1)

支出对比.plot(kind='bar', ax=ax, stacked=True,
color=['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FECA57', '#FF9FF3'], width=0.8)
ax.set_title('各类支出月度对比', fontsize=14, fontweight='bold')
ax.set_xlabel('月份', fontsize=12)
ax.set_ylabel('支出金额(元)', fontsize=12)
ax.legend(fontsize=9, loc='upper left', bbox_to_anchor=(1, 1))
ax.tick_params(axis='x', rotation=45)
ax.grid(True, alpha=0.3)

def _绘制健康度雷达图(self, ax):
"""绘制健康度雷达图"""
指标列表 = list(self.健康指标.keys())
数值列表 = list(self.健康指标.values())

# 闭合图形
指标列表 += [指标列表[0]]
数值列表 += [数值列表[0]]

# 计算角度
角度 = np.linspace(0, 2 * np.pi, len(指标列表), endpoint=True)

# 绘制雷达图
ax.plot(角度, 数值列表, 'o-', linewidth=3, color='#3498DB')
ax.fill(角度, 数值列表, alpha=0.3, color='#3498DB')

# 设置标签
ax.set_xticks(角度[:-1])
ax.set_xticklabels(指标列表[:-1])
ax.set_ylim(0, 100)

# 添加网格
ax.grid(True)

ax.set_title('财务健康度评估', fontsize=14, fontweight='bold')

def _绘制关键指标(self, ax):
"""绘制关键指标仪表盘"""
ax.axis('off')

# 关键指标文本
关键指标文本 = f"""
关键财务指标

年度总收入:{self.年度汇总["年度总收入"]:,.0f}
年度总支出:{self.年度汇总["年度总支出"]:,.0f}
年度总结余:{self.年度汇总["年度总结余"]:,.0f}
平均结余率:{self.年度汇总["平均结余率"]:.1f}%

财务健康等级:{self.健康等级}
健康度评分:{self.健康得分}

收入最高月份:{self.月度排名["收入最高月份"]}
支出最高月份:{self.月度排名["支出最高月份"]}
结余最高月份:{self.月度排名["结余最高月份"]}
"""

ax.text(0.5, 0.5, 关键指标文本, transform=ax.transAxes,
fontsize=12, ha='center', va='center',
bbox=dict(boxstyle='round,pad=0.5', facecolor='lightblue', alpha=0.8))

def 生成完整报告(self, 输出目录="年度报告"):
"""生成完整的年度报告包"""

print("📦 生成完整年度报告包...")

# 创建输出目录
import os
os.makedirs(输出目录, exist_ok=True)

# 1. 生成图表集
图表文件 = self.生成图表集()

# 2. 生成Excel报告
Excel文件 = self.生成Excel报告(os.path.join(输出目录, "年度财务数据.xlsx"))

# 3. 生成PDF报告
PDF文件 = self.生成PDF报告(os.path.join(输出目录, "年度报告.pdf"))

# 4. 生成文本报告
文本文件 = self.生成文本报告(os.path.join(输出目录, "年度报告摘要.txt"))

# 5. 生成Markdown报告
Markdown文件 = self.生成Markdown报告(os.path.join(输出目录, "年度报告.md"))

print(f"✅ 完整年度报告包已生成:{输出目录}/")
print(f" 📊 图表文件:{图表文件}")
print(f" 📈 Excel文件:{Excel文件}")
print(f" 📄 PDF文件:{PDF文件}")
print(f" 📝 文本文件:{文本文件}")
print(f" 📝 Markdown文件:{Markdown文件}")

return {
'图表': 图表文件,
'Excel': Excel文件,
'PDF': PDF文件,
'文本': 文本文件,
'Markdown': Markdown文件
}

def 生成Excel报告(self, 文件名):
"""生成Excel格式的详细报告"""

print(f"📊 生成Excel报告:{文件名}")

with pd.ExcelWriter(文件名, engine='openpyxl') as writer:
# 数据表
self.年度收入.to_excel(writer, sheet_name='年度收入', index=False)
self.年度支出.to_excel(writer, sheet_name='年度支出', index=False)
self.年度结余.to_excel(writer, sheet_name='年度结余', index=False)

# 汇总表
汇总表 = pd.DataFrame({
'项目': ['年度总收入', '年度总支出', '年度总结余', '平均月结余', '平均结余率', '财务健康等级', '健康度得分'],
'数值': [self.年度汇总["年度总收入"], self.年度汇总["年度总支出"],
self.年度汇总["年度总结余"], self.年度汇总["平均月结余"],
self.年度汇总["平均结余率"], self.健康等级, self.健康得分],
'单位': ['元', '元', '元', '元', '%', '', '分']
})
汇总表.to_excel(writer, sheet_name='年度汇总', index=False)

# 分析结果表
分析结果 = pd.DataFrame({
'指标': ['收入最高月份', '支出最高月份', '结余最高月份', '收入趋势', '支出趋势', '结余趋势'],
'数值': [self.月度排名["收入最高月份"], self.月度排名["支出最高月份"],
self.月度排名["结余最高月份"], self.趋势分析["收入趋势"],
self.趋势分析["支出趋势"], self.趋势分析["结余趋势"]]
})
分析结果.to_excel(writer, sheet_name='分析结果', index=False)

# 健康指标表
健康指标表 = pd.DataFrame({
'健康指标': list(self.健康指标.keys()),
'得分': list(self.健康指标.values()),
'权重': [1/len(self.健康指标)] * len(self.健康指标)
})
健康指标表.to_excel(writer, sheet_name='健康指标', index=False)

return 文件名

def 生成PDF报告(self, 文件名):
"""生成PDF格式的专业报告"""

print(f"📄 生成PDF报告:{文件名}")

from matplotlib.backends.backend_pdf import PdfPages

with PdfPages(文件名) as pdf:
# 封面页
self._生成PDF封面(pdf)

# 总览页
self._生成PDF总览(pdf)

# 详细分析页
self._生成PDF详细分析(pdf)

# 健康度评估页
self._生成PDF健康评估(pdf)

# 建议页
self._生成PDF建议(pdf)

return 文件名

def _生成PDF封面(self, pdf):
"""生成PDF封面"""
fig = plt.figure(figsize=(8.27, 11.69)) # A4尺寸

# 主标题
plt.text(0.5, 0.8, '个人理财年度报告', ha='center', va='center',
transform=fig.transFigure, fontsize=36, fontweight='bold')

# 副标题
plt.text(0.5, 0.65, '2024年度财务分析报告', ha='center', va='center',
transform=fig.transFigure, fontsize=24, style='italic')

# 关键数据
plt.text(0.5, 0.45, f'年度总结余:{self.年度汇总["年度总结余"]:,.0f}元',
ha='center', va='center', transform=fig.transFigure,
fontsize=20, color='#2ECC71', fontweight='bold',
bbox=dict(boxstyle='round', facecolor='lightgreen', alpha=0.8))

plt.text(0.5, 0.35, f'平均结余率:{self.年度汇总["平均结余率"]:.1f}%',
ha='center', va='center', transform=fig.transFigure,
fontsize=18, color='#3498DB', fontweight='bold',
bbox=dict(boxstyle='round', facecolor='lightblue', alpha=0.8))

plt.text(0.5, 0.25, f'财务健康度:{self.健康等级}',
ha='center', va='center', transform=fig.transFigure,
fontsize=18, color='#DC143C', fontweight='bold',
bbox=dict(boxstyle='round', facecolor='lightcoral', alpha=0.8))

# 生成时间
plt.text(0.5, 0.1, f'生成时间:{datetime.now().strftime("%Y年%m月%d日")}',
ha='center', va='center', transform=fig.transFigure, fontsize=14)

plt.axis('off')
pdf.savefig(fig, bbox_inches='tight')
plt.close()

def _生成PDF总览(self, pdf):
"""生成PDF总览页"""
# 使用之前生成的图表集
if hasattr(self, '图表集'):
pdf.savefig(self.图表集, bbox_inches='tight')
else:
# 如果没有图表集,生成简化版
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(11.69, 8.27))
self._绘制年度总览(ax1)
self._绘制收入结构(ax2)
self._绘制支出结构(ax3)
self._绘制月度趋势(ax4)
plt.suptitle('年度财务总览', fontsize=18, fontweight='bold')
plt.tight_layout()
pdf.savefig(fig, bbox_inches='tight')
plt.close()

def _生成PDF详细分析(self, pdf):
"""生成PDF详细分析页"""
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(11.69, 8.27))

self._绘制结余率分析(ax1)
self._绘制收入对比(ax2)
self._绘制支出对比(ax3)
self._绘制热力图(ax4)

plt.suptitle('详细财务分析', fontsize=18, fontweight='bold')
plt.tight_layout()
pdf.savefig(fig, bbox_inches='tight')
plt.close()

def _生成PDF健康评估(self, pdf):
"""生成PDF健康度评估页"""
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(11.69, 8.27))

self._绘制健康度雷达图(ax1)
self._绘制关键指标(ax2)

plt.suptitle('财务健康度评估', fontsize=18, fontweight='bold')
plt.tight_layout()
pdf.savefig(fig, bbox_inches='tight')
plt.close()

def _生成PDF建议(self, pdf):
"""生成PDF建议页"""
fig = plt.figure(figsize=(8.27, 11.69))

# 建议内容
建议内容 = f"""
个人理财建议与规划

一、当前财务状况总结

1. 总体评价
• 财务健康等级:{self.健康等级}
• 健康度评分:{self.健康得分}
• 平均结余率:{self.年度汇总["平均结余率"]:.1f}%

2. 主要亮点
• 年度总结余:{self.年度汇总["年度总结余"]:,.0f}
• 收入结构:工资收入占比{self.年度汇总["收入结构"]["工资收入"]/self.年度汇总["年度总收入"]*100:.1f}%

3. 需要关注的问题
• 支出集中度:{list(self.年度汇总["支出结构"].keys())[0]}占比最高
• 结余率波动:{self.年度结余["结余率"].std():.1f}%

二、明年理财目标

1. 结余目标
• 目标结余率:≥25%
• 目标月结余:≥{self.年度汇总["平均月结余"]*1.2:,.0f}

2. 收入目标
• 增加投资收入占比至10%以上
• 探索多元化收入来源

3. 支出控制目标
• 降低非必要支出占比
• 建立应急基金(6个月生活费)

三、具体行动计划

1. 短期行动(1-3个月)
• 制定详细的月度预算
• 建立支出追踪系统
• 开始建立应急基金

2. 中期行动(3-12个月)
• 学习投资理财知识
• 优化投资组合
• 定期回顾和调整计划

3. 长期行动(1年以上)
• 实现财务目标多元化
• 建立被动收入来源
• 规划退休理财方案
"""

plt.text(0.1, 0.9, 建议内容, transform=fig.transFigure, fontsize=12,
verticalalignment='top', fontfamily='monospace',
bbox=dict(boxstyle='round,pad=0.5', facecolor='lightyellow', alpha=0.8))

plt.axis('off')
plt.suptitle('个人理财建议与规划', fontsize=20, fontweight='bold', y=0.98)
pdf.savefig(fig, bbox_inches='tight')
plt.close()

def 生成文本报告(self, 文件名):
"""生成文本格式的报告摘要"""

print(f"📝 生成文本报告:{文件名}")

报告内容 = f"""
═══════════════════════════════════════════════════════════════
个人理财年度报告摘要
2024年度
═══════════════════════════════════════════════════════════════

📊 年度财务概况
───────────────────────────────────────────────────────────────
• 年度总收入:{self.年度汇总["年度总收入"]:,}
• 年度总支出:{self.年度汇总["年度总支出"]:,}
• 年度总结余:{self.年度汇总["年度总结余"]:,}
• 平均月结余:{self.年度汇总["平均月结余"]:,.2f}
• 平均结余率:{self.年度汇总["平均结余率"]:.1f}%
• 财务健康等级:{self.健康等级}{self.健康得分}分)

📈 趋势分析
───────────────────────────────────────────────────────────────
• 收入趋势:{self.趋势分析["收入趋势"]}
• 支出趋势:{self.趋势分析["支出趋势"]}
• 结余趋势:{self.趋势分析["结余趋势"]}

🏆 年度之最
───────────────────────────────────────────────────────────────
• 收入最高月份:{self.月度排名["收入最高月份"]}
• 支出最高月份:{self.月度排名["支出最高月份"]}
• 结余最高月份:{self.月度排名["结余最高月份"]}

💡 理财建议
───────────────────────────────────────────────────────────────
{self.健康建议}

📅 报告生成时间:{datetime.now().strftime("%Y年%m月%d日 %H:%M")}
═══════════════════════════════════════════════════════════════
"""

with open(文件名, 'w', encoding='utf-8') as f:
f.write(报告内容)

return 文件名

def 生成Markdown报告(self, 文件名):
"""生成Markdown格式的报告"""

print(f"📝 生成Markdown报告:{文件名}")

Markdown内容 = f"""# 个人理财年度报告 2024

## 📊 年度财务概况

### 关键指标
| 指标 | 数值 | 单位 |
|------|------|------|
| 年度总收入 | {self.年度汇总["年度总收入"]:,.0f} | 元 |
| 年度总支出 | {self.年度汇总["年度总支出"]:,.0f} | 元 |
| 年度总结余 | {self.年度汇总["年度总结余"]:,.0f} | 元 |
| 平均月结余 | {self.年度汇总["平均月结余"]:,.2f} | 元 |
| 平均结余率 | {self.年度汇总["平均结余率"]:.1f} | % |
| 财务健康等级 | {self.健康等级} | - |
| 健康度得分 | {self.健康得分} | 分 |

### 收入结构
{self.年度汇总["收入结构"].to_markdown()}

### 支出结构
{self.年度汇总["支出结构"].to_markdown()}

## 📈 趋势分析

### 月度趋势
{self.年度结余[["月份", "月度结余", "结余率"]].to_markdown()}

### 关键排名
- 收入最高月份:{self.月度排名["收入最高月份"]}
- 支出最高月份:{self.月度排名["支出最高月份"]}
- 结余最高月份:{self.月度排名["结余最高月份"]}

## 💡 理财建议

{self.健康建议}

## 📊 健康指标详情

{pd.DataFrame(list(self.健康指标.items()), columns=['指标', '得分']).to_markdown()}

---

*报告生成时间:{datetime.now().strftime("%Y年%m月%d日 %H:%M")}*
"""

with open(文件名, 'w', encoding='utf-8') as f:
f.write(Markdown内容)

return 文件名

# 使用专业年度报告生成器
专业生成器 = 年度报告生成器()

# 加载数据
专业生成器.加载数据(月度收入, 月度支出, 月度结余)

# 生成完整报告包
报告文件 = 专业生成器.生成完整报告("个人理财年度报告_专业版")

print("\n🎉 所有报告已生成完成!")
print("您可以查看以下文件:")
for 类型, 文件 in 报告文件.items():
print(f" {类型}{文件}")

🏃‍♀️ 进阶小挑战

挑战1:投资组合分析报告
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# 投资组合分析报告挑战
print("=== 投资组合分析报告挑战 ===")

# 创建投资组合数据
投资组合数据 = pd.DataFrame({
'日期': pd.date_range('2024-01-01', periods=250, freq='D'),
'股票A': np.random.normal(100, 5, 250).cumsum() + 100,
'股票B': np.random.normal(95, 8, 250).cumsum() + 95,
'债券A': np.random.normal(102, 2, 250).cumsum() + 102,
'基金A': np.random.normal(98, 6, 250).cumsum() + 98,
'黄金': np.random.normal(105, 4, 250).cumsum() + 105
})

# 添加收益率
forin 投资组合数据.columns[1:]:
投资组合数据[f'{列}_收益率'] = 投资组合数据[列].pct_change()

def 生成投资组合报告(投资组合df):
"""生成专业的投资组合分析报告"""

print("📊 生成投资组合分析报告...")

# 1. 基础统计分析
收益统计 = 投资组合数据[['股票A_收益率', '股票B_收益率', '债券A_收益率', '基金A_收益率', '黄金_收益率']].describe()

print("\n📈 收益率统计分析:")
print(收益统计)

# 2. 风险收益分析
风险收益分析 = pd.DataFrame({
'平均收益率': 投资组合数据[['股票A_收益率', '股票B_收益率', '债券A_收益率', '基金A_收益率', '黄金_收益率']].mean(),
'收益率标准差': 投资组合数据[['股票A_收益率', '股票B_收益率', '债券A_收益率', '基金A_收益率', '黄金_收益率']].std(),
'夏普比率': 0 # 待计算
})

# 计算夏普比率(假设无风险利率为3%)
无风险利率 = 0.03 / 250 # 日化收益率
风险收益分析['夏普比率'] = (风险收益分析['平均收益率'] - 无风险利率) / 风险收益分析['收益率标准差']

print("\n💰 风险收益分析:")
print(风险收益分析.round(4))

# 3. 相关性分析
相关性矩阵 = 投资组合数据[['股票A_收益率', '股票B_收益率', '债券A_收益率', '基金A_收益率', '黄金_收益率']].corr()

print("\n🔗 资产相关性分析:")
print(相关性矩阵.round(3))

# 4. 生成专业图表
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))

# 价格走势图
投资组合数据.set_index('日期')[['股票A', '股票B', '债券A', '基金A', '黄金']].plot(ax=ax1, linewidth=2)
ax1.set_title('投资组合价格走势', fontsize=14, fontweight='bold')
ax1.set_ylabel('价格')
ax1.legend()
ax1.grid(True, alpha=0.3)

# 收益率分布图
投资组合数据[['股票A_收益率', '股票B_收益率', '债券A_收益率', '基金A_收益率', '黄金_收益率']].plot(kind='hist', bins=30, alpha=0.7, ax=ax2)
ax2.set_title('日收益率分布', fontsize=14, fontweight='bold')
ax2.set_xlabel('收益率')
ax2.legend()

# 相关性热力图
sns.heatmap(相关性矩阵, annot=True, cmap='coolwarm', center=0, ax=ax3)
ax3.set_title('资产收益率相关性', fontsize=14, fontweight='bold')

# 风险收益散点图
散点数据 = 风险收益分析.reset_index()
散点数据['资产名称'] = 散点_data['index'].str.replace('_收益率', '')

colors = ['red', 'blue', 'green', 'orange', 'purple']
for i, (资产, 数据) in enumerate(散点数据.iterrows()):
ax4.scatter(数据['收益率标准差'], 数据['平均收益率'],
s=200, c=colors[i], alpha=0.7, label=数据['资产名称'])

ax4.set_xlabel('风险(标准差)', fontsize=12)
ax4.set_ylabel('收益率', fontsize=12)
ax4.set_title('风险收益分析', fontsize=14, fontweight='bold')
ax4.legend()
ax4.grid(True, alpha=0.3)

plt.suptitle('投资组合分析报告', fontsize=18, fontweight='bold')
plt.tight_layout()
plt.savefig('投资组合分析报告.png', dpi=300, bbox_inches='tight')
plt.close()

print("✅ 投资组合分析报告已生成!")

# 5. 生成投资建议
print("\n💡 投资建议:")

# 基于分析结果生成建议
最佳夏普 = 风险收益分析['夏普比率'].idxmax()
最差夏普 = 风险收益分析['夏普比率'].idxmin()

print(f" • 最佳风险调整后收益:{最佳夏普.replace('_收益率', '')}(夏普比率:{风险收益分析.loc[最佳夏普, '夏普比率']:.3f})")
print(f" • 需要关注的资产:{最差夏普.replace('_收益率', '')}(夏普比率:{风险收益分析.loc[最差夏普, '夏普比率']:.3f})")

# 基于相关性给出建议
高相关性 = 相关性矩阵[相关性矩阵 > 0.7].count().sum() - len(相关性矩阵)
if 高相关性 > 0:
print(f" • 发现{高相关性}对高相关性资产,建议适当分散投资")

print(" • 建议定期回顾和调整投资组合")
print(" • 考虑增加低相关性资产以降低整体风险")

# 生成投资组合报告
生成投资组合报告(投资组合数据)
挑战2:企业财务分析报告
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
# 企业财务分析报告挑战
print("=== 企业财务分析报告挑战 ===")

# 创建企业财务数据
企业财务数据 = pd.DataFrame({
'年份': [2021, 2022, 2023, 2024],
'营业收入': [5000000, 6000000, 7200000, 8500000],
'营业成本': [3000000, 3600000, 4300000, 5000000],
'营业利润': [800000, 1000000, 1200000, 1500000],
'净利润': [600000, 750000, 900000, 1100000],
'总资产': [8000000, 9500000, 11000000, 13000000],
'总负债': [4000000, 4500000, 5000000, 6000000],
'流动资产': [5000000, 6000000, 7000000, 8500000],
'流动负债': [2500000, 3000000, 3500000, 4000000],
'应收账款': [1500000, 1800000, 2100000, 2500000],
'存货': [2000000, 2400000, 2800000, 3200000],
'固定资产': [3000000, 3500000, 4000000, 4500000]
})

def 生成企业财务报告(企业数据):
"""生成企业财务分析报告"""

print("📊 生成企业财务分析报告...")

# 1. 计算财务比率
财务比率 = pd.DataFrame()

# 盈利能力比率
财务比率['销售毛利率'] = (企业数据['营业收入'] - 企业数据['营业成本']) / 企业数据['营业收入'] * 100
财务比率['销售净利率'] = 企业数据['净利润'] / 企业数据['营业收入'] * 100
财务比率['资产净利率'] = 企业数据['净利润'] / 企业数据['总资产'] * 100
财务比率['净资产收益率'] = 企业数据['净利润'] / (企业数据['总资产'] - 企业数据['总负债']) * 100

# 偿债能力比率
财务比率['流动比率'] = 企业数据['流动资产'] / 企业数据['流动负债']
财务比率['速动比率'] = (企业数据['流动资产'] - 企业数据['存货']) / 企业数据['流动负债']
财务比率['资产负债率'] = 企业数据['总负债'] / 企业数据['总资产'] * 100

# 营运能力比率
财务比率['应收账款周转率'] = 企业数据['营业收入'] / 企业数据['应收账款']
财务比率['存货周转率'] = 企业数据['营业成本'] / 企业数据['存货']
财务比率['总资产周转率'] = 企业数据['营业收入'] / 企业数据['总资产']

print("📊 财务比率计算完成:")
print(财务比率.round(2))

# 2. 趋势分析
趋势分析 = pd.DataFrame()
forin ['营业收入', '净利润', '总资产']:
趋势分析[f'{列}_增长率'] = 企业数据[列].pct_change() * 100

print("\n📈 增长趋势分析:")
print(趋势分析.round(2))

# 3. 生成专业图表
fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(2, 2, figsize=(15, 10))

# 营业收入和利润趋势
ax1_twin = ax1.twinx()
ax1.bar(企业数据['年份'], 企业数据['营业收入'], alpha=0.7, color='skyblue', label='营业收入')
ax1_twin.plot(企业数据['年份'], 企业数据['净利润'], color='red', marker='o', linewidth=3, label='净利润')

ax1.set_xlabel('年份', fontsize=12)
ax1.set_ylabel('营业收入(元)', fontsize=12, color='blue')
ax1_twin.set_ylabel('净利润(元)', fontsize=12, color='red')
ax1.set_title('营业收入与净利润趋势', fontsize=14, fontweight='bold')
ax1.legend(loc='upper left')
ax1_twin.legend(loc='upper right')

# 财务比率趋势
财务比率[['销售毛利率', '销售净利率', '净资产收益率']].plot(ax=ax2, marker='o', linewidth=2)
ax2.set_title('盈利能力比率趋势', fontsize=14, fontweight='bold')
ax2.set_xlabel('年份', fontsize=12)
ax2.set_ylabel('比率(%)', fontsize=12)
ax2.legend()
ax2.grid(True, alpha=0.3)

# 偿债能力比率
财务比率[['流动比率', '速动比率']].plot(ax=ax3, marker='s', linewidth=2)
ax3.axhline(y=2, color='green', linestyle='--', alpha=0.7, label='标准流动比率')
ax3.axhline(y=1, color='orange', linestyle='--', alpha=0.7, label='标准速动比率')
ax3.set_title('偿债能力比率趋势', fontsize=14, fontweight='bold')
ax3.set_xlabel('年份', fontsize=12)
ax3.set_ylabel('比率', fontsize=12)
ax3.legend()
ax3.grid(True, alpha=0.3)

# 营运能力比率
财务比率[['应收账款周转率', '存货周转率', '总资产周转率']].plot(ax=ax4, marker='^', linewidth=2)
ax4.set_title('营运能力比率趋势', fontsize=14, fontweight='bold')
ax4.set_xlabel('年份', fontsize=12)
ax4.set_ylabel('周转率(次)', fontsize=12)
ax4.legend()
ax4.grid(True, alpha=0.3)

plt.suptitle('企业财务分析报告', fontsize=18, fontweight='bold')
plt.tight_layout()
plt.savefig('企业财务分析报告.png', dpi=300, bbox_inches='tight')
plt.close()

print("✅ 企业财务分析报告已生成!")

# 4. 生成投资建议
print("\n💡 企业财务建议:")

# 基于分析结果给出建议
最新年份 = 企业数据['年份'].iloc[-1]
最新数据 = 企业数据.iloc[-1]
最新比率 = 财务比率.iloc[-1]

print(f"\n {最新年份}年度财务表现:")
print(f" • 营业收入:{最新数据['营业收入']:,}元")
print(f" • 净利润:{最新数据['净利润']:,}元")
print(f" • 净资产收益率:{最新比率['净资产收益率']:.2f}%")
print(f" • 资产负债率:{最新比率['资产负债率']:.2f}%")

# 基于比率给出建议
if 最新比率['净资产收益率'] > 15:
print(" ✅ 盈利能力良好,净资产收益率超过15%")
else:
print(" ⚠️ 盈利能力需要提升,建议优化成本结构")

if 最新比率['资产负债率'] < 50:
print(" ✅ 财务风险较低,资产负债率控制在50%以下")
else:
print(" ⚠️ 财务杠杆较高,建议控制负债规模")

if 最新比率['流动比率'] > 2:
print(" ✅ 短期偿债能力强,流动比率超过2倍")
else:
print(" ⚠️ 短期偿债能力需要关注,建议增加流动资产")

print(" • 建议定期监控财务比率变化")
print(" • 建议与同行业企业进行对比分析")
print(" • 建议制定长期的财务战略规划")

# 生成企业财务报告
生成企业财务报告(企业财务数据)

💭 今日思考

通过今天的学习,我们发现:

  • Python可以生成比Excel更专业、更美观的图表
  • 一次编写代码,可以重复使用生成报告
  • 可以导出多种格式,满足不同需求
  • 专业的数据报告能大大提升工作效率

📝 课后小结

  • ✅ 学会了用matplotlib生成各种专业图表
  • ✅ 掌握了seaborn高级绘图技巧
  • ✅ 学会了导出Excel、CSV、PDF等多种格式
  • ✅ 完成了专业的个人理财年度报告

💡 小贴士

  • 多练习真实项目,理论结合实践
  • 关注Python和数据分析的最新发展
  • 加入相关的技术社区,与他人交流学习
  • 保持学习的热情,技术永远在进步

🤖 Powered by Kimi K2 0905 💻 内容经葵葵🌻审核与修改