背景
今日我的Python心路历程是 基金实战可视化之根据基金代码在线获取净值并保存在js文件中)
分析
难点在于:
- 编码格式 encoding=‘utf-8’
- 解析
方案
核心代码如下:
# 根据基金代码在线获取净值,并保存在js文件中
def getWorth(fscode):
content = requests.get(getUrl(fscode))
jsContent = execjs.compile(content.text)
# 获取绝对路径,funddata为当前文件夹
curpath = os.path.join(os.path.dirname(__file__), 'funddata')
fileName = fscode + 'content.js'
file_object_path = os.path.join(curpath, fileName)
# 保存为js文件
f = open(file_object_path, 'w', encoding='utf-8')
f.write(content.text)
f.close()
# 基金名称及代码
name = jsContent.eval('fS_name')
code = jsContent.eval('fS_code')
# 收益率 应用时需要加百分比
# 近一年收益率
syl_1n = jsContent.eval('syl_1n')
# 近6月收益率
syl_6y = jsContent.eval('syl_6y')
# 近三月收益率
syl_3y = jsContent.eval('syl_3y')
# 近一月收益率
syl_1y = jsContent.eval('syl_1y')
# 单位净值走势(及时的交易价值参考)
netWorthTrend = jsContent.eval('Data_netWorthTrend')
# 累计净值走势=单位净值+累计分红
ACWorthTrend = jsContent.eval('Data_ACWorthTrend')
# 现任基金经理
currentFundManager = jsContent.eval('Data_currentFundManager')
netWorth = []
ACWorth = []
for dayWorth in netWorthTrend[::-1]:
netWorth.append(dayWorth['y'])
for dayACWorth in ACWorthTrend[::-1]:
ACWorth.append(dayACWorth[1])
print(name, code)
return netWorth, ACWorth