20年初准备投资基金,想爬取基金的业绩数据。

20年基金迎来了爆发式增长,现把代码开源以供参考。

本代码只能实现初步汇总,输出csv文件来保存基金的单位&累计净值,后期仍需要结合统计方法来筛选优质基金。

参考了网上的部分代码,实在不记得出处了,侵删。

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))

# 获取基金编号为fscode的所有信息
def geturl(fscode):
  head = 'http://fund.eastmoney.com/pingzhongdata/'
  tail = '.js?v=' + time.strftime("%y%m%d%h%m%s", time.localtime())
  return head + fscode + tail

# 获取净值
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

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))

到此这篇关于python批量获取基金数据的方法步骤的文章就介绍到这了,更多相关python批量获取基金数据内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!