From 5afb8ddcd12119721fda4348997f01c0687882c8 Mon Sep 17 00:00:00 2001 From: lanyuanxiaoyao Date: Wed, 28 Jan 2026 10:30:28 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E5=8D=96=E5=87=BA=E9=80=BB?= =?UTF-8?q?=E8=BE=91=E7=9A=84=E5=AE=9E=E7=8E=B0=EF=BC=8C=E4=B8=8D=E5=85=81?= =?UTF-8?q?=E8=AE=B8=E5=8D=96=E7=A9=BA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .idea/vcs.xml | 1 + strategies/macd_strategy.py | 2 +- strategies/sma_strategy.py | 7 ++----- 3 files changed, 4 insertions(+), 6 deletions(-) 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)