【发布时间】: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