Python批量获取基金数据的方法步骤
本文介绍如何使用Python批量获取基金数据。通过请求特定URL获取基金编号,解析JavaScript文件提取基金代码,并进一步获取单位净值和累计净值。代码实现了初步的数据汇总,输出CSV文件保存基金的单位与累计净值,为后续结合统计方法筛选优质基金提供基础数据支持。
Python批量获取基金数据的方法步骤
在2020年初,为了准备投资基金,我们需要爬取基金的业绩数据。这一年基金迎来了爆发式增长,因此获取准确的基金数据变得尤为重要。本代码只能实现初步汇总,输出csv文件来保存基金的单位与累计净值,后期仍需要结合统计方法来筛选优质基金。
获取所有基金编号
首先,我们需要获取所有基金的编号。这可以通过请求特定的URL来实现。代码如下:
import requests
import time
import execjs
start = time.perf_counter()
# 获取所有基金编号
def getAllCode():
url = 'http://fund.eastmoney.com/js/fundcode_search.js'
content = requests.get(url)
jsContent = execjs.compile(content.text)
rawData = jsContent.eval('r')
allCode = []
for code in rawData:
allCode.append(code[0])
return allCode
allCode = getAllCode()
del allCode[100:len(allCode)]
# print(len(allCode))这段代码通过请求`http://fund.eastmoney.com/js/fundcode_search.js`获取基金编号,并使用`execjs`库解析JavaScript文件,提取出所有基金的编号。
获取基金编号为fscode的所有信息
接下来,我们需要获取每个基金编号对应的详细信息。这可以通过构建特定的URL来实现。代码如下:
# 获取基金编号为fscode的所有信息
def getUrl(fscode):
head = 'http://fund.eastmoney.com/pingzhongdata/'
tail = '.js?=' + time.strftime("%Y%m%d%H%M%S", time.localtime())
return head + fscode + tail这段代码通过拼接URL头部和尾部,生成获取基金详细信息的URL。
获取净值
最后,我们需要获取基金的单位净值和累计净值。这可以通过请求特定的URL并解析JavaScript文件来实现。代码如下:
# 获取净值
def getWorth(fscode):
content = requests.get(getUrl(fscode))
jsContent = execjs.compile(content.text)
name = jsContent.eval('fS_name')
code = jsContent.eval('fS_code')
# 单位净值走势
netWorthTrend = jsContent.eval('Data_netWorthTrend')
# 累计净值走势
ACWorthTrend = jsContent.eval('Data_ACWorthTrend')
# 近一年收益率
Profit_12month = jsContent.eval('syl_1n')
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这段代码通过请求特定的URL并解析JavaScript文件,提取出基金的单位净值和累计净值。
保存数据
最后,我们需要将获取到的基金数据保存到CSV文件中。代码如下:
netWorthFile = open('./netWorth.csv', 'w')
ACWorthFile = open('./ACWorth.csv', 'w')
for code in allCode:
try:
netWorth, ACWorth = getWorth(code)
except:
continue
if len(netWorth) <= 0 or len(ACWorth) < 0:
# print(code + " empty data")
continue
netWorthFile.write("\'" + code + "\',")
netWorthFile.write(",".join(list(map(str, netWorth))))
netWorthFile.write("\n")
ACWorthFile.write("\'" + code + "\',")
ACWorthFile.write(",".join(list(map(str, ACWorth))))
ACWorthFile.write("\n")
# print("write " + code + " success.")
netWorthFile.close()
ACWorthFile.close()
end = time.perf_counter()
print('Running time: %s seconds' %(end-start))这段代码通过遍历所有基金编号,获取每个基金的单位净值和累计净值,并将数据保存到CSV文件中。
总结
通过上述步骤,我们可以使用Python批量获取基金数据。这为后续结合统计方法筛选优质基金提供了基础数据支持。
以上就是Python批量获取基金数据的方法步骤的详细内容,更多关于Python基金数据批量获取的资料请关注本站其它相关文章!
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









