利用python進行基金數(shù)據(jù)分析
背景說明
本文主要是利用Python提取并分析相關(guān)數(shù)據(jù),看下當(dāng)前基金市場上存在哪些類型的基金,作為新手如何判斷一支基金是否值得購買。
分析過程
1.獲取所有種類基金數(shù)據(jù)
1.1導(dǎo)入相關(guān)包
import pandas as pd
import re
import numpy as np
from bs4 import BeautifulSoup
import requests
import matplotlib.pyplot as plt
%matplotlib inline # 解決圖表在jupyter的顯示問題
# 解決中文和‘-’號在jupyter的顯示問題
plt.rcParams['font.sans-serif']='SimHei'
plt.rcParams['axes.unicode_minus']=False
1.2通過天天基金網(wǎng)接口獲取基金數(shù)據(jù)
1.2.1獲取網(wǎng)頁信息
url='http://fund.eastmoney.com/js/fundcode_search.js'
num=requests.get(url)
# 通過正則表達式獲取基金信息
text=re.findall(r'"(\d*?)","(.*?)","(.*?)","(.*?)","(.*?)"',num.text)
1.2.2將數(shù)據(jù)轉(zhuǎn)化成二維表并寫入本地磁盤(dataframe)
# 轉(zhuǎn)化為二維表
基金代碼=[]
基金名稱=[]
基金類型=[]
for i in text:
content=list(i)
基金代碼.append(content[0])
基金名稱.append(content[2])
基金類型.append(content[3])
基金信息=pd.DataFrame({<!-- -->'代碼':基金代碼,'名稱':基金名稱,'類型':基金類型})
# 寫入到本地磁盤,想到后續(xù)會在excel做一些分析,先把數(shù)據(jù)下載下來
writer=pd.ExcelWriter(r'D:\工作文檔\工作\2020\11月\python\基金數(shù)據(jù)導(dǎo)出.xlsx')
基金信息.to_excel(writer,sheet_name='基金信息',index=False)
writer.save()
writer.close()
1.3數(shù)據(jù)概覽
1.3.1查看前幾行數(shù)據(jù)
1.3.2查看各類型基金分布及可視化展示
# 按照類型進行分組
分組數(shù)量=基金信息.groupby('類型').agg(基金數(shù)量=('類型','count')).\
sort_values(by='基金數(shù)量',ascending=False).reset_index('類型')
# 圖表展示
plt.style.use('ggplot')
fig=plt.figure(figsize=(20,8))
plt.xticks(fontsize=12)
plt.yticks(fontsize=12)
plt.bar(x='類型',height='基金數(shù)量',data=分組數(shù)量)
for a,b in zip(range(len(分組數(shù)量.類型)),分組數(shù)量.基金數(shù)量):
plt.text(a,b,b,ha='center',va='bottom',fontsize=16)
plt.title('各類基金數(shù)量',fontdict={<!-- -->'fontsize':20})
分析:
-
通過圖表看到,目前市面上基金數(shù)量前五的類別分別是混合型、債券型、定開債券、貨幣型和股票指數(shù)型。一般來講,數(shù)量越多表明受到投資者喜愛的程度越高。- 針對不同類型的基金,可通過了解他們的特點然后結(jié)合自己的自身情況選擇購買某一種類型的基金。
2.對某支基金進行分析
背景: 通常在購買某支基金前,需要對其歷史凈值信息、歷史漲跌等信息進行充分了解再決定是否購買,以下通過簡單的分析看下當(dāng)下某支基金是否值得購買。
2.1定義抓取函數(shù)
# 這里通過天天基金網(wǎng)的數(shù)據(jù)接口,通過輸入基金代碼、查詢的起始時間獲取基金數(shù)據(jù)
# 抓取網(wǎng)頁
def get_url(url, params=None, proxies=None):
rsp = requests.get(url, params=params, proxies=proxies)
rsp.raise_for_status()
return rsp.text
# 從網(wǎng)頁抓取數(shù)據(jù)
def get_fund_data(code,per=10,sdate='',edate='',proxies=None):
url = 'http://fund.eastmoney.com/f10/F10DataApi.aspx'
params = {<!-- -->'type': 'lsjz', 'code': code, 'page':1,'per': per, 'sdate': sdate, 'edate': edate}
html = get_url(url, params, proxies)
soup = BeautifulSoup(html, 'html.parser')
# 獲取總頁數(shù)
pattern=re.compile(r'pages:(.*),')
result=re.search(pattern,html).group(1)
pages=int(result)
# 獲取表頭
heads = []
for head in soup.findAll("th"):
heads.append(head.contents[0])
# 數(shù)據(jù)存取列表
records = []
# 從第1頁開始抓取所有頁面數(shù)據(jù)
page=1
while page<=pages:
params = {<!-- -->'type': 'lsjz', 'code': code, 'page':page,'per': per, 'sdate': sdate, 'edate': edate}
html = get_url(url, params, proxies)
soup = BeautifulSoup(html, 'html.parser')
# 獲取數(shù)據(jù)
for row in soup.findAll("tbody")[0].findAll("tr"):
row_records = []
for record in row.findAll('td'):
val = record.contents
# 處理空值
if val == []:
row_records.append(np.nan)
else:
row_records.append(val[0])
# 記錄數(shù)據(jù)
records.append(row_records)
# 下一頁
page=page+1
# 數(shù)據(jù)整理到dataframe
np_records = np.array(records)
data= pd.DataFrame()
for col,col_name in enumerate(heads):
data[col_name] = np_records[:,col]
return data
2.2獲取基金凈值信息
#這里提取招商中證白酒基金作分析
found_code='161725'
start_date='2015-01-01'
end_date='2020-12-22'
增長率基準(zhǔn)=0
if __name__ == "__main__":
data=get_fund_data(found_code,per=49,sdate=start_date,edate=end_date)
2.3 查看數(shù)據(jù)字段和數(shù)據(jù)內(nèi)容
data.info()
data.head()
-
可以看到主要字段是日期、單位凈值、累計凈值和日增長率,這些都是后面分析的重要指標(biāo)- 這里我們?nèi)×?年多的數(shù)據(jù),差不多有一千三百多條數(shù)據(jù),扣除節(jié)假日,數(shù)據(jù)量基本是對的,后續(xù)可通過查看某年或某月的數(shù)據(jù)進行驗證。同時導(dǎo)出來的數(shù)據(jù)不存在缺失值,數(shù)據(jù)質(zhì)量較好。
2.4歷史凈值數(shù)據(jù)可視化分析
# 修改數(shù)據(jù)類型
data['凈值日期']=pd.to_datetime(data['凈值日期'],format='%Y/%m/%d')
data['單位凈值']= data['單位凈值'].astype(float)
data['累計凈值']=data['累計凈值'].astype(float)
data['日增長率']=data['日增長率'].str.strip('%').astype(float)
# data['日增長率']=data['日增長率'].astype(float) #上面那句出錯的情況用這一句轉(zhuǎn)化,格式問題
data['基準(zhǔn)值']=增長率基準(zhǔn)
# 按照日期升序排序并重建索引
data=data.sort_values(by='凈值日期',axis=0,ascending=True).reset_index(drop=True)
# 獲取凈值日期、單位凈值、累計凈值、日增長率等數(shù)據(jù)并
net_value_date = data['凈值日期']
net_asset_value = data['單位凈值']
accumulative_net_value=data['累計凈值']
daily_growth_rate = data['日增長率']
daily_jizhun=data['基準(zhǔn)值']
# 作基金凈值圖
fig = plt.figure(figsize=(16,10),dpi=240)
#坐標(biāo)軸1
ax1 = fig.add_subplot(211)
ax1.plot(net_value_date,net_asset_value,label='基金凈值')
ax1.plot(net_value_date,accumulative_net_value,label='累計凈值')
ax1.set_ylabel('凈值數(shù)據(jù)')
ax1.set_xlabel('日期')
plt.legend(loc='upper left')
#坐標(biāo)軸2
ax2 = fig.add_subplot(212)
ax2.plot(net_value_date,daily_growth_rate,'r',label='日增長率')
ax2.plot(net_value_date,daily_jizhun,'b',label='增長率基準(zhǔn)值')
ax2.set_ylabel('日增長率(%)')
plt.legend(loc='upper right')
plt.title('基金凈值數(shù)據(jù)')
plt.show()
-
從整體趨勢上看,該基金自成立后累計凈值呈現(xiàn)的是向上走的趨勢,中間也有過幾次分紅的情況,因此這是一支盈利水平較為不錯的基金,從長期看,該基金有比較大的概率可以盈利。同時目前凈值屬于歷史最高水平,如果進場遇到回調(diào),可能導(dǎo)致資金被套住,應(yīng)該注意風(fēng)險把控。- 從日增長率上看,該基金增長率整體波動范圍不大,較為穩(wěn)定。
2.5查看每年增長率正負(fù)的天數(shù)
2.5.1增加“年”字段
data1=data.iloc[:,0:4] # 這里提取后面分析需要用到的字段
data1['年']=data1['凈值日期'].dt.year # 增加“年”字段
2.5.2正增長和負(fù)增長的數(shù)量及年度增長平均值
# 獲取正增長年月和負(fù)增長年月數(shù)據(jù)
data1_inc=data1[data1['日增長率']>0]
data1_des=data1[data1['日增長率']<0]
data1_g_inc=data1_inc.groupby('年',as_index=False).agg({<!-- -->'日增長率':'count'}).rename(columns\
={<!-- -->'日增長率':'正增長數(shù)量'})
data1_g_des=data1_des.groupby('年',as_index=False).agg({<!-- -->'日增長率':'count'}).rename(\
columns={<!-- -->'日增長率':'負(fù)增長數(shù)量'})
data_g=pd.merge(data1_g_inc,data1_g_des,on='年',how='left')
# 轉(zhuǎn)化百分比函數(shù)
def baifenbi(x):
return ('%.2f%%'%(x*100))
data_g['正增長占比']=(data_g['正增長數(shù)量']/(data_g['正增長數(shù)量']+data_g['負(fù)增長數(shù)量']))
data_g['正增長占比']=data_g['正增長占比'].apply(baifenbi)
data_g
計算每一年的平均增長率
data_year_rate=data1.groupby('年',as_index=False).agg({<!-- -->'日增長率':'mean'}).rename(columns={<!-- -->'日增長率':'日增長率均值'})
data_year_rate.head(6)
-
通過分析15年到20年的數(shù)據(jù)可知,除了18年股市整體大跌之外。其他年份日增長率為正的天數(shù)都是比負(fù)的多;再通過分析當(dāng)年日增長率均值可看出,除了15年和18年日增長率均值為負(fù),其他年份的均值均為正且絕對值相對來說比15年和18年的要大。因此如果長期持有的話,該基金還是能夠有較大的盈利效應(yīng)。
說明:這里只是利用python做一個簡單的數(shù)據(jù)分析,具體選擇基金的時候還需要注意到其他方面的問題。


Python“寶藏級”公眾號【Python之王】專注于Python領(lǐng)域,會爬蟲,數(shù)分,C++,tensorflow和Pytorch等等。
近 2年共原創(chuàng) 100+ 篇技術(shù)文章。創(chuàng)作的精品文章系列有:
日常收集整理了一批不錯的 Python 學(xué)習(xí)資料,有需要的小伙可以自行免費領(lǐng)取。
獲取方式如下:公眾號回復(fù)資料。領(lǐng)取Python等系列筆記,項目,書籍,直接套上模板就可以用了。資料包含算法、python、算法小抄、力扣刷題手冊和 C++ 等學(xué)習(xí)資料!
評論
圖片
表情
