Wind账号被停,优矿试用期到期,Tushare开启积分模式,基金数据来源只能开启自给自足模式。参考
《Python爬取天天基金网历史净值数据》,自己动手尝试。
1. 天天基金网API
API:url 和 结果
fund_api_nav_table.PNG
2. Python 解析代码
def fund_nav_esatmoney(tickCode, startDate, endDate):
"""
通过天天基金网API查询基金净值数据,返回DataFrame。
- Imput
- tickCode, 基金代码
- startDate, 查询起始日
- endDate, 查询截止日
- Output, df with col:
1. 净值日期
2. 单位净值
3. 累计净值
4. 日增长率
5. 申购状态
6. 赎回状态
7. 分红送配
"""
# 调用天天基金网API 并解析网页
days = (dt.datetime.strptime(endDate, "%Y-%m-%d") - dt.datetime.strptime(startDate, "%Y-%m-%d")).days
url = "http://fund.eastmoney.com/f10/F10DataApi.aspx?type=lsjz&code={}&sdate={}&edate={}&per={}".format(tickCode,startDate, endDate,days)
response = requests.get(url)
soup = BeautifulSoup(response.content, "lxml")
# 获取表头
table_heads = []
for head in soup.findAll("th"):
table_heads.append(head.contents[0])
# 获取数据
table_rows = []
for rows in soup.findAll("tbody")[0].findAll("tr"):
table_records = []
for record in rows.findAll('td'):
val = record.contents
# 处理空值
if len(val) == 0:
table_records.append(np.nan)
else:
table_records.append(val[0])
table_rows.append(table_records)
# 写入DataFrame
table_rows = np.array(table_rows)
df = pd.DataFrame()
for col,col_name in enumerate(table_heads):
df[col_name] = table_rows[:,col]
return df
3. 结果
fund_api_nav_search_result.PNG