【发布时间】:2018-05-11 15:43:28
【问题描述】:
我想根据简单移动平均线 (SMA) 交叉计算股票的买入和卖出信号。只要 SMA_short 高于 SMA_long(即 SMA_difference > 0),就应该发出买入信号。为了避免仓位被过快卖出,我希望只有在 SMA_short 大幅移动超过交叉点时才发出卖出信号(即 SMA_difference
我通过这个help 来实现它(见下文):
- 买入和卖出信号由 in 和 out 指示。
- 列Position首先考虑buy_limit。
- 在 Position_extended 中,然后为 SMA_short 刚刚穿过 SMA_long 的所有情况设置一个 in (SMA_short SMA_long) 但 SMA_short > -1。为此,它考虑了 i-1 的位置扩展,以防超过一天前交叉但 SMA_short 仍然存在:
0 > SMA_short > -1。
Python 代码
import pandas as pd
import numpy as np
index = pd.date_range('20180101', periods=6)
df = pd.DataFrame(index=index)
df["SMA_short"] = [9,10,11,10,10,9]
df["SMA_long"] = 10
df["SMA_difference"] = df["SMA_short"] - df["SMA_long"]
buy_limit = 0
sell_limit = -1
df["Position"] = np.where((df["SMA_difference"] > buy_limit),"in","out")
df["Position_extended"] = df["Position"]
for i in range(1,len(df)):
df.loc[index[i],"Position_extended"] = \
np.where((df.loc[index[i], "SMA_difference"] > sell_limit) \
& (df.loc[index[i-1],"Position_extended"] == "in") \
,"in",df.loc[index[i],'Position'])
print df
结果是:
SMA_short SMA_long SMA_difference Position Position_extended
2018-01-01 9 10 -1 out out
2018-01-02 10 10 0 out out
2018-01-03 11 10 1 in in
2018-01-04 10 10 0 out in
2018-01-05 10 10 0 out in
2018-01-06 9 10 -1 out out
该代码有效,但是,它使用了for 循环,这大大减慢了脚本的速度,并且在此分析的更大范围内变得不适用。由于 SMA 交叉是一种使用率很高的工具,我想知道是否有人可以为此找到更优雅、更快的解决方案。
【问题讨论】:
标签: python pandas dataframe moving-average