diff --git a/.idea/vcs.xml b/.idea/vcs.xml index 94a25f7..bc9452c 100644 --- a/.idea/vcs.xml +++ b/.idea/vcs.xml @@ -2,5 +2,6 @@ + \ No newline at end of file diff --git a/strategies/macd_strategy.py b/strategies/macd_strategy.py index 773648e..8eb634f 100644 --- a/strategies/macd_strategy.py +++ b/strategies/macd_strategy.py @@ -117,7 +117,7 @@ class MacdTrendStrategy(Strategy): self.buy() # 开多仓 # 卖出条件: MACD 死叉 OR 价格 < EMA - elif crossover(self.signal, self.macd) or self.data.Close[-1] < self.ema[-1]: + elif self.position.size > 0 and (crossover(self.signal, self.macd) or self.data.Close[-1] < self.ema[-1]): self.position.close() # 平掉多仓 diff --git a/strategies/sma_strategy.py b/strategies/sma_strategy.py index 87bddee..67b0a65 100644 --- a/strategies/sma_strategy.py +++ b/strategies/sma_strategy.py @@ -12,7 +12,6 @@ SMA 双均线交叉策略 - SMA120: 120 日简单移动平均线 """ -import pandas as pd from backtesting import Strategy from backtesting.lib import crossover @@ -84,13 +83,11 @@ class SmaCross(Strategy): """ # 金叉:短期均线上穿长期均线 if crossover(self.data.sma10, self.data.sma30): - self.position.close() # 先平掉现有仓位 self.buy() # 开多仓 # 死叉:短期均线下穿长期均线 - elif crossover(self.data.sma30, self.data.sma10): - self.position.close() # 先平掉现有仓位 - self.sell() # 开空仓 + elif self.position.size > 0 and crossover(self.data.sma30, self.data.sma10): + self.position.close() # 开空仓 # 导入 talib (必须在文件末尾,因为 calculate_indicators 函数中使用了 talib)