使用 Python 采集并可视化分析白酒类基金收益数据
基于 Python 技术栈,演示如何爬取第三方基金平台接口数据并对白酒类基金进行量化分析。通过 Requests 库获取净值历史数据,利用 Pandas 处理时间序列,结合 Matplotlib 绘制月度盈亏、涨跌幅波动及月差值图表。文章提供了完整的代码示例与分析逻辑,帮助读者理解基金数据分析的基本流程,同时强调投资风险提示。

基于 Python 技术栈,演示如何爬取第三方基金平台接口数据并对白酒类基金进行量化分析。通过 Requests 库获取净值历史数据,利用 Pandas 处理时间序列,结合 Matplotlib 绘制月度盈亏、涨跌幅波动及月差值图表。文章提供了完整的代码示例与分析逻辑,帮助读者理解基金数据分析的基本流程,同时强调投资风险提示。

在投资理财领域,数据分析能够帮助投资者更理性地评估资产表现。本文以白酒类基金为例,演示如何使用 Python 从公开接口采集基金历史净值数据,并通过可视化手段分析其月度盈亏、涨跌幅波动及整体趋势。通过本教程,读者可以掌握从数据采集到图表展示的全流程,并将代码框架应用于其他基金产品的分析。
在开始之前,请确保已安装以下 Python 库:
pip install requests matplotlib pandas
以某基金平台为例,选择白酒类基金(代号:161725)。通过浏览器开发者工具(F12)的 Network 面板观察,发现数据是通过异步接口加载的。
访问链接示例:
https://danjuanapp.com/djapi/fund/nav/history/161725?size=200&page=1
其中参数说明:
161725:基金代码。size:单次请求返回的数据条数。page:页码,支持分页拉取。使用 requests 库模拟浏览器请求,注意设置 User-Agent 以避免被拦截。
import requests
import json
def fetch_fund_data(code, size=365):
url = f"https://danjuanapp.com/djapi/fund/nav/history/{code}?size={size}&page=1"
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
}
try:
res = requests.get(url, headers=headers, timeout=10)
res.encoding = 'utf-8'
data = res.json()
if data.get('success') or 'data' in data:
items = data['data']['items']
return items
else:
print("获取数据失败")
return []
except Exception as e:
print(f"请求异常:{e}")
return []
原始数据为 JSON 格式,包含日期、净值、增长率等信息。为了便于分析,我们将数据转换为结构化列表或 DataFrame。
def parse_data(items):
parsed_list = []
for item in items:
try:
date = item.get('date')
percentage = float(item.get('percentage', 0))
value = float(item.get('value', 0))
parsed_list.append({'date': date, 'percentage': percentage, 'value': value})
except (KeyError, ValueError):
continue
# 按日期倒序排列,方便后续处理
parsed_list.sort(key=lambda x: x['date'], reverse=True)
return parsed_list
利用 Matplotlib 库绘制多种图表,直观展示基金表现。
通过柱状图对比每个月初和月末的净值,判断月度盈亏情况。
import matplotlib.pyplot as plt
from matplotlib.font_manager import FontProperties
# 设置中文字体,防止乱码
myfont = FontProperties(fname="C:\\Windows\\Fonts\\simhei.ttf")
def plot_monthly_comparison(months, start_values, end_values):
plt.figure(figsize=(12, 6), dpi=80)
bar_width = 0.35
x1 = list(range(len(months)))
x2 = [i + bar_width for i in x1]
plt.bar(x1, start_values, width=bar_width, label='月初净值', fontproperties=myfont)
plt.bar(x2, end_values, width=bar_width, label='月末净值', fontproperties=myfont)
plt.xticks([i + bar_width / 2 for i in range(len(months))], months, fontproperties=myfont)
plt.xlabel('月份', fontproperties=myfont)
plt.ylabel('净值', fontproperties=myfont)
plt.legend(prop=myfont)
plt.grid(axis='y', linestyle='--', alpha=0.5)
plt.savefig('./monthly_comparison.png')
plt.show()

分析结论:若月末值高于月初值,则该月盈利。通过图表可快速识别盈利月份与亏损月份。
展示每月的最大涨幅和最大跌幅,反映基金的波动性。
def plot_max_min_fluctuation(months, max_ups, min_downs):
plt.figure(figsize=(12, 6), dpi=80)
bar_width = 0.35
x1 = list(range(len(months)))
x2 = [i + bar_width for i in x1]
plt.bar(x1, max_ups, width=bar_width, label='当月最高涨', color='green', fontproperties=myfont)
plt.bar(x2, min_downs, width=bar_width, label='当月最低跌', color='red', fontproperties=myfont)
plt.xticks([i + bar_width / 2 for i in range(len(months))], months, fontproperties=myfont)
plt.xlabel('月份', fontproperties=myfont)
plt.ylabel('涨跌幅 (%)', fontproperties=myfont)
plt.legend(prop=myfont)
plt.grid(axis='y', linestyle='--', alpha=0.5)
plt.savefig('./fluctuation.png')
plt.show()

分析结论:绿色代表上涨幅度,红色代表下跌幅度。波动较大的月份通常伴随市场热点或政策变化。
计算每月最高涨与最低跌的差值,衡量该月的整体波动剧烈程度。
def plot_volatility(months, diffs):
plt.figure(figsize=(12, 6), dpi=80)
plt.plot(months, diffs, marker='o', label='波动差值', color='blue', fontproperties=myfont)
plt.xlabel('月份', fontproperties=myfont)
plt.ylabel('波动差值 (%)', fontproperties=myfont)
plt.title('月度波动趋势', fontproperties=myfont)
plt.legend(prop=myfont)
plt.grid(True, alpha=0.3)
plt.savefig('./volatility.png')
plt.show()

分析结论:折线越陡峭,说明该月内价格震荡越剧烈,投资风险相对较高。
通过上述图表,我们可以得出以下结论:
本文展示了使用 Python 进行基金数据分析的完整流程:
扩展方向:
希望本文能为学习 Python 金融数据分析的读者提供参考。

微信公众号「极客日志」,在微信中扫描左侧二维码关注。展示文案:极客日志 zeeklog
使用加密算法(如AES、TripleDES、Rabbit或RC4)加密和解密文本明文。 在线工具,加密/解密文本在线工具,online
生成新的随机RSA私钥和公钥pem证书。 在线工具,RSA密钥对生成器在线工具,online
基于 Mermaid.js 实时预览流程图、时序图等图表,支持源码编辑与即时渲染。 在线工具,Mermaid 预览与可视化编辑在线工具,online
解析常见 curl 参数并生成 fetch、axios、PHP curl 或 Python requests 示例代码。 在线工具,curl 转代码在线工具,online
将字符串编码和解码为其 Base64 格式表示形式即可。 在线工具,Base64 字符串编码/解码在线工具,online
将字符串、文件或图像转换为其 Base64 表示形式。 在线工具,Base64 文件转换器在线工具,online