54 lines
1.4 KiB
Python
54 lines
1.4 KiB
Python
"""SMA 双均线交叉策略"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import numpy as np
|
|
import raptorbt
|
|
|
|
from .base import Strategy, SignalResult
|
|
|
|
|
|
class SmaCrossStrategy(Strategy):
|
|
"""快慢 SMA 金叉买入、死叉卖出"""
|
|
|
|
name = "sma_cross"
|
|
|
|
def __init__(self, fast: int = 10, slow: int = 20):
|
|
self.fast = fast
|
|
self.slow = slow
|
|
|
|
def warmup_bars(self) -> int:
|
|
return self.slow + 1
|
|
|
|
def generate_signals(self, df) -> SignalResult:
|
|
close = df["close"].values.astype(np.float64)
|
|
sma_fast = raptorbt.sma(close, period=self.fast)
|
|
sma_slow = raptorbt.sma(close, period=self.slow)
|
|
|
|
entries = self.cross_above(sma_fast, sma_slow).astype(bool)
|
|
exits = self.cross_below(sma_fast, sma_slow).astype(bool)
|
|
entries, exits = self.apply_warmup(entries, exits)
|
|
|
|
return SignalResult(
|
|
entries=entries,
|
|
exits=exits,
|
|
direction=1,
|
|
extra={"sma_fast": sma_fast, "sma_slow": sma_slow},
|
|
)
|
|
|
|
def build_config(self) -> raptorbt.PyBacktestConfig:
|
|
config = raptorbt.PyBacktestConfig(
|
|
initial_capital=100000.0,
|
|
fees=0.001,
|
|
slippage=0.0005,
|
|
)
|
|
config.set_fixed_stop(0.02)
|
|
config.set_fixed_target(0.04)
|
|
return config
|
|
|
|
def description(self) -> str:
|
|
return f"SMA({self.fast})/SMA({self.slow}) 双均线交叉, 2% 止损/4% 止盈"
|
|
|
|
|
|
STRATEGY_CLASS = SmaCrossStrategy
|