【问题标题】:How to use rolling function to predict a trend based on either Simple Moving Average or some other strategy如何使用滚动功能来预测基于简单移动平均线或其他策略的趋势
【发布时间】:2021-10-02 22:57:15
【问题描述】:

我有一个代码,可以让我得到一只股票的 44 天简单移动平均线,因为它的开盘价、收盘价、最高价、最低价、日期如下:

stocks.sort_index(ascending=False, inplace = True)  # Without reverse, recent rolling mean will be either NaN or equal to the exact value

stocks['44-SMA'] = stocks[Close].rolling(44, min_periods = 1).mean()

我想购买 44-SMA 上升的股票。我可以直观地得到它,但我正在编写一个用于回测自动化的代码。

我的假设是,如果当前平均价格高于过去 5 次平均价格(一周)的平均价格,则存在上升趋势。(有没有其他更好的方法来找到它?)

所以我写了这样的代码:

def assume_trend(df): # last value -1 is the Latest Stock Price after sorting reverse
    '''
    Perform a rolling operation on the df to find the Current Average and the mean of previous 5 averages
    '''
    for i in range(df.shape[0]):
        df.loc[i,'Trend Prediction'] = df.loc[-6-i:-i,'Rolling Mean'].mean() < df.loc[i,'Rolling Mean']

我如何在这里使用rolling,因为它会比这里的循环快。

【问题讨论】:

    标签: python pandas numpy time-series data-science


    【解决方案1】:

    您可以通过以下方式进行:

    import pandas as pd
    import numpy as np
    
    df = pd.DataFrame(dict(a=np.arange(10), b=np.random.randint(1, 10, 10), c=np.random.randn(10)))
    df.loc[:, 'Rolling Mean'] = df.apply(lambda row: df.loc[-5:row.name, 'b'].mean(), axis=1)
    df.loc[:, 'Valid'] = df.apply(lambda row: False if row.name < 5 else (False if df.loc[-5:row.name, 'Rolling Mean'].mean() > df.loc[row.name, 'Rolling Mean'] else True), axis=1)
    df
    

    输出:

        a   b       c       Rolling Mean    Valid
    0   0   5   0.779053    5.000000        False
    1   1   6   -0.822965   5.500000        False
    2   2   8   0.116101    6.333333        False
    3   3   3   -0.716928   5.500000        False
    4   4   3   0.077724    5.000000        False
    5   5   6   0.235477    5.166667        False
    6   6   5   -0.198586   5.142857        False
    7   7   7   0.625347    5.375000        False
    8   8   7   0.798292    5.555556        True
    9   9   5   -0.369337   5.500000        True
    

    干杯

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-17
      • 2013-12-22
      • 1970-01-01
      • 2019-07-26
      • 2012-10-04
      • 2021-07-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多