785 lines
30 KiB
Python
785 lines
30 KiB
Python
"""
|
||
多时间周期均线交叉策略
|
||
|
||
基于15分钟、30分钟、60分钟三个时间周期的均线金叉/死叉信号:
|
||
- 每个时间周期发生金叉时,股票分数+1
|
||
- 每个时间周期发生死叉时,股票分数-1
|
||
- 分数从0变为1时,发出买入信号
|
||
- 分数从1变为0时,发出卖出信号
|
||
- 分数最低为0,不会低于0
|
||
"""
|
||
|
||
import pandas as pd
|
||
import numpy as np
|
||
from datetime import datetime, timedelta
|
||
from typing import Dict, List, Any, Optional, Tuple
|
||
import logging
|
||
import sys
|
||
import os
|
||
|
||
# 添加项目路径
|
||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||
src_dir = os.path.dirname(current_dir)
|
||
sys.path.insert(0, src_dir)
|
||
|
||
from strategy_base import StrategyBase, Signal, Portfolio, Position, Trade
|
||
from data_process_model.technical_indicators import TechnicalIndicators
|
||
from data_process_model.database_config import init_database
|
||
from data_process_model.stock_models import create_stock_kline_model
|
||
|
||
logger = logging.getLogger(__name__)
|
||
|
||
|
||
class MultiTimeFrameMAStrategy(StrategyBase):
|
||
class MultiTimeFrameMAStrategy(StrategyBase):
|
||
"""
|
||
多时间周期均线交叉策略
|
||
|
||
特点:
|
||
1. 监控15分钟、30分钟、60分钟三个时间周期
|
||
2. 每个周期使用5日和20日均线进行金叉死叉判断
|
||
3. 分数系统:金叉+1,死叉-1,最低分数为0
|
||
4. 分数变化触发交易信号
|
||
"""
|
||
|
||
def __init__(self, params: Dict[str, Any]):
|
||
"""
|
||
初始化多时间周期均线交叉策略
|
||
|
||
Args:
|
||
params: 策略参数字典
|
||
"""
|
||
super().__init__(params)
|
||
|
||
# 策略参数
|
||
self.short_ma = params.get('short_ma', 5) # 短期均线周期
|
||
self.long_ma = params.get('long_ma', 20) # 长期均线周期
|
||
self.position_size = params.get('position_size', 0.5) # 仓位大小
|
||
self.stop_loss = params.get('stop_loss', 0.05) # 止损比例
|
||
self.take_profit = params.get('take_profit', 0.10) # 止盈比例
|
||
|
||
# 时间周期配置
|
||
self.timeframes = ['15m', '30m', '60m']
|
||
|
||
# 技术指标计算器
|
||
self.indicators = TechnicalIndicators()
|
||
|
||
# 股票分数系统
|
||
self.stock_scores = {} # {symbol: score}
|
||
self.previous_scores = {} # 记录上一次的分数用于检测变化
|
||
|
||
# 各时间周期的均线状态
|
||
self.ma_states = {} # {symbol: {timeframe: {'short_ma': [], 'long_ma': [], 'last_cross': None}}}
|
||
|
||
# 数据缓存
|
||
self.data_cache = {} # {symbol: {timeframe: DataFrame}}
|
||
|
||
logger.info(f"[Multi-TimeFrame MA Strategy] 初始化多时间周期均线交叉策略")
|
||
logger.info(f"[Multi-TimeFrame MA Strategy] 短期均线: {self.short_ma}日")
|
||
logger.info(f"[Multi-TimeFrame MA Strategy] 长期均线: {self.long_ma}日")
|
||
logger.info(f"[Multi-TimeFrame MA Strategy] 监控时间周期: {self.timeframes}")
|
||
logger.info(f"[Multi-TimeFrame MA Strategy] 仓位大小: {self.position_size*100:.1f}%")
|
||
logger.info(f"[Multi-TimeFrame MA Strategy] 止损: {self.stop_loss*100:.1f}%")
|
||
logger.info(f"[Multi-TimeFrame MA Strategy] 止盈: {self.take_profit*100:.1f}%")
|
||
|
||
def initialize_stock(self, symbol: str):
|
||
"""初始化股票的分数和均线状态"""
|
||
if symbol not in self.stock_scores:
|
||
self.stock_scores[symbol] = 0
|
||
self.previous_scores[symbol] = 0
|
||
self.ma_states[symbol] = {}
|
||
self.data_cache[symbol] = {}
|
||
|
||
for timeframe in self.timeframes:
|
||
self.ma_states[symbol][timeframe] = {
|
||
'short_ma': [],
|
||
'long_ma': [],
|
||
'last_cross': None # 'golden' or 'death' or None
|
||
}
|
||
self.data_cache[symbol][timeframe] = pd.DataFrame()
|
||
|
||
def detect_ma_crossover(self, short_ma: List[float], long_ma: List[float]) -> Optional[str]:
|
||
"""
|
||
检测均线金叉死叉
|
||
|
||
Args:
|
||
short_ma: 短期均线数据
|
||
long_ma: 长期均线数据
|
||
|
||
Returns:
|
||
'golden': 金叉 (短期均线上穿长期均线)
|
||
'death': 死叉 (短期均线下穿长期均线)
|
||
None: 无交叉
|
||
"""
|
||
if len(short_ma) < 2 or len(long_ma) < 2:
|
||
return None
|
||
|
||
# 检查是否有足够的数据且都不是NaN
|
||
if (pd.isna(short_ma[-2]) or pd.isna(long_ma[-2]) or
|
||
pd.isna(short_ma[-1]) or pd.isna(long_ma[-1])):
|
||
return None
|
||
|
||
# 前一天:短期 <= 长期,今天:短期 > 长期 -> 金叉
|
||
if short_ma[-2] <= long_ma[-2] and short_ma[-1] > long_ma[-1]:
|
||
return 'golden'
|
||
|
||
# 前一天:短期 >= 长期,今天:短期 < 长期 -> 死叉
|
||
elif short_ma[-2] >= long_ma[-2] and short_ma[-1] < long_ma[-1]:
|
||
return 'death'
|
||
|
||
return None
|
||
|
||
def load_timeframe_data(self, symbol: str, timeframe: str, current_time: datetime) -> pd.DataFrame:
|
||
"""
|
||
加载指定时间周期的历史数据
|
||
|
||
Args:
|
||
symbol: 股票代码
|
||
timeframe: 时间周期 ('15m', '30m', '60m')
|
||
current_time: 当前时间
|
||
|
||
Returns:
|
||
DataFrame: K线数据
|
||
"""
|
||
try:
|
||
# 计算需要的数据量(确保有足够数据计算均线)
|
||
periods_needed = max(self.short_ma, self.long_ma) + 10
|
||
|
||
# 根据时间周期确定表名
|
||
table_name = f"kline_601398_sh_{timeframe}"
|
||
|
||
# 创建模型
|
||
KlineModel = create_stock_kline_model(table_name)
|
||
|
||
# 查询数据
|
||
query = (KlineModel.select()
|
||
.where(KlineModel.datetime <= current_time)
|
||
.order_by(KlineModel.datetime.desc())
|
||
.limit(periods_needed))
|
||
|
||
data = []
|
||
for record in query:
|
||
data.append({
|
||
'datetime': record.datetime,
|
||
'open': float(record.open),
|
||
'high': float(record.high),
|
||
'low': float(record.low),
|
||
'close': float(record.close),
|
||
'volume': int(record.volume)
|
||
})
|
||
|
||
if not data:
|
||
return pd.DataFrame()
|
||
|
||
df = pd.DataFrame(data)
|
||
df = df.sort_values('datetime').reset_index(drop=True)
|
||
df.set_index('datetime', inplace=True)
|
||
|
||
return df
|
||
|
||
except Exception as e:
|
||
logger.error(f"加载{timeframe}数据失败: {e}")
|
||
return pd.DataFrame()
|
||
|
||
def update_ma_analysis(self, symbol: str, current_time: datetime) -> Dict[str, str]:
|
||
"""
|
||
更新各时间周期的均线分析
|
||
|
||
Args:
|
||
symbol: 股票代码
|
||
current_time: 当前时间
|
||
|
||
Returns:
|
||
Dict: {timeframe: crossover_type} 本次检测到的交叉信号
|
||
"""
|
||
crossovers = {}
|
||
|
||
for timeframe in self.timeframes:
|
||
try:
|
||
# 加载该时间周期的数据
|
||
df = self.load_timeframe_data(symbol, timeframe, current_time)
|
||
|
||
if df.empty or len(df) < max(self.short_ma, self.long_ma):
|
||
continue
|
||
|
||
# 计算均线
|
||
ma_result = self.indicators.ma_from_df(df, [self.short_ma, self.long_ma])
|
||
|
||
short_ma_series = ma_result[f'ma{self.short_ma}']
|
||
long_ma_series = ma_result[f'ma{self.long_ma}']
|
||
|
||
# 转换为列表
|
||
short_ma_values = short_ma_series.tolist()
|
||
long_ma_values = long_ma_series.tolist()
|
||
|
||
# 检测交叉
|
||
crossover = self.detect_ma_crossover(short_ma_values, long_ma_values)
|
||
|
||
if crossover:
|
||
crossovers[timeframe] = crossover
|
||
logger.info(f"[{symbol}] {timeframe} 检测到{crossover}叉: "
|
||
f"短期MA({self.short_ma})={short_ma_values[-1]:.3f}, "
|
||
f"长期MA({self.long_ma})={long_ma_values[-1]:.3f}")
|
||
|
||
# 更新状态
|
||
self.ma_states[symbol][timeframe]['short_ma'] = short_ma_values
|
||
self.ma_states[symbol][timeframe]['long_ma'] = long_ma_values
|
||
self.ma_states[symbol][timeframe]['last_cross'] = crossover
|
||
|
||
except Exception as e:
|
||
logger.error(f"更新{symbol} {timeframe}均线分析失败: {e}")
|
||
|
||
return crossovers
|
||
|
||
def update_stock_score(self, symbol: str, crossovers: Dict[str, str]) -> Tuple[int, int]:
|
||
"""
|
||
更新股票分数
|
||
|
||
Args:
|
||
symbol: 股票代码
|
||
crossovers: 各时间周期的交叉信号
|
||
|
||
Returns:
|
||
Tuple: (previous_score, new_score)
|
||
"""
|
||
previous_score = self.stock_scores[symbol]
|
||
current_score = previous_score
|
||
|
||
for timeframe, crossover_type in crossovers.items():
|
||
if crossover_type == 'golden':
|
||
current_score += 1
|
||
logger.info(f"[{symbol}] {timeframe} 金叉,分数+1")
|
||
elif crossover_type == 'death':
|
||
current_score -= 1
|
||
logger.info(f"[{symbol}] {timeframe} 死叉,分数-1")
|
||
|
||
# 确保分数不低于0
|
||
current_score = max(0, current_score)
|
||
|
||
self.stock_scores[symbol] = current_score
|
||
self.previous_scores[symbol] = previous_score
|
||
|
||
if current_score != previous_score:
|
||
logger.info(f"[{symbol}] 分数变化: {previous_score} -> {current_score}")
|
||
|
||
return previous_score, current_score
|
||
|
||
def process_bar(self, data: Dict[str, Any]) -> List[Signal]:
|
||
"""
|
||
处理新的K线数据
|
||
|
||
Args:
|
||
data: K线数据字典
|
||
|
||
Returns:
|
||
List[Signal]: 生成的交易信号列表
|
||
"""
|
||
symbol = data['symbol']
|
||
current_time = data['datetime']
|
||
current_price = data['close']
|
||
|
||
# 初始化股票状态
|
||
self.initialize_stock(symbol)
|
||
|
||
signals = []
|
||
|
||
try:
|
||
# 更新各时间周期的均线分析
|
||
crossovers = self.update_ma_analysis(symbol, current_time)
|
||
|
||
if not crossovers:
|
||
return signals
|
||
|
||
# 更新股票分数
|
||
previous_score, new_score = self.update_stock_score(symbol, crossovers)
|
||
|
||
# 检查是否需要发出交易信号
|
||
if previous_score == 0 and new_score == 1:
|
||
# 分数从0变为1,发出买入信号
|
||
signal = Signal(
|
||
symbol=symbol,
|
||
action='BUY',
|
||
price=current_price,
|
||
quantity=self._calculate_position_size(current_price),
|
||
timestamp=current_time,
|
||
reason=f"多时间周期金叉信号,分数: {previous_score}->{new_score}"
|
||
)
|
||
signals.append(signal)
|
||
logger.info(f"[{symbol}] 买入信号: 分数{previous_score}->{new_score}, 价格: {current_price}")
|
||
|
||
elif previous_score == 1 and new_score == 0:
|
||
# 分数从1变为0,发出卖出信号
|
||
signal = Signal(
|
||
symbol=symbol,
|
||
action='SELL',
|
||
price=current_price,
|
||
quantity=0, # 全部卖出
|
||
timestamp=current_time,
|
||
reason=f"多时间周期死叉信号,分数: {previous_score}->{new_score}"
|
||
)
|
||
signals.append(signal)
|
||
logger.info(f"[{symbol}] 卖出信号: 分数{previous_score}->{new_score}, 价格: {current_price}")
|
||
|
||
except Exception as e:
|
||
logger.error(f"处理{symbol}数据失败: {e}")
|
||
|
||
return signals
|
||
|
||
def _calculate_position_size(self, price: float) -> int:
|
||
"""计算买入数量"""
|
||
if hasattr(self, 'portfolio') and self.portfolio:
|
||
available_cash = self.portfolio.cash
|
||
target_value = available_cash * self.position_size
|
||
return int(target_value / price / 100) * 100 # 按手数买入
|
||
return 0
|
||
|
||
def check_risk_management(self, portfolio: Portfolio) -> List[Signal]:
|
||
"""
|
||
风险管理检查
|
||
|
||
Args:
|
||
portfolio: 当前投资组合
|
||
|
||
Returns:
|
||
List[Signal]: 风险管理信号
|
||
"""
|
||
signals = []
|
||
|
||
for symbol, position in portfolio.positions.items():
|
||
if position.quantity <= 0:
|
||
continue
|
||
|
||
current_price = position.current_price
|
||
cost_price = position.cost_price
|
||
|
||
if current_price <= 0 or cost_price <= 0:
|
||
continue
|
||
|
||
# 计算收益率
|
||
return_rate = (current_price - cost_price) / cost_price
|
||
|
||
# 止损检查
|
||
if return_rate <= -self.stop_loss:
|
||
signal = Signal(
|
||
symbol=symbol,
|
||
action='SELL',
|
||
price=current_price,
|
||
quantity=0, # 全部卖出
|
||
timestamp=datetime.now(),
|
||
reason=f"止损: {return_rate:.2%} <= -{self.stop_loss:.2%}"
|
||
)
|
||
signals.append(signal)
|
||
logger.info(f"[{symbol}] 止损信号: 收益率{return_rate:.2%}")
|
||
|
||
# 止盈检查
|
||
elif return_rate >= self.take_profit:
|
||
signal = Signal(
|
||
symbol=symbol,
|
||
action='SELL',
|
||
price=current_price,
|
||
quantity=0, # 全部卖出
|
||
timestamp=datetime.now(),
|
||
reason=f"止盈: {return_rate:.2%} >= {self.take_profit:.2%}"
|
||
)
|
||
signals.append(signal)
|
||
logger.info(f"[{symbol}] 止盈信号: 收益率{return_rate:.2%}")
|
||
|
||
return signals
|
||
|
||
def get_strategy_info(self) -> Dict[str, Any]:
|
||
"""获取策略信息"""
|
||
return {
|
||
'name': 'MultiTimeFrameMAStrategy',
|
||
'description': '多时间周期均线交叉策略',
|
||
'timeframes': self.timeframes,
|
||
'short_ma': self.short_ma,
|
||
'long_ma': self.long_ma,
|
||
'position_size': self.position_size,
|
||
'stop_loss': self.stop_loss,
|
||
'take_profit': self.take_profit,
|
||
'current_scores': self.stock_scores.copy()
|
||
}
|
||
|
||
Args:
|
||
params: 策略参数字典
|
||
- short_ma_period: 短期均线周期,默认5
|
||
- long_ma_period: 长期均线周期,默认20
|
||
- timeframes: 监控的时间周期列表,默认['15m', '30m', '60m']
|
||
- position_size: 仓位大小,默认0.3 (30%)
|
||
- min_score_buy: 买入最低分数,默认1
|
||
- max_score_sell: 卖出最高分数,默认0
|
||
"""
|
||
# 设置默认参数
|
||
default_params = {
|
||
'short_ma_period': 5, # 短期均线周期
|
||
'long_ma_period': 20, # 长期均线周期
|
||
'timeframes': ['15m', '30m', '60m'], # 监控时间周期
|
||
'position_size': 0.3, # 仓位大小 30%
|
||
'min_score_buy': 1, # 买入分数阈值
|
||
'max_score_sell': 0 # 卖出分数阈值
|
||
}
|
||
|
||
if params:
|
||
default_params.update(params)
|
||
|
||
super().__init__("多时间周期均线交叉策略", default_params)
|
||
|
||
# 初始化技术指标计算器
|
||
self.indicator_calculator = TechnicalIndicators()
|
||
|
||
# 股票评分系统 {stock_code: score}
|
||
self.stock_scores = {}
|
||
|
||
# 上一次均线状态 {stock_code: {timeframe: {'short_ma': value, 'long_ma': value, 'is_golden': bool}}}
|
||
self.previous_ma_states = {}
|
||
|
||
# 数据库表映射
|
||
self.table_mapping = {
|
||
'15m': 'kline_601398_sh_15m',
|
||
'30m': 'kline_601398_sh_30m',
|
||
'60m': 'kline_601398_sh_60m'
|
||
}
|
||
|
||
logger.info(f"[Multi MA Strategy] 初始化多时间周期均线交叉策略")
|
||
logger.info(f"[Multi MA Strategy] 短期均线: {self.params['short_ma_period']}周期")
|
||
logger.info(f"[Multi MA Strategy] 长期均线: {self.params['long_ma_period']}周期")
|
||
logger.info(f"[Multi MA Strategy] 监控时间周期: {self.params['timeframes']}")
|
||
logger.info(f"[Multi MA Strategy] 仓位大小: {self.params['position_size']*100:.1f}%")
|
||
|
||
def initialize(self):
|
||
"""策略初始化"""
|
||
self.log_info("多时间周期均线交叉策略初始化完成")
|
||
|
||
def on_data(self, data: pd.DataFrame, timestamp: datetime):
|
||
"""
|
||
处理新数据并生成交易信号
|
||
|
||
Args:
|
||
data: 股票数据DataFrame,包含OHLCV等字段
|
||
timestamp: 当前时间戳
|
||
"""
|
||
if data.empty:
|
||
return
|
||
|
||
# 假设数据中包含股票代码信息,或者从索引中获取
|
||
# 这里我们假设处理601398.SH的数据
|
||
stock_code = "601398.SH"
|
||
|
||
try:
|
||
# 获取当前股票的分数
|
||
current_score = self.stock_scores.get(stock_code, 0)
|
||
|
||
# 检查所有时间周期的均线交叉情况
|
||
score_changes = self._check_ma_crossovers(stock_code, timestamp)
|
||
|
||
# 更新股票分数
|
||
new_score = max(0, current_score + score_changes) # 分数不能为负
|
||
previous_score = self.stock_scores.get(stock_code, 0)
|
||
self.stock_scores[stock_code] = new_score
|
||
|
||
# 生成交易信号
|
||
if data['close'].iloc[-1] > 0: # 确保有有效价格
|
||
current_price = data['close'].iloc[-1]
|
||
signal = self._generate_signal(stock_code, previous_score, new_score, current_price, timestamp)
|
||
if signal:
|
||
self.signals.append(signal)
|
||
|
||
# 记录分数变化
|
||
if score_changes != 0:
|
||
logger.info(f"[Multi MA Strategy] {stock_code} 分数变化: {previous_score} → {new_score} (变化: {score_changes:+d})")
|
||
|
||
except Exception as e:
|
||
logger.error(f"[Multi MA Strategy] 处理 {stock_code} 数据失败: {e}")
|
||
|
||
def process_new_data(self, data: Dict, timestamp: datetime) -> List[Signal]:
|
||
"""
|
||
处理新数据并生成交易信号(扩展方法)
|
||
|
||
Args:
|
||
data: 股票数据字典 {stock_code: price_data}
|
||
timestamp: 当前时间戳
|
||
|
||
Returns:
|
||
List[Signal]: 生成的交易信号列表
|
||
"""
|
||
signals = []
|
||
|
||
for stock_code, price_data in data.items():
|
||
try:
|
||
# 获取当前股票的分数
|
||
current_score = self.stock_scores.get(stock_code, 0)
|
||
|
||
# 检查所有时间周期的均线交叉情况
|
||
score_changes = self._check_ma_crossovers(stock_code, timestamp)
|
||
|
||
# 更新股票分数
|
||
new_score = max(0, current_score + score_changes) # 分数不能为负
|
||
previous_score = self.stock_scores.get(stock_code, 0)
|
||
self.stock_scores[stock_code] = new_score
|
||
|
||
# 生成交易信号
|
||
current_price = price_data.get('close', price_data.get('price', 0))
|
||
signal = self._generate_signal(stock_code, previous_score, new_score, current_price, timestamp)
|
||
if signal:
|
||
signals.append(signal)
|
||
|
||
# 记录分数变化
|
||
if score_changes != 0:
|
||
logger.info(f"[Multi MA Strategy] {stock_code} 分数变化: {previous_score} → {new_score} (变化: {score_changes:+d})")
|
||
|
||
except Exception as e:
|
||
logger.error(f"[Multi MA Strategy] 处理 {stock_code} 数据失败: {e}")
|
||
continue
|
||
|
||
return signals
|
||
|
||
def _check_ma_crossovers(self, stock_code: str, timestamp: datetime) -> int:
|
||
"""
|
||
检查所有时间周期的均线交叉情况
|
||
|
||
Args:
|
||
stock_code: 股票代码
|
||
timestamp: 当前时间戳
|
||
|
||
Returns:
|
||
int: 分数变化值(正数表示金叉增加,负数表示死叉减少)
|
||
"""
|
||
total_score_change = 0
|
||
|
||
# 初始化股票的历史状态
|
||
if stock_code not in self.previous_ma_states:
|
||
self.previous_ma_states[stock_code] = {}
|
||
|
||
for timeframe in self.params['timeframes']:
|
||
try:
|
||
# 获取该时间周期的最新数据
|
||
df = self._get_latest_data(stock_code, timeframe, timestamp)
|
||
if df.empty or len(df) < self.params['long_ma_period']:
|
||
continue
|
||
|
||
# 计算均线
|
||
ma_data = self.indicator_calculator.ma_from_df(
|
||
df,
|
||
[self.params['short_ma_period'], self.params['long_ma_period']]
|
||
)
|
||
|
||
short_ma_key = f"ma{self.params['short_ma_period']}"
|
||
long_ma_key = f"ma{self.params['long_ma_period']}"
|
||
|
||
if short_ma_key not in ma_data or long_ma_key not in ma_data:
|
||
continue
|
||
|
||
# 获取最新的均线值
|
||
current_short_ma = ma_data[short_ma_key].iloc[-1]
|
||
current_long_ma = ma_data[long_ma_key].iloc[-1]
|
||
|
||
# 检查是否发生交叉
|
||
crossover_type = self._detect_crossover(
|
||
stock_code, timeframe, current_short_ma, current_long_ma
|
||
)
|
||
|
||
# 根据交叉类型调整分数
|
||
if crossover_type == 'golden':
|
||
total_score_change += 1
|
||
logger.info(f"[Multi MA Strategy] {stock_code}({timeframe}) 金叉: 短线{current_short_ma:.3f} > 长线{current_long_ma:.3f}")
|
||
elif crossover_type == 'death':
|
||
total_score_change -= 1
|
||
logger.info(f"[Multi MA Strategy] {stock_code}({timeframe}) 死叉: 短线{current_short_ma:.3f} < 长线{current_long_ma:.3f}")
|
||
|
||
except Exception as e:
|
||
logger.error(f"[Multi MA Strategy] 检查 {stock_code}({timeframe}) 均线交叉失败: {e}")
|
||
continue
|
||
|
||
return total_score_change
|
||
|
||
def _detect_crossover(self, stock_code: str, timeframe: str, current_short_ma: float, current_long_ma: float) -> Optional[str]:
|
||
"""
|
||
检测均线交叉类型
|
||
|
||
Args:
|
||
stock_code: 股票代码
|
||
timeframe: 时间周期
|
||
current_short_ma: 当前短期均线值
|
||
current_long_ma: 当前长期均线值
|
||
|
||
Returns:
|
||
Optional[str]: 'golden'(金叉), 'death'(死叉), None(无交叉)
|
||
"""
|
||
# 获取上一次的均线状态
|
||
previous_state = self.previous_ma_states[stock_code].get(timeframe, {})
|
||
|
||
# 当前均线关系
|
||
current_is_golden = current_short_ma > current_long_ma
|
||
|
||
# 更新当前状态
|
||
self.previous_ma_states[stock_code][timeframe] = {
|
||
'short_ma': current_short_ma,
|
||
'long_ma': current_long_ma,
|
||
'is_golden': current_is_golden
|
||
}
|
||
|
||
# 如果没有历史状态,不能判断交叉
|
||
if 'is_golden' not in previous_state:
|
||
return None
|
||
|
||
previous_is_golden = previous_state['is_golden']
|
||
|
||
# 检测交叉
|
||
if not previous_is_golden and current_is_golden:
|
||
return 'golden' # 金叉:从死叉状态转为金叉状态
|
||
elif previous_is_golden and not current_is_golden:
|
||
return 'death' # 死叉:从金叉状态转为死叉状态
|
||
|
||
return None # 无交叉
|
||
|
||
def _get_latest_data(self, stock_code: str, timeframe: str, timestamp: datetime) -> pd.DataFrame:
|
||
"""
|
||
获取指定时间周期的最新数据
|
||
|
||
Args:
|
||
stock_code: 股票代码
|
||
timeframe: 时间周期 ('15m', '30m', '60m')
|
||
timestamp: 当前时间戳
|
||
|
||
Returns:
|
||
pd.DataFrame: 最新的K线数据
|
||
"""
|
||
# 计算查询时间范围(确保有足够的数据计算均线)
|
||
periods_needed = max(self.params['long_ma_period'] * 2, 100)
|
||
|
||
if timeframe == '15m':
|
||
start_time = timestamp - timedelta(minutes=15 * periods_needed)
|
||
elif timeframe == '30m':
|
||
start_time = timestamp - timedelta(minutes=30 * periods_needed)
|
||
elif timeframe == '60m':
|
||
start_time = timestamp - timedelta(hours=1 * periods_needed)
|
||
else:
|
||
start_time = timestamp - timedelta(days=periods_needed)
|
||
|
||
# 格式化时间
|
||
start_time_str = start_time.strftime('%Y-%m-%d')
|
||
end_time_str = timestamp.strftime('%Y-%m-%d')
|
||
|
||
# 使用数据管理器获取数据
|
||
with StockDataManager() as data_manager:
|
||
df = data_manager.read_stock_data(stock_code, timeframe, start_time_str, end_time_str)
|
||
|
||
return df
|
||
|
||
def _generate_signal(self, stock_code: str, previous_score: int, new_score: int,
|
||
current_price: float, timestamp: datetime) -> Optional[Signal]:
|
||
"""
|
||
根据分数变化生成交易信号
|
||
|
||
Args:
|
||
stock_code: 股票代码
|
||
previous_score: 之前的分数
|
||
new_score: 新的分数
|
||
current_price: 当前价格
|
||
timestamp: 时间戳
|
||
|
||
Returns:
|
||
Optional[Signal]: 交易信号或None
|
||
"""
|
||
if current_price <= 0:
|
||
return None
|
||
|
||
# 分数从0变成1:买入信号
|
||
if previous_score == 0 and new_score >= self.params['min_score_buy']:
|
||
return Signal(
|
||
timestamp=timestamp,
|
||
stock_code=stock_code,
|
||
action='BUY',
|
||
strength=1.0,
|
||
reason=f"多时间周期金叉买入 (分数: {previous_score}→{new_score})"
|
||
)
|
||
|
||
# 分数从1变成0:卖出信号
|
||
elif previous_score >= 1 and new_score <= self.params['max_score_sell']:
|
||
position = self.portfolio.get_position(stock_code)
|
||
if position and position.shares > 0:
|
||
return Signal(
|
||
timestamp=timestamp,
|
||
stock_code=stock_code,
|
||
action='SELL',
|
||
strength=1.0,
|
||
reason=f"多时间周期死叉卖出 (分数: {previous_score}→{new_score})"
|
||
)
|
||
|
||
return None
|
||
|
||
def get_strategy_info(self) -> Dict:
|
||
"""
|
||
获取策略信息
|
||
|
||
Returns:
|
||
Dict: 策略信息字典
|
||
"""
|
||
return {
|
||
'name': '多时间周期均线交叉策略',
|
||
'version': '1.0.0',
|
||
'description': '基于15分钟、30分钟、60分钟均线金叉/死叉的评分系统',
|
||
'timeframes': self.params['timeframes'],
|
||
'ma_periods': f"{self.params['short_ma_period']}/{self.params['long_ma_period']}",
|
||
'current_scores': self.stock_scores.copy()
|
||
}
|
||
|
||
|
||
# 便捷函数:创建策略实例
|
||
def create_multi_timeframe_ma_strategy(params: Optional[Dict] = None) -> MultiTimeframeMAStrategy:
|
||
"""
|
||
创建多时间周期均线交叉策略实例
|
||
|
||
Args:
|
||
params: 可选的策略参数
|
||
|
||
Returns:
|
||
MultiTimeframeMAStrategy: 策略实例
|
||
"""
|
||
return MultiTimeframeMAStrategy(params)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# 测试代码
|
||
print("🧪 多时间周期均线交叉策略测试")
|
||
|
||
# 初始化数据库
|
||
if not init_database():
|
||
print("❌ 数据库连接失败")
|
||
exit(1)
|
||
|
||
try:
|
||
# 创建策略
|
||
strategy = create_multi_timeframe_ma_strategy({
|
||
'short_ma_period': 5,
|
||
'long_ma_period': 20,
|
||
'timeframes': ['15m', '30m', '60m'],
|
||
'position_size': 0.3
|
||
})
|
||
|
||
print("✅ 策略创建成功")
|
||
print(f"📊 策略信息: {strategy.get_strategy_info()}")
|
||
|
||
# 模拟数据测试
|
||
test_data = pd.DataFrame({
|
||
'close': [5.85],
|
||
'volume': [1000000],
|
||
'open': [5.80],
|
||
'high': [5.90],
|
||
'low': [5.75]
|
||
}, index=[datetime.now()])
|
||
|
||
test_timestamp = datetime.now()
|
||
strategy.on_data(test_data, test_timestamp)
|
||
|
||
print(f"🎯 生成信号数量: {len(strategy.signals)}")
|
||
for signal in strategy.signals:
|
||
print(f" {signal}")
|
||
|
||
except Exception as e:
|
||
print(f"❌ 测试失败: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
finally:
|
||
close_database()
|