import tushare as ts
import xlrd
import pandas as pd
import matplotlib.pyplot as plt
ts.set_token('**********************')
pro = ts.pro_api()
def strategy_invest(fund,money,c_rate,be_data,en_date):
df = pro.fund_nav(ts_code=fund)
df.sort_values(by=['end_date'],inplace=True)#按时间排序从小到大
df = df.reset_index(drop=True)#index重新标记
df['交易时间'] = pd.to_datetime(df['end_date'])
df=df[['交易时间','unit_nav']]#只选日期,和净值
#设置投资时间
df=df[df['交易时间']>=be_data]
df=df[df['交易时间']<=en_date]
df["每次投入资金"]=money
df["累计投入资金"]=df["每次投入资金"].cumsum()
c_rate=0.002
df["每次数量"]=df["每次投入资金"]/df['unit_nav']*(1-c_rate)
df["累计数量"]=df["每次数量"].cumsum()
df["盈亏"]=df["累计数量"]*df['unit_nav']-df["累计投入资金"]
df["收益率"]=df["盈亏"]/df["累计投入资金"]*100
return df
def get_draw(df):
dfplot=df.copy()
dfplot.index=dfplot["交易时间"]
dfplot[["收益率"]].plot()
plt.rcParams['font.sans-serif']=['SimHei'] #用来正常显示中文标签
plt.rcParams['axes.unicode_minus']=False #用来正常显示负号
return plt.show()
def average_invest(df):
dfstrategy=df.copy()
dfstrategy["移动平均值"] = dfstrategy['unit_nav'].rolling(60).mean() # 计算移动平均值
dfstrategy=dfstrategy[["交易时间","unit_nav","移动平均值"]]
dfstrategy.loc[dfstrategy['unit_nav']<=(dfstrategy["移动平均值"]*0.97),"每次投入资金"]=200
dfstrategy.fillna(0,inplace=True)
dfstrategy["累计投入资金"]=dfstrategy["每次投入资金"].cumsum()
c_rate=0.002
dfstrategy["每次数量"]=dfstrategy["每次投入资金"]/dfstrategy['unit_nav']*(1-c_rate)
dfstrategy["累计数量"]=dfstrategy["每次数量"].cumsum()
dfstrategy["盈亏"]=dfstrategy["累计数量"]*dfstrategy['unit_nav']-dfstrategy["累计投入资金"]
dfstrategy["收益率"]=dfstrategy["盈亏"]/dfstrategy["累计投入资金"]*100
return dfstrategy
df=strategy_invest(fund="001632.OF",money=50,be_data="2019-04-03",en_date="2020-04-04",c_rate=0.002)
dfstrategy=average_invest(df)
df=df[["交易时间","unit_nav","累计投入资金","盈亏","收益率"]]
dfstrategy=dfstrategy[["交易时间","unit_nav","累计投入资金","盈亏","收益率"]]
print(df.tail(3))
get_draw(df)
print(dfstrategy.tail(3))
get_draw(dfstrategy)