首页 > 解决方案 > 如何使用滚动功能来预测基于简单移动平均线或其他策略的趋势

问题描述

我有一个代码,我可以在其中获得单只股票的 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在这里使用,因为它会比这里的循环超级快。

标签: pythonpandasnumpytime-seriesdata-science

解决方案


您可以通过以下方式执行此操作:

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

干杯


推荐阅读