Python 计算多个移动平均交叉点

Python 计算多个移动平均交叉点,python,moving-average,Python,Moving Average,我想计算多个移动平均线交叉点 我的目标是从short=20和long=21开始。一旦短期移动平均线穿过多头,我将在特定的基础上做多。我想把long变量从21增加到200,然后从short=21和long=22开始,重复这个过程 我的嵌套循环如下所示: #Calculate moving averages first for GD in range(20,200,1): aapl[GD] = aapl.Adj_Close.rolling(GD).mean() #Calculate MA

我想计算多个移动平均线交叉点

我的目标是从short=20和long=21开始。一旦短期移动平均线穿过多头,我将在特定的基础上做多。我想把long变量从21增加到200,然后从short=21和long=22开始,重复这个过程

我的嵌套循环如下所示:

#Calculate moving averages first
for GD in range(20,200,1):
    aapl[GD] = aapl.Adj_Close.rolling(GD).mean()

#Calculate MA crossovers
short = 20
long = 21
while short < 200:
    while long < 200:
        aapl[short,long] = np.where(aapl[short] > aapl[long],1,0)
        long = long + 1
    short = short + 1
short = 20
while short < 200:
    long = short + 1
    while long < 200:
        aapl[short,long] = np.where(aapl[short] > aapl[long],1,0)
        long = long + 1
    short = short + 1
#首先计算移动平均值
对于范围(20200,1)内的GD:
aapl[GD]=aapl.Adj_Close.rolling(GD).mean()
#计算MA交叉
短=20
长=21
短时间<200时:
当长度<200时:
aapl[short,long]=np.其中(aapl[short]>aapl[long],1,0)
长=长+1
短=短+1

如何更改代码,使嵌套循环重复,直到我计算了所有可能的交叉?

您需要重置外部循环的每个迭代
long
。设置一次不起作用,需要每次都设置。我猜想您希望它比
short
大一个,所以如下所示:

#Calculate moving averages first
for GD in range(20,200,1):
    aapl[GD] = aapl.Adj_Close.rolling(GD).mean()

#Calculate MA crossovers
short = 20
long = 21
while short < 200:
    while long < 200:
        aapl[short,long] = np.where(aapl[short] > aapl[long],1,0)
        long = long + 1
    short = short + 1
short = 20
while short < 200:
    long = short + 1
    while long < 200:
        aapl[short,long] = np.where(aapl[short] > aapl[long],1,0)
        long = long + 1
    short = short + 1