def fit_fun(new_pos): # 目标函数
# lz_dim = [0.1, 0.2, 0.3, 0.4, 0.1, 0.2, 0.3, 0.4]
#print(new_pos[0])
Rx = 0.04 # 期望值
df = pd.read_csv("./2021年.csv", encoding='gbk')
df.insert(1, "粒子维度", new_pos[0]) # 在第一列插入粒子维数列
print(new_pos[0])
index_lst = list(df.columns) # 列索引
# 列索引循环读取数据
total = 0
for num in range(2, len(index_lst)-1): # 第二列到第n-1列是不同日期的收益率,最后一列是均值。
print(index_lst[num])
df["E_xr"] = df["粒子维度"] * df[index_lst[num]] # 粒子占比*不同股票每天的收益率
res = sum(df["E_xr"]) - Rx # 当天收益率- 预期收益率
print("res",res)
if res < 0: # 若当天收益率没有预期收益率高,也就是负值,
res1 =np.square(res) # 下半方差求平方
print("res1", res1)
total = total + res1 # 依次(占比*每天日期)求和
print("total",total)
break
total1 = (1 / 52) * total # (1/T)*total;总的下半方差
print("total1",total1)
res2 = Rx - sum(df["粒子维度"] * df["均值"]) # 如果预期收益率大于投资组合收益率,就加上惩罚项
if res2> 0:
total = total1 + 1000* res2 # 惩罚项:1000*res1
return total
第一个for循环计算的是f(x)=前半部分公式,if判断(红色框-0.04),若<0就求平方,再求和。
问题1:代码total1=(1/52)*total 是绿色框,T=52,,这样写对么?
问题2:公式+后面的用res2,这样连接对么,应该怎么改?