diff --git a/src/back_trader/backtest_engine.py b/src/back_trader/backtest_engine.py index 761f1c4..add558c 100644 --- a/src/back_trader/backtest_engine.py +++ b/src/back_trader/backtest_engine.py @@ -20,12 +20,15 @@ logger = logging.getLogger(__name__) # 添加项目根目录到Python路径 current_dir = os.path.dirname(os.path.abspath(__file__)) -src_dir = os.path.dirname(current_dir) +project_root = os.path.dirname(os.path.dirname(current_dir)) +src_dir = os.path.join(project_root, 'src') +data_model_dir = os.path.join(src_dir, 'data_process_model') sys.path.append(src_dir) +sys.path.append(data_model_dir) try: - from data_process_model.database_config import init_database - from data_process_model.stock_models import create_stock_kline_model + from database_config import init_database + from stock_models import create_stock_kline_model DATABASE_AVAILABLE = True except ImportError as e: logger.warning(f"数据库模块导入失败: {e}") @@ -115,10 +118,10 @@ class BacktestEngine: for record in query: data_list.append({ 'timestamp': record.timestamp, - 'open_price': float(record.open_price), - 'high_price': float(record.high_price), - 'low_price': float(record.low_price), - 'close_price': float(record.close_price), + 'open': float(record.open), + 'high': float(record.high), + 'low': float(record.low), + 'close': float(record.close), 'volume': record.volume, 'amount': float(record.amount) }) @@ -213,24 +216,68 @@ class BacktestEngine: if price_data.empty: continue - current_price = price_data['close_price'].iloc[0] + current_price = price_data['close'].iloc[0] if signal.action == 'BUY': - # 计算买入股数 - position_ratio = 0.2 # 默认每次使用20%资金 - available_cash = self.portfolio.cash - target_value = available_cash * position_ratio - shares = int(target_value / current_price / 100) * 100 # 向下取整到100的倍数 + # 使用信号中指定的股数,如果没有则按比例计算 + if hasattr(signal, 'shares') and signal.shares > 0: + shares = signal.shares + else: + # 使用信号中指定的金额,如果没有则使用20%资金 + if hasattr(signal, 'amount') and signal.amount > 0: + target_value = min(signal.amount, self.portfolio.cash) + else: + position_ratio = 0.2 # 默认每次使用20%资金 + target_value = self.portfolio.cash * position_ratio + + shares = int(target_value / current_price / 100) * 100 # 向下取整到100的倍数 - if shares > 0: + if shares > 0 and shares * current_price <= self.portfolio.cash: success = self.portfolio.execute_trade( timestamp, signal.stock_code, 'BUY', shares, current_price ) if success: self.performance_analyzer.add_trade(self.portfolio.trades[-1]) + logger.info(f"✅ 买入: {signal.stock_code} {shares}股 @{current_price:.3f}") + + elif signal.action == 'BUY_ALL': + # 全仓买入操作 + target_value = self.portfolio.cash + shares = int(target_value / current_price / 100) * 100 # 向下取整到100的倍数 + + if shares > 0 and shares * current_price <= self.portfolio.cash: + success = self.portfolio.execute_trade( + timestamp, signal.stock_code, 'BUY', shares, current_price + ) + if success: + self.performance_analyzer.add_trade(self.portfolio.trades[-1]) + logger.info(f"🚀 全仓买入: {signal.stock_code} {shares}股 @{current_price:.3f}") elif signal.action == 'SELL': - # 全部卖出 + # 使用信号中指定的股数,如果没有则部分卖出 + position = self.portfolio.get_position(signal.stock_code) + if position and position.shares > 0: + if hasattr(signal, 'shares') and signal.shares > 0: + # 使用指定股数,但不能超过持仓 + shares = min(signal.shares, position.shares) + elif hasattr(signal, 'amount') and signal.amount > 0: + # 按指定金额计算股数 + shares = int(signal.amount / current_price / 100) * 100 + shares = min(shares, position.shares) + else: + # 全部卖出 + shares = position.shares + + if shares > 0: + success = self.portfolio.execute_trade( + timestamp, signal.stock_code, 'SELL', shares, current_price + ) + if success: + self.performance_analyzer.add_trade(self.portfolio.trades[-1]) + logger.info(f"✅ 卖出: {signal.stock_code} {shares}股 @{current_price:.3f}") + + elif signal.action == 'SELL_ALL': + # 清仓操作 position = self.portfolio.get_position(signal.stock_code) if position and position.shares > 0: success = self.portfolio.execute_trade( @@ -238,6 +285,7 @@ class BacktestEngine: ) if success: self.performance_analyzer.add_trade(self.portfolio.trades[-1]) + logger.info(f"🔥 清仓: {signal.stock_code} {position.shares}股 @{current_price:.3f}") except Exception as e: logger.error(f"执行信号失败: {e}") @@ -256,7 +304,7 @@ class BacktestEngine: df = self.data_cache[stock_code] price_data = df[df.index == timestamp] if not price_data.empty: - current_prices[stock_code] = price_data['close_price'].iloc[0] + current_prices[stock_code] = price_data['close'].iloc[0] # 更新投资组合市值 self.portfolio.update_market_values(current_prices) @@ -287,6 +335,11 @@ class BacktestEngine: logger.error("未设置交易策略") return False + # 加载数据 + if not self.load_data_from_database(): + logger.error("数据加载失败") + return False + if not self.data_cache: logger.error("未加载数据") return False diff --git a/src/back_trader/database_test.py b/src/back_trader/database_test.py index f88d415..5d8595a 100644 --- a/src/back_trader/database_test.py +++ b/src/back_trader/database_test.py @@ -34,9 +34,11 @@ def test_database_connection(): print("\n🏦 检查工商银行(601398.SH)分钟数据...") try: + # 使用新的1m周期模型创建函数 model_class = create_stock_kline_model("601398.SH", "1m") count = model_class.select().count() - print(f"✅ 找到 601398.SH 分钟数据: {count} 条记录") + print(f"✅ 找到 601398.SH 1分钟数据: {count} 条记录") + print(f" 表名: {model_class._meta.table_name}") if count > 0: # 查看数据范围 @@ -46,24 +48,39 @@ def test_database_connection(): if first and last: print(f"📅 数据时间范围: {first.timestamp} ~ {last.timestamp}") - # 检查2024年数据 + # 检查2025年数据(根据实际数据时间范围) from datetime import datetime - start_2024 = datetime(2024, 1, 1) - end_2024 = datetime(2024, 12, 31) + start_2025 = datetime(2025, 1, 1) + end_2025 = datetime(2025, 7, 31) - count_2024 = model_class.select().where( - (model_class.timestamp >= start_2024) & - (model_class.timestamp <= end_2024) + count_2025 = model_class.select().where( + (model_class.timestamp >= start_2025) & + (model_class.timestamp <= end_2025) ).count() - print(f"📊 2024年数据: {count_2024} 条记录") + print(f"📊 2025年1-7月数据: {count_2025} 条记录") - # 分钟数据一年大约有 250天 * 4小时 * 60分钟 = 60000条 - if count_2024 > 10000: # 至少要有1万条分钟数据 - print("✅ 2024年分钟数据充足,可以进行回测") + # 分钟数据7个月大约有 150天 * 4小时 * 60分钟 = 36000条 + if count_2025 > 5000: # 至少要有5千条分钟数据 + print("✅ 2025年分钟数据充足,可以进行回测") + + # 额外检查:验证其他周期数据是否存在 + print("\n🔍 验证其他时间周期数据...") + test_periods = ['15m', '30m', '60m'] + for period in test_periods: + try: + tf_model = create_stock_kline_model("601398.SH", period) + tf_count = tf_model.select().where( + (tf_model.timestamp >= start_2025) & + (tf_model.timestamp <= end_2025) + ).count() + print(f" {period}: {tf_count} 条记录 (表名: {tf_model._meta.table_name})") + except Exception as e: + print(f" {period}: ❌ 无法访问 ({e})") + return True else: - print("⚠️ 2024年分钟数据不足,建议检查数据") + print("⚠️ 2025年分钟数据不足,建议检查数据") return False else: print("❌ 未找到数据,请先运行数据下载脚本") diff --git a/src/back_trader/multi_timeframe_ma_backtest_strategy.py b/src/back_trader/multi_timeframe_ma_backtest_strategy.py new file mode 100644 index 0000000..9c19f37 --- /dev/null +++ b/src/back_trader/multi_timeframe_ma_backtest_strategy.py @@ -0,0 +1,413 @@ +#!/usr/bin/env python3 +""" +多时间周期MA策略 - 回测专用版本(最新优化版) +- 使用1分钟数据进行回测 +- 同时监听15分钟/30分钟/60分钟MA5/MA18交叉信号 +- 评分系统:每个金叉+1分,每个死叉-1分(分数最低为0) +- 交易系统:分数从0变成1时全仓买入,仅当分数从1变成0时清仓并置0分 +- 持仓跟踪:跟踪持仓状态和分数变化 +- 无阈值判断:只要发生MA交叉就产生信号 +""" + +import os +import sys +import pandas as pd +import logging +from datetime import datetime, timedelta +from typing import Dict, List, Optional +import numpy as np + +# 添加项目路径 +project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.append(project_root) + +try: + from strategy_base import StrategyBase, Signal + from data_process_model.database_config import init_database + from data_process_model.stock_models import create_stock_kline_model, SUPPORTED_PERIODS +except ImportError as e: + print(f"导入错误: {e}") + sys.exit(1) + +logger = logging.getLogger(__name__) + +class MultiTimeframeMABacktestStrategy(StrategyBase): + """ + 多时间周期MA策略 - 回测版本(最新优化版) + + 特点: + - 回测数据:1分钟K线数据 + - 监听策略:同时监听15分钟/30分钟/60分钟MA5/MA18交叉 + - 评分系统:每个金叉+1分,每个死叉-1分(分数最低为0) + - 交易规则:分数从0变成1时全仓买入,仅当分数从1变成0时清仓并置0分 + - 无阈值判断:只要发生MA交叉就产生信号 + """ + + def __init__(self, stock_code: str = "601398.SH"): + """ + 初始化策略 + + Args: + stock_code: 股票代码 + """ + super().__init__(name="MultiTimeframeMABacktest") + + self.description = "多时间周期MA交叉策略 - 回测版本" + self.stock_code = stock_code + + # MA参数 + self.ma_periods = [5, 18] + + # 信号计算时间周期(用于计算交叉信号) + self.signal_timeframes = ['15m', '30m', '60m'] + + # 股票评分系统 + self.stock_scores = {stock_code: 0} + + # 持仓状态跟踪 + self.holding_stocks = {stock_code: False} # 跟踪是否持有股票 + + # 交易参数 - 全仓交易模式 + # 不再使用固定金额,改为全仓买卖 + + # 仓位管理参数 - 简化版本 + # 不再需要复杂的仓位管理,只有全仓买入和清仓 + + # 时间周期数据缓存 + self.timeframe_data = {} + self.model_cache = {} + + # 上次交叉状态记录(避免重复信号) + self.last_crossover_status = {} + + # 上次信号时的MA差值记录 + self.last_signal_diff = {} + + # 信号记录 + self.crossover_signals = [] + self.signal_stats = {tf: {'golden_cross': 0, 'death_cross': 0} for tf in self.signal_timeframes} + + # 数据更新时间记录 + self.last_update_times = {} + + def initialize(self) -> bool: + """初始化策略""" + try: + # 初始化数据库连接 + init_database() + + logger.info(f"[{self.name}] 初始化多时间周期MA回测策略") + logger.info(f"[{self.name}] 股票代码: {self.stock_code}") + logger.info(f"[{self.name}] 信号时间周期: {self.signal_timeframes}") + logger.info(f"[{self.name}] MA周期: {self.ma_periods}") + logger.info(f"[{self.name}] 交易规则: 分数从0变成1时全仓买入,仅当分数从1变成0时清仓并置0分") + + # 创建各时间周期的数据库模型 + self._create_timeframe_models() + + # 初始化交叉状态 + for tf in self.signal_timeframes: + self.last_crossover_status[tf] = None + self.last_signal_diff[tf] = 0.0 + self.last_update_times[tf] = None + + return True + + except Exception as e: + logger.error(f"[{self.name}] 策略初始化失败: {e}") + return False + + def _create_timeframe_models(self): + """创建各时间周期的数据库模型""" + try: + for tf in self.signal_timeframes: + self.model_cache[tf] = create_stock_kline_model(self.stock_code, tf) + logger.info(f"[{self.name}] 创建 {tf} 模型: {self.model_cache[tf]._meta.table_name}") + except Exception as e: + logger.error(f"[{self.name}] 创建时间周期模型失败: {e}") + + def _get_timeframe_data(self, timeframe: str, end_time: datetime, lookback_periods: int = 50) -> pd.DataFrame: + """ + 获取指定时间周期的数据 + + Args: + timeframe: 时间周期 ('15m', '30m', '60m') + end_time: 结束时间 + lookback_periods: 向前查看的周期数 + + Returns: + pd.DataFrame: 包含MA5和MA18的数据 + """ + try: + if timeframe not in self.model_cache: + return pd.DataFrame() + + model_class = self.model_cache[timeframe] + + # 查询数据,获取end_time之前的数据 + query = model_class.select().where( + model_class.timestamp <= end_time + ).order_by(model_class.timestamp.desc()).limit(lookback_periods) + + # 转换为DataFrame + data = [] + for record in query: + data.append({ + 'timestamp': record.timestamp, + 'open': float(record.open), + 'high': float(record.high), + 'low': float(record.low), + 'close': float(record.close), + 'volume': record.volume + }) + + if not data: + return pd.DataFrame() + + df = pd.DataFrame(data) + df['timestamp'] = pd.to_datetime(df['timestamp']) + df = df.set_index('timestamp').sort_index() + + # 计算移动平均线 + df['MA5'] = df['close'].rolling(window=5, min_periods=5).mean() + df['MA18'] = df['close'].rolling(window=18, min_periods=18).mean() + + return df + + except Exception as e: + logger.error(f"[{self.name}] 获取{timeframe}数据失败: {e}") + return pd.DataFrame() + + def _detect_ma_crossover(self, df: pd.DataFrame, timeframe: str) -> Optional[str]: + """ + 检测MA交叉信号(无阈值判定) + + Args: + df: 包含MA5和MA18的数据 + timeframe: 时间周期 + + Returns: + str: 'golden_cross', 'death_cross', 或 None + """ + if len(df) < 5 or 'MA5' not in df.columns or 'MA18' not in df.columns: + return None + + # 获取最近5个数据点来判断趋势 + recent_data = df.tail(5) + if len(recent_data) < 5: + return None + + ma5_values = recent_data['MA5'].values + ma18_values = recent_data['MA18'].values + + # 检查是否有NaN值 + if np.isnan(ma5_values).any() or np.isnan(ma18_values).any(): + return None + + # 当前MA值 + curr_ma5, curr_ma18 = ma5_values[-1], ma18_values[-1] + + # 分析前几个点的MA关系,确定是否发生了真正的交叉 + # 检查前3个点的MA5和MA18关系 + prev_relations = [] + for i in range(len(ma5_values) - 1): # 不包括最后一个点 + if ma5_values[i] > ma18_values[i]: + prev_relations.append('above') + elif ma5_values[i] < ma18_values[i]: + prev_relations.append('below') + else: + prev_relations.append('equal') + + # 当前关系 + if curr_ma5 > curr_ma18: + curr_relation = 'above' + elif curr_ma5 < curr_ma18: + curr_relation = 'below' + else: + curr_relation = 'equal' + + # 判断是否发生了交叉(去掉阈值判断) + # 金叉:前面大部分时间MA5在MA18下方,现在MA5在MA18上方 + if curr_relation == 'above': + # 检查前面的点是否大部分时间MA5在MA18下方 + below_count = prev_relations.count('below') + if below_count >= len(prev_relations) * 0.6: # 至少60%的时间在下方 + return 'golden_cross' + + # 死叉:前面大部分时间MA5在MA18上方,现在MA5在MA18下方 + elif curr_relation == 'below': + # 检查前面的点是否大部分时间MA5在MA18上方 + above_count = prev_relations.count('above') + if above_count >= len(prev_relations) * 0.6: # 至少60%的时间在上方 + return 'death_cross' + + return None + + def _should_update_timeframe(self, timeframe: str, current_time: datetime) -> bool: + """ + 判断是否需要更新特定时间周期的数据 + + Args: + timeframe: 时间周期 + current_time: 当前时间 + + Returns: + bool: 是否需要更新 + """ + if timeframe not in self.last_update_times or self.last_update_times[timeframe] is None: + return True + + last_update = self.last_update_times[timeframe] + + # 根据时间周期确定更新间隔 + if timeframe == '15m': + interval = timedelta(minutes=15) + elif timeframe == '30m': + interval = timedelta(minutes=30) + elif timeframe == '60m': + interval = timedelta(minutes=60) + else: + interval = timedelta(minutes=1) + + return current_time >= last_update + interval + + def on_data(self, data: pd.DataFrame, timestamp: datetime): + """ + 处理新的1分钟数据 + + Args: + data: 1分钟K线数据(用于回测) + timestamp: 当前时间戳 + """ + try: + stock_code = getattr(data, 'stock_code', self.stock_code) + + if stock_code not in self.stock_scores: + self.stock_scores[stock_code] = 0 + self.holding_stocks[stock_code] = False + + # 只在15分钟的倍数时间点检查买卖点 + # 因为15分钟周期的K线至少15分钟才会变化一次 + if timestamp.minute % 15 != 0: + return # 不是15分钟倍数时间点,跳过检查 + + # 记录交易前的分数 + old_score = self.stock_scores[stock_code] + score_changes = [] # 记录分数变化 + + # 同时检查所有时间周期的交叉信号 + timeframes_to_check = self.signal_timeframes # 始终检查所有时间周期 + + # 为所有时间周期检查交叉信号 + for timeframe in timeframes_to_check: + + # 获取时间周期数据(增加更多历史数据用于交叉判断) + tf_data = self._get_timeframe_data(timeframe, timestamp, lookback_periods=100) + + if tf_data.empty: + logger.debug(f"[{self.name}] {timeframe} 数据为空,跳过") + continue + + # 检测交叉信号 + crossover = self._detect_ma_crossover(tf_data, timeframe) + + # 检查是否与上次信号状态重复 + if crossover: + last_status = self.last_crossover_status.get(timeframe, None) + + # 如果与上次信号相同,跳过(避免重复信号) + if last_status == crossover: + logger.debug(f"[{self.name}] {timeframe} 重复{crossover}信号,跳过") + continue + + # 更新状态 + self.last_crossover_status[timeframe] = crossover + + # 记录当前差值 + ma5_val = tf_data['MA5'].iloc[-1] + ma18_val = tf_data['MA18'].iloc[-1] + curr_diff_abs = abs(ma5_val - ma18_val) + self.last_signal_diff[timeframe] = curr_diff_abs + + if crossover: + # 计算MA差值(绝对金额) + ma5_val = tf_data['MA5'].iloc[-1] + ma18_val = tf_data['MA18'].iloc[-1] + diff_abs = abs(ma5_val - ma18_val) + + # 记录信号 + signal_record = { + 'timestamp': timestamp, + 'timeframe': timeframe, + 'signal_type': crossover, + 'stock_code': stock_code, + 'ma5': ma5_val, + 'ma18': ma18_val, + 'close_price': tf_data['close'].iloc[-1], + 'diff_abs': diff_abs + } + self.crossover_signals.append(signal_record) + + # 更新统计 + self.signal_stats[timeframe][crossover] += 1 + + # 记录分数变化 + if crossover == 'golden_cross': + score_changes.append(1) # 金叉+1分 + elif crossover == 'death_cross': + score_changes.append(-1) # 死叉-1分 + + # 计算总分数变化 + total_score_change = sum(score_changes) + if total_score_change == 0: + return # 没有分数变化,直接返回 + + # 应用分数变化,但分数最低为0 + new_score = max(0, old_score + total_score_change) + self.stock_scores[stock_code] = new_score + + # 根据分数变化生成交易信号 + # 规则:分数从0变成1时全仓买入,仅当分数从1变成0时清仓并置0分 + + if old_score == 0 and new_score == 1: + # 分数从0变成1:全仓买入 + signal = Signal( + stock_code=stock_code, + action='BUY_ALL', # 全仓买入 + amount=0, # 全仓买入时amount设为0 + price=None, + timestamp=timestamp, + reason=f"score_0_to_1_buy_all_change_{total_score_change}" + ) + self.signals.append(signal) + + # 更新持仓状态 + self.holding_stocks[stock_code] = True + + elif old_score == 1 and new_score == 0: + # 仅当分数从1变成0时:清仓并重置分数为0 + signal = Signal( + stock_code=stock_code, + action='SELL_ALL', # 清仓 + amount=0, + price=None, + timestamp=timestamp, + reason=f"score_1_to_0_sell_all_change_{total_score_change}" + ) + self.signals.append(signal) + + # 更新持仓状态和重置分数 + self.holding_stocks[stock_code] = False + self.stock_scores[stock_code] = 0 # 清仓后分数重置为0 + + except Exception as e: + logger.error(f"[{self.name}] 处理数据时出错: {e}") + + def get_signal_statistics(self) -> Dict: + """获取信号统计信息""" + return { + 'total_signals': len(self.crossover_signals), + 'timeframe_stats': self.signal_stats.copy(), + 'current_scores': self.stock_scores.copy(), + 'recent_signals': self.crossover_signals[-10:] if self.crossover_signals else [] + } diff --git a/src/back_trader/multi_timeframe_ma_score_strategy.py b/src/back_trader/multi_timeframe_ma_score_strategy.py index f762c16..2536902 100644 --- a/src/back_trader/multi_timeframe_ma_score_strategy.py +++ b/src/back_trader/multi_timeframe_ma_score_strategy.py @@ -22,7 +22,7 @@ sys.path.append(project_root) try: from strategy_base import StrategyBase, Signal from data_process_model.database_config import init_database - from data_process_model.stock_models import create_stock_kline_model + from data_process_model.stock_models import create_stock_kline_model, create_all_timeframe_models, SUPPORTED_PERIODS except ImportError as e: print(f"导入错误: {e}") sys.exit(1) @@ -31,13 +31,16 @@ logger = logging.getLogger(__name__) class MultiTimeframeMAScoreStrategy(StrategyBase): """ - 多时间周期均线交叉评分策略(简化版) + 多时间周期均线交叉评分策略(修正版) 策略逻辑: 1. 监控15分钟、30分钟、60分钟三个时间周期 2. 每个时间周期只使用MA5和MA20两根移动平均线 - 3. MA5金叉MA20时股票分数+1,死叉时股票分数-1(最低为-1) - 4. 分数-1→0时发出买入信号,分数0→-1时发出卖出信号 + 3. MA5金叉MA20时股票分数+1,死叉时股票分数-1(最低为0) + 4. 分数每增加1分:购买100000元股票 + 5. 分数每减少1分:卖出100000元股票 + 6. 分数从1变为0时:清仓 + 7. 分数等于0时:分数不再减少 """ def __init__(self, ma_periods: List[int] = [5, 20]): @@ -51,15 +54,20 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): name="MultiTimeframeMAScore" ) - self.description = "多时间周期均线交叉评分策略(MA5/MA20简化版)" + self.description = "多时间周期均线交叉评分策略(修正版)" # 简化为只使用MA5和MA20 self.ma_periods = [5, 20] - self.timeframes = ['15m', '30m', '60m'] - # 股票评分系统 - 为每个股票维护分数 + # 使用支持的时间周期:15分钟、30分钟、60分钟 + self.timeframes = SUPPORTED_PERIODS # ['15m', '30m', '60m'] + + # 股票评分系统 - 为每个股票维护分数,默认为0 self.stock_scores = {} + # 交易参数 + self.trade_amount = 100000 # 每次交易金额(元) + # 各时间周期的预加载数据缓存 self.timeframe_data = {} @@ -69,6 +77,11 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): # 数据库模型缓存,避免重复创建 self.model_cache = {} + # 信号记录功能(可选,由外部设置) + # 这些属性将在需要时由回测脚本添加 + # self.crossover_signals = [] # 详细信号记录 + # self.signal_stats = {} # 信号统计 + def initialize(self) -> bool: """初始化策略并预加载所有时间周期数据""" try: @@ -93,19 +106,28 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): stock_code = "601398.SH" # 暂时硬编码 logger.info(f"[{self.name}] 开始预加载时间周期数据...") + logger.info(f"[{self.name}] 支持的时间周期: {self.timeframes}") + + # 使用新的批量创建方法 + try: + self.model_cache = create_all_timeframe_models(stock_code) + logger.info(f"[{self.name}] 成功创建所有时间周期模型") + except Exception as e: + logger.error(f"[{self.name}] 创建模型失败: {e}") + return for timeframe in self.timeframes: try: - # 创建并缓存模型类 if timeframe not in self.model_cache: - self.model_cache[timeframe] = create_stock_kline_model(stock_code, timeframe) + logger.warning(f"[{self.name}] {timeframe} 模型不存在,跳过") + continue model_class = self.model_cache[timeframe] - # 查询2024年所有数据,按时间排序 + # 查询2025年所有数据(根据您的数据),按时间排序 query = model_class.select().where( - (model_class.timestamp >= '2024-01-01') & - (model_class.timestamp <= '2024-12-31') + (model_class.timestamp >= '2025-01-01') & + (model_class.timestamp <= '2025-07-31') ).order_by(model_class.timestamp) # 转换为DataFrame @@ -113,10 +135,10 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): for record in query: data.append({ 'timestamp': record.timestamp, - 'open': float(record.open_price), - 'high': float(record.high_price), - 'low': float(record.low_price), - 'close': float(record.close_price), + 'open': float(record.open), + 'high': float(record.high), + 'low': float(record.low), + 'close': float(record.close), 'volume': record.volume }) @@ -239,20 +261,21 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): return crossovers - def update_stock_score(self, stock_code: str, crossovers: List[tuple]) -> tuple: + def update_stock_score(self, stock_code: str, crossovers: List[tuple], current_price: float) -> tuple: """ - 更新股票评分 + 更新股票评分并生成交易信号 Args: stock_code: 股票代码 crossovers: 交叉信息列表 [(交叉类型, 短期, 长期, 短期值, 长期值)] + current_price: 当前股价 Returns: - tuple: (old_score, new_score, signal, crossover_details) + tuple: (old_score, new_score, trade_signals, crossover_details) """ - # 初始化股票分数为-1 + # 初始化股票分数为0 if stock_code not in self.stock_scores: - self.stock_scores[stock_code] = -1 + self.stock_scores[stock_code] = 0 old_score = self.stock_scores[stock_code] score_change = 0 @@ -267,18 +290,48 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): score_change -= 1 crossover_details.append(f"MA{short_period}↘MA{long_period}") - # 更新分数,确保最低分数为-1 - self.stock_scores[stock_code] = max(-1, self.stock_scores[stock_code] + score_change) - new_score = self.stock_scores[stock_code] + # 更新分数,确保最低分数为0 + new_score = max(0, old_score + score_change) + self.stock_scores[stock_code] = new_score - # 检查买卖信号 (从-1到0时买入,从0到-1时卖出) - signal = None - if old_score == -1 and new_score >= 0: - signal = 'BUY' - elif old_score >= 0 and new_score == -1: - signal = 'SELL' + # 生成交易信号 + trade_signals = [] + actual_score_change = new_score - old_score - return old_score, new_score, signal, crossover_details + if actual_score_change > 0: + # 分数增加:每增加1分买入100000元股票 + for _ in range(actual_score_change): + shares = int(self.trade_amount / current_price / 100) * 100 # 按手买入 + if shares > 0: + trade_signals.append({ + 'action': 'BUY', + 'amount': self.trade_amount, + 'shares': shares, + 'reason': f'分数增加1分,买入{self.trade_amount}元股票' + }) + + elif actual_score_change < 0: + # 分数减少:每减少1分卖出100000元股票 + for _ in range(abs(actual_score_change)): + shares = int(self.trade_amount / current_price / 100) * 100 # 按手卖出 + if shares > 0: + trade_signals.append({ + 'action': 'SELL', + 'amount': self.trade_amount, + 'shares': shares, + 'reason': f'分数减少1分,卖出{self.trade_amount}元股票' + }) + + # 特殊情况:分数从1变为0时清仓 + if old_score == 1 and new_score == 0: + trade_signals.append({ + 'action': 'SELL_ALL', + 'amount': 0, # 清仓不限制金额 + 'shares': 0, # 清仓不限制股数 + 'reason': '分数从1变为0,清仓' + }) + + return old_score, new_score, trade_signals, crossover_details def on_data(self, data: pd.DataFrame, timestamp: datetime) -> List[Signal]: """ @@ -299,9 +352,12 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): # 这里使用我们知道的测试股票代码 stock_code = "601398.SH" # 暂时硬编码,实际应该从data中获取 - # 初始化股票评分为-1 + # 获取当前股价 + current_price = float(data['close'].iloc[-1]) if not data.empty else 7.5 # 默认价格 + + # 初始化股票评分为0 if stock_code not in self.stock_scores: - self.stock_scores[stock_code] = -1 + self.stock_scores[stock_code] = 0 # 限制检查频率 - 只在每15分钟检查一次各时间周期 # 这可以显著减少数据库查询次数 @@ -321,8 +377,31 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): crossovers = self.calculate_ma_crossovers(df) if crossovers: - # 更新股票评分 - old_score, new_score, signal_type, crossover_details = self.update_stock_score(stock_code, crossovers) + # 记录金叉/死叉信号(如果有记录功能) + if hasattr(self, 'crossover_signals') and hasattr(self, 'signal_stats'): + for crossover_type, short_period, long_period, short_value, long_value in crossovers: + # 记录详细信号 + signal_record = { + 'timestamp': timestamp, + 'timeframe': timeframe, + 'type': '金叉' if crossover_type == 'golden' else '死叉', + 'ma5': short_value, + 'ma20': long_value, + 'stock_code': stock_code + } + self.crossover_signals.append(signal_record) + + # 更新统计 + signal_type = 'golden_cross' if crossover_type == 'golden' else 'death_cross' + self.signal_stats[signal_type][timeframe] += 1 + self.signal_stats[signal_type]['total'] += 1 + + logger.info(f"[{self.name}] 📊 记录{signal_record['type']}信号: {timeframe} " + f"MA5={short_value:.3f} MA20={long_value:.3f}") + + # 更新股票评分并获取交易信号 + old_score, new_score, trade_signals, crossover_details = self.update_stock_score( + stock_code, crossovers, current_price) # 记录交叉详情 for crossover_type, short_period, long_period, short_value, long_value in crossovers: @@ -332,19 +411,26 @@ class MultiTimeframeMAScoreStrategy(StrategyBase): logger.info(f"[{self.name}] {stock_code} Score updated: {old_score} -> {new_score}") logger.info(f"[{self.name}] {stock_code} Crossover details: {', '.join(crossover_details)}") - # 如果产生买卖信号,创建Signal对象 - if signal_type: + # 生成交易信号 + for trade_signal in trade_signals: signal = Signal( timestamp=timestamp, stock_code=stock_code, - action=signal_type, + action=trade_signal['action'], strength=1.0, - reason=f"{timeframe} crossovers: {', '.join(crossover_details)} -> {signal_type} signal (score:{old_score}->{new_score})" + reason=f"{timeframe} crossovers: {', '.join(crossover_details)} -> {trade_signal['reason']} (score:{old_score}->{new_score})" ) + + # 为Signal添加额外的交易信息 + if hasattr(signal, 'amount'): + signal.amount = trade_signal['amount'] + if hasattr(signal, 'shares'): + signal.shares = trade_signal['shares'] + signals.append(signal) - logger.info(f"[{self.name}] Generated {signal_type} signal: {stock_code} " - f"Reason: {timeframe} {', '.join(crossover_details)}") + logger.info(f"[{self.name}] Generated {trade_signal['action']} signal: {stock_code} " + f"Reason: {trade_signal['reason']}") except Exception as e: logger.error(f"[{self.name}] Error processing data: {e}") diff --git a/src/back_trader/real_backtest_demo.py b/src/back_trader/real_backtest_demo.py index 99825a9..86791b6 100644 --- a/src/back_trader/real_backtest_demo.py +++ b/src/back_trader/real_backtest_demo.py @@ -1,8 +1,9 @@ """ 真实数据库回测脚本 -使用真实数据库数据对601398.SH(工商银行)进行回测 -回测期间:2024年1月1日 - 2024年12月31日 +使用真实数据库数据对601658.SH(邮储银行)进行回测 +回测期间:2025年1月1日 - 2025年7月31日 +使用修改后的多时间周期MA评分策略 """ import sys @@ -14,6 +15,8 @@ from datetime import datetime current_dir = os.path.dirname(os.path.abspath(__file__)) src_dir = os.path.dirname(current_dir) sys.path.insert(0, src_dir) +data_process_model_dir = os.path.join(src_dir, 'data_process_model') +sys.path.insert(0, data_process_model_dir) # 配置日志 logging.basicConfig( @@ -29,11 +32,16 @@ logger = logging.getLogger(__name__) def progress_callback(current, total, message): - """进度回调函数""" + """进度回调函数 - 每5%输出一次""" progress = (current / total) * 100 - print(f"\r进度: {progress:.1f}% - {message}", end="", flush=True) + + # 每5%输出一次,或者在开始和结束时输出 + if current == 1 or current == total or progress % 5 < (100 / total): + print(f"进度: {progress:.1f}% - {message}") + + # 结束时换行 if current == total: - print() + print("回测进度完成!") def run_real_backtest(): @@ -41,8 +49,9 @@ def run_real_backtest(): try: print("🚀 启动真实数据库回测") print("="*60) - print("📊 测试股票: 601398.SH (工商银行)") - print("📅 回测期间: 2024-01-01 ~ 2024-12-31") + print("📊 测试股票: 601658.SH (邮储银行)") + print("📅 回测期间: 2025-01-01 ~ 2025-07-31") + print("🎯 策略: 多时间周期MA评分策略(修正版)") print("="*60) # 1. 检查数据库连接 @@ -65,45 +74,58 @@ def run_real_backtest(): sys.path.insert(0, current_back_trader_dir) from backtest_engine import BacktestEngine - from ma_cross_strategy import MACrossStrategy - print("✅ 回测引擎导入成功") + from multi_timeframe_ma_backtest_strategy import MultiTimeframeMABacktestStrategy + print("✅ 回测引擎和回测专用策略导入成功") except Exception as e: print(f"❌ 回测引擎导入失败: {e}") return False # 3. 创建回测引擎 print("\n3️⃣ 创建回测引擎...") - engine = BacktestEngine(initial_capital=1000000.0) + engine = BacktestEngine(initial_capital=100000.0) print(f"✅ 回测引擎创建成功,初始资金: {engine.initial_capital:,.2f} 元") # 4. 设置回测参数 print("\n4️⃣ 设置回测参数...") - stock_codes = ["601398.SH"] # 工商银行 + stock_codes = ["601658.SH"] # 邮储银行 engine.set_universe(stock_codes) - engine.set_period("2024-01-01", "2024-12-31", "1m") + engine.set_period("2025-01-01", "2025-07-31", "1m") print(f"✅ 股票池: {stock_codes}") - print("✅ 回测期间: 2024-01-01 ~ 2024-12-31") + print("✅ 回测期间: 2025-01-01 ~ 2025-07-31") print("✅ 数据周期: 分钟线(1m)") - # 5. 创建均线交叉策略 + # 5. 创建多时间周期MA回测策略 print("\n5️⃣ 创建交易策略...") - strategy_params = { - 'short_period': 20, # 20分钟均线(相当于日线的短期) - 'long_period': 60, # 60分钟均线(相当于日线的长期) - 'stop_loss': 0.02, # 2%止损(分钟级别风险控制更严) - 'take_profit': 0.05, # 5%止盈(分钟级别目标更小) - 'position_size': 0.3, # 30%仓位(分钟级别更保守) - 'min_volume': 1000000 # 最小成交量过滤 - } - strategy = MACrossStrategy(strategy_params) + strategy = MultiTimeframeMABacktestStrategy(stock_code="601658.SH") engine.set_strategy(strategy) + print(f"✅ 策略创建成功: {strategy.name}") + print(f" 信号时间周期: {strategy.signal_timeframes}") + print(f" MA周期: {strategy.ma_periods}") + print(f" 交易模式: 全仓买入 + 条件清仓") + + # 初始化策略 + if not strategy.initialize(): + print("❌ 策略初始化失败") + return False + + print("✅ 策略初始化成功") + print("✅ 策略配置:") - print(f" - 短期均线: {strategy_params['short_period']}分钟") - print(f" - 长期均线: {strategy_params['long_period']}分钟") - print(f" - 止损比例: {strategy_params['stop_loss']*100:.1f}%") - print(f" - 止盈比例: {strategy_params['take_profit']*100:.1f}%") - print(f" - 仓位比例: {strategy_params['position_size']*100:.1f}%") + print(f" - 策略名称: 多时间周期MA回测策略(最新优化版)") + print(f" - 移动平均线: MA5 和 MA18") + print(f" - 交叉判定: 无阈值限制(只要发生交叉就产生信号)") + print(f" - 监听策略: 同时监听15分钟、30分钟、60分钟周期") + print(f" - 回测数据周期: 1分钟") + print(f" - 检查频率: 每15分钟一次") + print(f" - 评分与交易规则:") + print(f" * 初始分数: 0分") + print(f" * 每个金叉: +1分") + print(f" * 每个死叉: -1分(分数最低为0)") + print(f" * 分数从0变成1: 全仓买入") + print(f" * 分数从1变成0: 清仓并重置分数为0") + print(f" * 分数从2变成1: 无动作(持续持仓)") + print(f" - 📊 已启用信号记录功能") # 6. 加载历史数据 print("\n6️⃣ 从数据库加载历史数据...") @@ -112,7 +134,7 @@ def run_real_backtest(): print(" 请确认:") print(" - 数据库中存在对应的股票数据表") print(" - 数据时间范围覆盖回测期间") - print(" - 股票代码格式正确(601398.SH)") + print(" - 股票代码格式正确(601658.SH)") return False print("✅ 历史数据加载成功") @@ -121,10 +143,22 @@ def run_real_backtest(): print("\n7️⃣ 开始执行回测...") print(" (这可能需要几分钟时间,请耐心等待)") + # 临时调整日志级别,只显示WARNING及以上级别的日志 + # 这样可以屏蔽买卖交易的详细日志信息,只保留进度信息 + original_log_level = logging.getLogger().level + backtest_logger = logging.getLogger('src.back_trader.backtest_engine') + strategy_logger = logging.getLogger('src.back_trader.multi_timeframe_ma_backtest_strategy') + backtest_logger.setLevel(logging.WARNING) + strategy_logger.setLevel(logging.WARNING) + start_time = datetime.now() success = engine.run_backtest(progress_callback) end_time = datetime.now() + # 恢复原来的日志级别 + backtest_logger.setLevel(original_log_level) + strategy_logger.setLevel(original_log_level) + duration = (end_time - start_time).total_seconds() if success: @@ -137,7 +171,7 @@ def run_real_backtest(): # 9. 保存详细结果 print("\n9️⃣ 保存回测结果...") - result_file = f"backtest_601398_SH_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" + result_file = f"backtest_601658_SH_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" if engine.save_results(result_file): print(f"✅ 详细结果已保存到: {result_file}") @@ -145,27 +179,134 @@ def run_real_backtest(): print("\n🔟 投资组合最终状态:") print(f" 现金余额: {engine.portfolio.cash:,.2f} 元") print(f" 总资产: {engine.portfolio.total_value:,.2f} 元") + total_return = ((engine.portfolio.total_value - 100000) / 100000) * 100 + print(f" 总收益率: {total_return:.2f}%") print(f" 持仓情况:") if engine.portfolio.positions: for stock_code, position in engine.portfolio.positions.items(): - print(f" {stock_code}: {position.shares}股, 市值: {position.market_value:,.2f}元") + if position.shares > 0: + print(f" {stock_code}: {position.shares}股, 市值: {position.market_value:,.2f}元") else: print(" 无持仓") + # 显示策略分数 + if hasattr(strategy, 'stock_scores') and strategy.stock_scores: + print(f"\n🎯 策略分数状态:") + for stock_code, score in strategy.stock_scores.items(): + print(f" {stock_code}: {score}分") + + # 显示金叉/死叉信号统计 + if hasattr(strategy, 'get_signal_statistics'): + stats = strategy.get_signal_statistics() + print(f"\n📊 金叉/死叉信号统计:") + print(f"="*40) + + print(f"📈 总信号数量: {stats['total_signals']}个") + + # 按时间周期显示统计 + timeframe_stats = stats['timeframe_stats'] + for timeframe, counts in timeframe_stats.items(): + print(f"\n⏰ {timeframe} 级别:") + print(f" 🟢 金叉: {counts['golden_cross']}次") + print(f" 🔴 死叉: {counts['death_cross']}次") + + # 显示当前分数 + current_scores = stats['current_scores'] + print(f"\n🎯 当前策略分数:") + for stock_code, score in current_scores.items(): + print(f" {stock_code}: {score}分") + + # 显示最近信号记录 + recent_signals = stats['recent_signals'] + if recent_signals: + print(f"\n📋 金叉/死叉信号记录:") + print("="*120) + print(f"{'序号':<4} {'日期时间':<19} {'时间框架':<8} {'信号类型':<12} {'MA5':<10} {'MA18':<10} {'差值(元)':<10} {'价格':<10} {'分数变化':<10}") + print("-" * 120) + + for idx, signal in enumerate(recent_signals, 1): + timestamp = signal['timestamp'].strftime('%Y-%m-%d %H:%M:%S') + timeframe = signal['timeframe'] + signal_type = signal['signal_type'] + ma5 = f"{signal['ma5']:.4f}" + ma18 = f"{signal['ma18']:.4f}" + price = f"{signal['close_price']:.4f}" + diff_abs = f"{signal.get('diff_abs', 0):.4f}" + + signal_icon = "🟢" if signal_type == "golden_cross" else "🔴" + signal_text = "金叉" if signal_type == "golden_cross" else "死叉" + score_change = "+1" if signal_type == "golden_cross" else "-1" + + print(f"{idx:<4} {timestamp:<19} {timeframe:<8} {signal_icon}{signal_text:<11} {ma5:<10} {ma18:<10} {diff_abs:<10} {price:<10} {score_change:<10}") + + print("="*120) + # 交易记录统计 trades = engine.portfolio.trades if trades: - buy_trades = [t for t in trades if t.action == 'BUY'] - sell_trades = [t for t in trades if t.action == 'SELL'] + buy_trades = [t for t in trades if t.action in ['BUY', 'BUY_ALL']] + sell_trades = [t for t in trades if t.action in ['SELL', 'SELL_ALL']] print(f"\n📈 交易记录统计:") + print("="*80) print(f" 总交易次数: {len(trades)}笔") print(f" 买入交易: {len(buy_trades)}笔") print(f" 卖出交易: {len(sell_trades)}笔") if trades: - total_commission = sum(t.commission for t in trades) - print(f" 总手续费: {total_commission:,.2f}元") + try: + total_commission = sum(getattr(t, 'commission', 0) or 0 for t in trades) + print(f" 总手续费: {total_commission:,.2f}元") + except Exception as e: + print(f" 总手续费: 计算错误 - {e}") + + # 详细交易记录 + if len(trades) > 0: + print(f"\n💰 详细交易记录:") + print("="*120) + print(f"{'序号':<4} {'日期时间':<19} {'操作':<8} {'股票代码':<12} {'股数':<10} {'价格':<10} {'金额':<15} {'手续费':<10} {'原因':<20}") + print("-" * 120) + + for idx, trade in enumerate(trades, 1): + try: + timestamp = trade.timestamp.strftime('%Y-%m-%d %H:%M:%S') if hasattr(trade, 'timestamp') and trade.timestamp else "未知时间" + + # 根据操作类型设置显示文本 + if trade.action == 'BUY_ALL': + action = "全仓买入" + elif trade.action == 'BUY': + action = "普通买入" + elif trade.action == 'SELL_ALL': + action = "全仓卖出" + elif trade.action == 'SELL': + action = "普通卖出" + else: + action = trade.action + + stock_code = getattr(trade, 'stock_code', '未知') + shares = f"{trade.shares:,}" if hasattr(trade, 'shares') and trade.shares is not None else "0" + price = f"{trade.price:.4f}" if hasattr(trade, 'price') and trade.price is not None else "市价" + + # 计算金额:优先使用total_amount,其次是amount,最后计算 + if hasattr(trade, 'total_amount') and trade.total_amount is not None: + amount = f"{trade.total_amount:,.2f}" + elif hasattr(trade, 'amount') and trade.amount is not None: + amount = f"{trade.amount:,.2f}" + elif hasattr(trade, 'shares') and hasattr(trade, 'price') and trade.shares and trade.price: + calculated_amount = trade.shares * trade.price + amount = f"{calculated_amount:,.2f}" + else: + amount = "0.00" + + commission = f"{trade.commission:.2f}" if hasattr(trade, 'commission') and trade.commission is not None else "0.00" + reason = getattr(trade, 'reason', '策略信号') + + action_icon = "🟢" if trade.action in ['BUY', 'BUY_ALL'] else "🔴" + print(f"{idx:<4} {timestamp:<19} {action_icon}{action:<7} {stock_code:<12} {shares:<10} {price:<10} {amount:<15} {commission:<10} {reason:<20}") + except Exception as e: + print(f"{idx:<4} {'错误':<19} {'--':<8} {'数据异常':<12} {'--':<10} {'--':<10} {'--':<15} {'--':<10} {str(e):<20}") + + print("="*120) return True @@ -200,13 +341,13 @@ def check_data_availability(): print("❌ 无法连接数据库") return False - # 检查是否存在601398.SH的分钟数据 + # 检查是否存在601658.SH的分钟数据 try: - model_class = create_stock_kline_model("601398.SH", "1m") + model_class = create_stock_kline_model("601658.SH", "1m") # 检查表是否存在数据 count = model_class.select().count() - print(f"✅ 找到 601398.SH 分钟数据: {count} 条记录") + print(f"✅ 找到 601658.SH 分钟数据: {count} 条记录") if count == 0: print("⚠️ 数据表为空,请先运行数据下载脚本") @@ -224,18 +365,18 @@ def check_data_availability(): if first_record and last_record: print(f"📅 数据时间范围: {first_record.timestamp} ~ {last_record.timestamp}") - # 检查是否覆盖回测期间 + # 检查时间范围 from datetime import datetime - backtest_start = datetime(2024, 1, 1) - backtest_end = datetime(2024, 12, 31) + backtest_start = datetime(2025, 1, 1) + backtest_end = datetime(2025, 7, 31) if first_record.timestamp <= backtest_start and last_record.timestamp >= backtest_end: print("✅ 数据时间范围覆盖回测期间") return True else: print("⚠️ 数据时间范围不完全覆盖回测期间") - print(" 但分钟数据量充足,继续进行回测") - return True # 对于分钟数据,即使不完全覆盖也可以回测 + print(" 但继续进行回测") + return True except Exception as e: print(f"❌ 检查数据时出错: {e}") @@ -250,15 +391,15 @@ def check_data_availability(): def main(): """主函数""" - print("🏦 工商银行(601398.SH)真实数据回测") + print("🏦 邮储银行(601658.SH)真实数据回测") print("="*60) # 首先检查数据可用性 if not check_data_availability(): print("\n💡 建议操作:") print("1. 确认已运行数据下载脚本 (data_process_model/main.py)") - print("2. 确认数据库中存在 601398.SH 的历史数据") - print("3. 确认数据时间范围覆盖 2024年") + print("2. 确认数据库中存在 601658.SH 的历史数据") + print("3. 确认数据时间范围覆盖 2025年1-7月") return # 执行回测 diff --git a/src/back_trader/simple_backtest_engine.py b/src/back_trader/simple_backtest_engine.py index 03e9897..88a8a03 100644 --- a/src/back_trader/simple_backtest_engine.py +++ b/src/back_trader/simple_backtest_engine.py @@ -86,10 +86,10 @@ class SimpleBacktestEngine: data.append({ 'timestamp': date, - 'open_price': open_price, - 'high_price': max(open_price, high, close_price), - 'low_price': min(open_price, low, close_price), - 'close_price': close_price, + 'open': open_price, + 'high': max(open_price, high, close_price), + 'low': min(open_price, low, close_price), + 'close': close_price, 'volume': volume, 'amount': volume * close_price }) @@ -156,7 +156,7 @@ class SimpleBacktestEngine: if price_data.empty: continue - current_price = price_data['close_price'].iloc[0] + current_price = price_data['close'].iloc[0] if signal.action == 'BUY': # 计算买入股数 @@ -199,7 +199,7 @@ class SimpleBacktestEngine: df = self.mock_data[stock_code] price_data = df[df.index == timestamp] if not price_data.empty: - current_prices[stock_code] = price_data['close_price'].iloc[0] + current_prices[stock_code] = price_data['close'].iloc[0] # 更新投资组合市值 self.portfolio.update_market_values(current_prices) diff --git a/src/back_trader/strategy_base.py b/src/back_trader/strategy_base.py index 100b71b..1c832ae 100644 --- a/src/back_trader/strategy_base.py +++ b/src/back_trader/strategy_base.py @@ -51,9 +51,11 @@ class Signal: """交易信号""" timestamp: datetime stock_code: str - action: str # 'BUY', 'SELL', 'HOLD' + action: str # 'BUY', 'SELL', 'SELL_ALL', 'HOLD' strength: float = 1.0 # 信号强度,0-1之间 reason: str = "" # 信号原因 + amount: Optional[float] = None # 交易金额(用于固定金额交易) + price: Optional[float] = None # 目标价格(None表示市价) class Portfolio: diff --git a/src/back_trader/test_ma_crossovers_quick.py b/src/back_trader/test_ma_crossovers_quick.py index c727f39..712795a 100644 --- a/src/back_trader/test_ma_crossovers_quick.py +++ b/src/back_trader/test_ma_crossovers_quick.py @@ -91,10 +91,10 @@ def test_ma_crossovers_quick(): for record in query: data.append({ 'timestamp': record.timestamp, - 'open': float(record.open_price), - 'high': float(record.high_price), - 'low': float(record.low_price), - 'close': float(record.close_price), + 'open': float(record.open), + 'high': float(record.high), + 'low': float(record.low), + 'close': float(record.close), 'volume': record.volume }) diff --git a/src/back_trader/test_multi_timeframe_simple.py b/src/back_trader/test_multi_timeframe_simple.py index f4190fa..3f5145c 100644 --- a/src/back_trader/test_multi_timeframe_simple.py +++ b/src/back_trader/test_multi_timeframe_simple.py @@ -54,10 +54,10 @@ class SimpleMultiTimeframeTest: for record in query: data.append({ 'timestamp': record.timestamp, - 'open': float(record.open_price), - 'high': float(record.high_price), - 'low': float(record.low_price), - 'close': float(record.close_price), + 'open': float(record.open), + 'high': float(record.high), + 'low': float(record.low), + 'close': float(record.close), 'volume': record.volume }) diff --git a/src/data_process_model/main.py b/src/data_process_model/main.py index bf97fd3..00a7ce1 100644 --- a/src/data_process_model/main.py +++ b/src/data_process_model/main.py @@ -27,7 +27,7 @@ g_stock_code_list = [ # 若取某日全量历史数据,时间需要具体到秒,如 "20200427093000" # 开始时间:7月1日 09:30:00 (交易开始时间) -g_start_date = "20250701093000" +g_start_date = "20250101093000" # 结束时间选项 # 选项1: 使用当前日期时间,精确到秒 (推荐用于获取最新数据) @@ -137,7 +137,7 @@ def get_trading_time_range(start_date_str, end_date_str=None, time_format="full" 获取交易时间范围 Args: - start_date_str (str): 开始日期,如 "20250701" + start_date_str (str): 开始日期,如 "20240101" end_date_str (str): 结束日期,None 则使用当前日期 time_format (str): 时间格式类型 diff --git a/src/data_process_model/stock_models.py b/src/data_process_model/stock_models.py index e70ff31..8988f06 100644 --- a/src/data_process_model/stock_models.py +++ b/src/data_process_model/stock_models.py @@ -3,6 +3,7 @@ 只负责数据模型的定义与约束,不包含数据库操作逻辑 """ +from typing import Dict from peewee import DateTimeField, DecimalField, BigIntegerField try: from database_config import BaseModel, get_database @@ -36,31 +37,39 @@ class StockKlineBase(BaseModel): volume = BigIntegerField(help_text="成交量") amount = DecimalField(max_digits=20, decimal_places=2, help_text="成交额", null=True) -def create_stock_kline_model(stock_code: str, period: str = "1d"): +# 支持的K线周期常量 +SUPPORTED_PERIODS = ['1m', '15m', '30m', '60m'] # 添加1m用于回测数据 + +def create_stock_kline_model(stock_code: str, period: str): """ 动态创建股票K线数据表模型 - 使用公共配置的标准化函数确保表名一致性 + 专门用于创建1分钟、15分钟、30分钟、60分钟周期的K线数据模型 Args: - stock_code (str): 股票代码,如 "601658.SH", "000001.SZ" - period (str): 数据周期,如 "1m", "5m", "1d",默认为 "1d" + stock_code (str): 股票代码,如 "601398.SH", "000001.SZ" + period (str): 数据周期,支持 "1m", "15m", "30m", "60m" Returns: type: 动态创建的股票K线模型类 Raises: - ValueError: 当股票代码格式不正确时 + ValueError: 当股票代码格式不正确或周期不支持时 """ + # 验证周期参数 + if period not in SUPPORTED_PERIODS: + raise ValueError(f"不支持的周期: {period},支持的周期为: {SUPPORTED_PERIODS}") + # 使用公共配置标准化股票代码 normalized_code = normalize_stock_code(stock_code) - # 使用公共配置生成表名 - table_name = get_table_name(normalized_code, period) + # 生成表名:kline_{股票代码}_{周期} + # 例如:601398.SH + 15m -> kline_601398_sh_15m + code_part = normalized_code.lower().replace('.', '_') # 601398.SH -> 601398_sh + table_name = f"kline_{code_part}_{period}" # 生成类名 clean_code = normalized_code.lower().replace(".", "_") - clean_period = period.replace(".", "_").replace("/", "_").replace("-", "_").lower() - class_name = f"StockKline_{clean_code}_{clean_period}" + class_name = f"StockKline_{clean_code}_{period}" # 动态创建模型类 model_class = type(class_name, (StockKlineBase,), { @@ -76,6 +85,26 @@ def create_stock_kline_model(stock_code: str, period: str = "1d"): logger.info(f"{LOG_PREFIXES['DATABASE']} 创建股票K线模型: {class_name} -> {table_name}") return model_class +def create_all_timeframe_models(stock_code: str) -> Dict[str, type]: + """ + 为指定股票创建所有时间周期的K线模型 + + Args: + stock_code (str): 股票代码,如 "601398.SH" + + Returns: + Dict[str, type]: 时间周期到模型类的映射字典 + """ + models = {} + for period in SUPPORTED_PERIODS: + try: + models[period] = create_stock_kline_model(stock_code, period) + logger.info(f"{LOG_PREFIXES['DATABASE']} 成功创建 {stock_code} {period} 模型") + except Exception as e: + logger.error(f"{LOG_PREFIXES['DATABASE']} 创建 {stock_code} {period} 模型失败: {e}") + + return models + # 其他可能的模型类可以在这里定义 # class StockInfo(BaseModel): # """股票基本信息模型"""