我想运行两个 for 循环,在其中我计算基于移动平均交叉的假设交易策略的年化回报。这很简单:只要“较快”的 MA 越过“较慢”的 MA,就做多。否则转移到现金。
我的数据如下所示:
我的代码:
rets = {}
ann_rets = {}
#Nested Loop to calculate returns
for short in range(20, 200):
for long in range(short + 1, 200):
#Calculate cumulative return
rets[short,long] = (aapl[short,long][-1] - aapl[short,long][1]) / aapl[short,long][1]
#calculate annualized return
ann_rets[short,long] = (( 1 + rets[short,long]) ** (12 / D))-1
我得到的错误信息如下:
TypeError: list indices must be integers or slices, not tuple
编辑:使用字典工作正常。下面的屏幕截图显示了我目前卡在哪里。我想要最后三列: (SMA_1,SMA_2,Ann_rets) SMA_1:第一个移动平均线,例如 20 SMA_2:第二个移动平均线,例如 50 Ann_rets:在上面的循环中计算的年化回报