我来抛砖引玉一下,需要强调的是,收益率没有折算成年化,只是简单的除以投入成本。欢迎大家交流,谢谢!
def get_return_aip(code, s_date, e_date):
info = 'unit_net_value' # unit_net_value: 基金单位净值
df = get_extras(info, code, start_date=s_date, end_date=e_date) # 获取传入基金指定时间段内 单位净值列表
# 只在“周四”定投
list_dates = df.index.tolist()
df['wkday'] = [list_dates[x].isoweekday() for x in range(len(list_dates))]
df = df[df['wkday'] == 4]
capital = 10000 # 单次定投金额
open_commission=0.0015 # 手续费,取蚂蚁金服手续费率
df['capital'] = capital # 每次投入金额
df['quant'] = round(capital/(1+open_commission)/df.iloc[:,0], 2) # 每次定投获得的份额
# Return the cumulative sum of the elements along the given axis.
df['total_qnt'] = df.quant.cumsum() # 计算每次定投后的总份额
df['cost'] = df.capital.cumsum() # 计算每次定投后的总投入成本
df['value'] = round(df['total_qnt']*df.iloc[:, 0], 2) # 计算每次定投后,实际持有总份额的价值
df['ret'] = round((df['value']/df['cost']-1)*100, 2) # 计算每次定投后,收益率
df.to_csv('auto_inv_plan.csv', mode='w', encoding='utf_8_sig') # 写入.csv
# 计算过程的验证代码,待删除
print(df)
cost = len(df)*capital
value = round(df.iloc[-1, 0] * df['quant'].sum(), 2)
print('总投入资金:', cost)
print(value)
print('-------')
print(df.iloc[-1, 0])
print(df['quant'].sum())
print('总投入资金:%s, 期末资金:%s, 总收益率:%.2f%%' %(format(cost,','),
format(value,','), (value/cost-1)*100))
get_return_aip('000971.OF', '2019-8-02', '2020-11-27')
结果如下:
000971.OF wkday capital quant total_qnt cost value ret
2019/8/8 0.859 4 10000 11624.01 11624.01 10000 9985.02 -0.15
2019/8/15 0.86 4 10000 11610.49 23234.5 20000 19981.67 -0.09
2019/8/22 0.89 4 10000 11219.13 34453.63 30000 30663.73 2.21
2019/8/29 0.904 4 10000 11045.38 45499.01 40000 41131.11 2.83
2019/9/5 0.938 4 10000 10645.01 56144.02 50000 52663.09 5.33
2019/9/12 0.938 4 10000 10645.01 66789.03 60000 62648.11 4.41
2019/9/19 0.935 4 10000 10679.17 77468.2 70000 72432.77 3.48
2019/9/26 0.912 4 10000 10948.49 88416.69 80000 80636.02 0.8
2019/10/10 0.926 4 10000 10782.96 99199.65 90000 91858.88 2.07
2019/10/17 0.921 4 10000 10841.5 110041.15 100000 101347.9 1.35
2019/10/24 0.904 4 10000 11045.38 121086.53 110000 109462.22 -0.49
2019/10/31 0.919 4 10000 10865.1 131951.63 120000 121263.55 1.05
2019/11/7 0.942 4 10000 10599.81 142551.44 130000 134283.46 3.29
2019/11/14 0.932 4 10000 10713.54 153264.98 140000 142842.96 2.03
2020-11-28