如题,这个项目是2021年写的,仅作参考:
#!/usr/bin/env python
# coding: utf-8
# In[47]:
import pandas as pd
import datetime
from dateutil.relativedelta import relativedelta
# In[48]:
# 设置参数----------------
# 设置参数----------------
# 设置参数----------------
df_mx= pd.read_excel('基金净值明细.xlsx') # 明细表
start_date = '2021-5-21' # 初始定投时间
start_money = 1000 # 初始定投金额
name_csv='result.csv'
# 设置参数----------------
# 设置参数----------------
# 设置参数----------------
# In[49]:
df_mx = df_mx.set_index('Getdata.净值日期')
df_mx.index = pd.to_datetime(df_mx.index) # 转为时间格式
df_mx.sort_index(inplace=True)
work_days = df_mx.index.tolist()
start_date = pd.to_datetime(start_date) # 转换为时间格式
start_day = start_date # 计算定投日
next_day = pd.to_datetime(start_date) + datetime.timedelta(days=1)
def get_next_workday(t): # 非工作日转换为临近一个可以申购的交易日
num=0
while True:
next_day = t + datetime.timedelta(days=num)
if next_day in work_days and df_mx.loc[next_day]['Getdata.申购状态']!= '封闭期':
return next_day
num+=1
if start_date in work_days and df_mx.loc[start_date]['Getdata.申购状态']!= '封闭期':
start_date = start_date
else:
start_date = get_next_workday(start_date)
# 构造定投日
the_days = []
num=1
while True:
the_day = start_day + relativedelta(months=num)
if the_day < df_mx.index.max():
if the_day in work_days:
the_days.append(the_day)# 定投日
else:
the_days.append(get_next_workday(the_day)) # 定投日
num+=1
else:
break
# In[50]:
import csv
def save_to_csv(items,name_csv):
'''
items:列表
name_csv:csv文件名
'''
with open(name_csv,'a',newline="") as f:
writer = csv.writer(f)
writer.writerow(items)
# In[51]:
# 开始定投策略
num=1
money = start_money
jingdu = 10 # 计算精度
# 核查初始时间是否为工作日
if start_day not in work_days:
start_day = get_next_workday(start_day)
items=['开始',start_day,round(money,jingdu),0]
print(items)
save_to_csv(items,name_csv)
try:
while True:
next_day = start_date + datetime.timedelta(days=num)
if next_day in work_days: # 计算日收益
money = money*(1+df_mx.loc[next_day]['Getdata.日增长率'])
shouyi = round((money-start_money)/start_money,6)
print('正常:',next_day,round(money,jingdu),shouyi)
items=['正常',next_day,round(money,jingdu),shouyi]
save_to_csv(items,name_csv)
# f.write('当前:'+str(next_day)+str(money)+'\n')
# 定投日
if next_day in the_days:
if (money-start_money)/start_money < 0: # 仅仅收益为-
money=money+1000
start_money = money
shouyi = round((money-start_money)/start_money,jingdu)
print('追加--------->:',next_day,round(money,jingdu),shouyi)
items=['追加',next_day,round(money,jingdu),shouyi]
save_to_csv(items,name_csv)
# f.write('追加--------->:'+str(next_day)+str(money)+'\n')
# 计算收益
if (money-start_money)/start_money>0.1:
shouyi = round((money-start_money)/start_money,jingdu)
print('止盈+++++++++++:',next_day,round(money,jingdu),shouyi)
items=['止盈',next_day,round(money,jingdu),shouyi]
save_to_csv(items,name_csv)
# f.write('止盈+++++++++++:'+str(next_day)+str(money)+'\n')
break
num+=1
except:
pass
# In[52]:
1000*(1-0.0263)
# In[ ]: