完善买卖流程,优化回测后的买卖点K线图展示
This commit is contained in:
parent
6b32e761a4
commit
f8aff1184b
File diff suppressed because it is too large
Load Diff
@ -239,6 +239,10 @@ class BacktestEngine:
|
||||
if success:
|
||||
self.performance_analyzer.add_trade(self.portfolio.trades[-1])
|
||||
logger.info(f"✅ 买入: {signal.stock_code} {shares}股 @{current_price:.3f}")
|
||||
|
||||
# 通知策略更新买入价格
|
||||
if hasattr(self.strategy, 'update_buy_price'):
|
||||
self.strategy.update_buy_price(signal.stock_code, current_price)
|
||||
|
||||
elif signal.action == 'BUY_ALL':
|
||||
# 全仓买入操作
|
||||
@ -252,6 +256,10 @@ class BacktestEngine:
|
||||
if success:
|
||||
self.performance_analyzer.add_trade(self.portfolio.trades[-1])
|
||||
logger.info(f"🚀 全仓买入: {signal.stock_code} {shares}股 @{current_price:.3f}")
|
||||
|
||||
# 通知策略更新买入价格
|
||||
if hasattr(self.strategy, 'update_buy_price'):
|
||||
self.strategy.update_buy_price(signal.stock_code, current_price)
|
||||
|
||||
elif signal.action == 'SELL':
|
||||
# 使用信号中指定的股数,如果没有则部分卖出
|
||||
@ -299,12 +307,26 @@ class BacktestEngine:
|
||||
try:
|
||||
# 获取当前所有持仓的价格
|
||||
current_prices = {}
|
||||
benchmark_price = None
|
||||
|
||||
for stock_code in self.portfolio.positions.keys():
|
||||
if stock_code in self.data_cache:
|
||||
df = self.data_cache[stock_code]
|
||||
price_data = df[df.index == timestamp]
|
||||
if not price_data.empty:
|
||||
current_prices[stock_code] = price_data['close'].iloc[0]
|
||||
# 使用第一只股票作为基准
|
||||
if benchmark_price is None:
|
||||
benchmark_price = price_data['close'].iloc[0]
|
||||
|
||||
# 如果没有持仓,使用第一只股票作为基准
|
||||
if benchmark_price is None and self.stock_codes:
|
||||
stock_code = self.stock_codes[0]
|
||||
if stock_code in self.data_cache:
|
||||
df = self.data_cache[stock_code]
|
||||
price_data = df[df.index == timestamp]
|
||||
if not price_data.empty:
|
||||
benchmark_price = price_data['close'].iloc[0]
|
||||
|
||||
# 更新投资组合市值
|
||||
self.portfolio.update_market_values(current_prices)
|
||||
@ -312,6 +334,10 @@ class BacktestEngine:
|
||||
# 记录到性能分析器
|
||||
self.performance_analyzer.add_portfolio_value(timestamp, self.portfolio.total_value)
|
||||
|
||||
# 记录基准价格
|
||||
if benchmark_price is not None:
|
||||
self.performance_analyzer.add_benchmark_value(timestamp, benchmark_price)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"更新投资组合价值失败: {e}")
|
||||
|
||||
@ -361,6 +387,17 @@ class BacktestEngine:
|
||||
# 记录初始投资组合价值
|
||||
self.performance_analyzer.add_portfolio_value(trading_dates[0], self.portfolio.total_value)
|
||||
|
||||
# 记录初始基准价格
|
||||
initial_benchmark_price = None
|
||||
if self.stock_codes:
|
||||
stock_code = self.stock_codes[0]
|
||||
if stock_code in self.data_cache:
|
||||
df = self.data_cache[stock_code]
|
||||
price_data = df[df.index == trading_dates[0]]
|
||||
if not price_data.empty:
|
||||
initial_benchmark_price = price_data['close'].iloc[0]
|
||||
self.performance_analyzer.add_benchmark_value(trading_dates[0], initial_benchmark_price)
|
||||
|
||||
# 逐日回测
|
||||
for i, current_date in enumerate(trading_dates):
|
||||
try:
|
||||
|
||||
@ -1,40 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
检查2024年数据覆盖情况
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
sys.path.append('..')
|
||||
|
||||
import data_process_model.database_config as db_config
|
||||
|
||||
def check_2024_data():
|
||||
"""检查2024年数据"""
|
||||
try:
|
||||
db_config.init_database()
|
||||
mysql_db = db_config.mysql_db
|
||||
|
||||
# 检查分钟数据时间范围
|
||||
cursor = mysql_db.execute_sql('SELECT MIN(timestamp), MAX(timestamp) FROM kline_601398_sh_1m')
|
||||
min_date, max_date = cursor.fetchone()
|
||||
print(f'kline_601398_sh_1m时间范围: {min_date} 到 {max_date}')
|
||||
|
||||
# 检查2024年数据量
|
||||
cursor = mysql_db.execute_sql("SELECT COUNT(*) FROM kline_601398_sh_1m WHERE timestamp >= '2024-01-01' AND timestamp <= '2024-12-31'")
|
||||
count_2024 = cursor.fetchone()[0]
|
||||
print(f'2024年数据量: {count_2024}条')
|
||||
|
||||
# 检查多时间周期表的2024年数据
|
||||
timeframes = ['15m', '30m', '60m']
|
||||
for tf in timeframes:
|
||||
table_name = f'kline_601398_sh_{tf}'
|
||||
cursor = mysql_db.execute_sql(f"SELECT COUNT(*) FROM {table_name} WHERE timestamp >= '2024-01-01' AND timestamp <= '2024-12-31'")
|
||||
count = cursor.fetchone()[0]
|
||||
print(f'{table_name} 2024年数据量: {count}条')
|
||||
|
||||
except Exception as e:
|
||||
print(f"检查失败: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_2024_data()
|
||||
@ -1,50 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
检查数据库中的601398相关表
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
sys.path.append('..')
|
||||
|
||||
import data_process_model.database_config as db_config
|
||||
|
||||
def check_tables():
|
||||
"""检查数据库中的表"""
|
||||
try:
|
||||
db_config.init_database()
|
||||
mysql_db = db_config.mysql_db
|
||||
|
||||
# 查询所有表
|
||||
cursor = mysql_db.execute_sql('SHOW TABLES')
|
||||
all_tables = cursor.fetchall()
|
||||
|
||||
print("数据库中的所有表:")
|
||||
for table in all_tables:
|
||||
print(f" - {table[0]}")
|
||||
|
||||
# 筛选601398相关的表
|
||||
print("\n601398相关的表:")
|
||||
for table in all_tables:
|
||||
if '601398' in table[0]:
|
||||
print(f" ✅ {table[0]}")
|
||||
|
||||
# 检查表中的数据量
|
||||
try:
|
||||
cursor = mysql_db.execute_sql(f'SELECT COUNT(*) FROM `{table[0]}`')
|
||||
count = cursor.fetchone()[0]
|
||||
print(f" 数据行数: {count}")
|
||||
|
||||
# 检查时间范围
|
||||
cursor = mysql_db.execute_sql(f'SELECT MIN(datetime), MAX(datetime) FROM `{table[0]}`')
|
||||
min_date, max_date = cursor.fetchone()
|
||||
print(f" 时间范围: {min_date} 到 {max_date}")
|
||||
|
||||
except Exception as e:
|
||||
print(f" 检查数据失败: {e}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"检查表失败: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
check_tables()
|
||||
@ -1,130 +0,0 @@
|
||||
"""
|
||||
数据库连接测试脚本
|
||||
"""
|
||||
|
||||
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)
|
||||
|
||||
def test_database_connection():
|
||||
"""测试数据库连接"""
|
||||
try:
|
||||
print("🔍 测试数据库连接...")
|
||||
|
||||
# 导入数据库模块
|
||||
sys.path.insert(0, os.path.join(src_dir, 'data_process_model'))
|
||||
|
||||
from database_config import init_database, close_database, test_connection
|
||||
from stock_models import create_stock_kline_model
|
||||
|
||||
print("✅ 数据库模块导入成功")
|
||||
|
||||
# 测试连接
|
||||
if not test_connection():
|
||||
print("❌ 数据库连接测试失败")
|
||||
return False
|
||||
|
||||
print("✅ 数据库连接测试成功")
|
||||
|
||||
# 检查工商银行数据
|
||||
print("\n🏦 检查工商银行(601398.SH)分钟数据...")
|
||||
|
||||
try:
|
||||
# 使用新的1m周期模型创建函数
|
||||
model_class = create_stock_kline_model("601398.SH", "1m")
|
||||
count = model_class.select().count()
|
||||
print(f"✅ 找到 601398.SH 1分钟数据: {count} 条记录")
|
||||
print(f" 表名: {model_class._meta.table_name}")
|
||||
|
||||
if count > 0:
|
||||
# 查看数据范围
|
||||
first = model_class.select().order_by(model_class.timestamp).first()
|
||||
last = model_class.select().order_by(model_class.timestamp.desc()).first()
|
||||
|
||||
if first and last:
|
||||
print(f"📅 数据时间范围: {first.timestamp} ~ {last.timestamp}")
|
||||
|
||||
# 检查2025年数据(根据实际数据时间范围)
|
||||
from datetime import datetime
|
||||
start_2025 = datetime(2025, 1, 1)
|
||||
end_2025 = datetime(2025, 7, 31)
|
||||
|
||||
count_2025 = model_class.select().where(
|
||||
(model_class.timestamp >= start_2025) &
|
||||
(model_class.timestamp <= end_2025)
|
||||
).count()
|
||||
|
||||
print(f"📊 2025年1-7月数据: {count_2025} 条记录")
|
||||
|
||||
# 分钟数据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("⚠️ 2025年分钟数据不足,建议检查数据")
|
||||
return False
|
||||
else:
|
||||
print("❌ 未找到数据,请先运行数据下载脚本")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 检查数据时出错: {e}")
|
||||
return False
|
||||
finally:
|
||||
close_database()
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 数据库测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
def download_data_if_needed():
|
||||
"""如果需要,下载数据"""
|
||||
print("\n💡 如果数据不足,可以运行以下步骤下载数据:")
|
||||
print("1. 编辑 data_process_model/main.py")
|
||||
print("2. 确保 g_stock_code_list 包含 '601398.SH'")
|
||||
print("3. 设置 g_start_date = '20240101'")
|
||||
print("4. 设置 g_end_date = '20241231'")
|
||||
print("5. 运行: python data_process_model/main.py")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print("🔧 数据库连接和数据检查")
|
||||
print("="*50)
|
||||
|
||||
success = test_database_connection()
|
||||
|
||||
if success:
|
||||
print("\n🎉 数据检查通过!可以运行回测")
|
||||
|
||||
# 运行回测
|
||||
try:
|
||||
print("\n🚀 启动回测...")
|
||||
from real_backtest_demo import run_real_backtest
|
||||
run_real_backtest()
|
||||
except Exception as e:
|
||||
print(f"❌ 回测启动失败: {e}")
|
||||
else:
|
||||
print("\n❌ 数据检查失败")
|
||||
download_data_if_needed()
|
||||
@ -1,191 +0,0 @@
|
||||
"""
|
||||
回测示例脚本
|
||||
|
||||
演示如何使用回测引擎进行均线策略回测
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
# 添加项目路径
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
from back_trader.backtest_engine import BacktestEngine
|
||||
from back_trader.ma_cross_strategy import MACrossStrategy
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',
|
||||
handlers=[
|
||||
logging.StreamHandler(),
|
||||
logging.FileHandler('backtest.log', encoding='utf-8')
|
||||
]
|
||||
)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def progress_callback(current, total, message):
|
||||
"""进度回调函数"""
|
||||
progress = (current / total) * 100
|
||||
print(f"\r进度: {progress:.1f}% - {message}", end="", flush=True)
|
||||
if current == total:
|
||||
print() # 换行
|
||||
|
||||
|
||||
def run_ma_cross_backtest():
|
||||
"""运行均线交叉策略回测"""
|
||||
try:
|
||||
print("🚀 开始均线交叉策略回测")
|
||||
print("="*50)
|
||||
|
||||
# 创建回测引擎
|
||||
engine = BacktestEngine(initial_capital=1000000.0)
|
||||
|
||||
# 设置股票池
|
||||
stock_codes = ["601658.SH", "510310.SH", "601398.SH"]
|
||||
engine.set_universe(stock_codes)
|
||||
|
||||
# 设置回测时间范围
|
||||
engine.set_period("2024-01-01", "2024-12-31", "1d")
|
||||
|
||||
# 创建均线交叉策略
|
||||
strategy_params = {
|
||||
'short_period': 5, # 5日均线
|
||||
'long_period': 20, # 20日均线
|
||||
'stop_loss': 0.05, # 5%止损
|
||||
'take_profit': 0.15, # 15%止盈
|
||||
'position_size': 0.3 # 每次30%仓位
|
||||
}
|
||||
strategy = MACrossStrategy(strategy_params)
|
||||
engine.set_strategy(strategy)
|
||||
|
||||
# 加载数据
|
||||
print("\n📥 正在加载历史数据...")
|
||||
if not engine.load_data_from_database():
|
||||
print("❌ 数据加载失败,请检查数据库连接和数据")
|
||||
return False
|
||||
|
||||
# 运行回测
|
||||
print("\n🔄 开始执行回测...")
|
||||
success = engine.run_backtest(progress_callback)
|
||||
|
||||
if success:
|
||||
print("\n✅ 回测完成")
|
||||
|
||||
# 显示结果
|
||||
print("\n📊 回测结果:")
|
||||
engine.print_summary()
|
||||
|
||||
# 保存结果
|
||||
result_file = f"backtest_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
if engine.save_results(result_file):
|
||||
print(f"\n💾 结果已保存到: {result_file}")
|
||||
|
||||
return True
|
||||
else:
|
||||
print("\n❌ 回测失败")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"回测过程出错: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
def run_parameter_optimization():
|
||||
"""参数优化示例"""
|
||||
print("🔧 参数优化示例")
|
||||
print("="*50)
|
||||
|
||||
# 定义参数范围
|
||||
short_periods = [3, 5, 10]
|
||||
long_periods = [15, 20, 30]
|
||||
|
||||
best_return = float('-inf')
|
||||
best_params = None
|
||||
|
||||
total_combinations = len(short_periods) * len(long_periods)
|
||||
current_combination = 0
|
||||
|
||||
for short_period in short_periods:
|
||||
for long_period in long_periods:
|
||||
if short_period >= long_period:
|
||||
continue
|
||||
|
||||
current_combination += 1
|
||||
print(f"\n📊 测试参数组合 {current_combination}/{total_combinations}")
|
||||
print(f"短期均线: {short_period}, 长期均线: {long_period}")
|
||||
|
||||
try:
|
||||
# 创建回测引擎
|
||||
engine = BacktestEngine(initial_capital=1000000.0)
|
||||
engine.set_universe(["601658.SH"])
|
||||
engine.set_period("2024-01-01", "2024-12-31", "1d")
|
||||
|
||||
# 创建策略
|
||||
strategy_params = {
|
||||
'short_period': short_period,
|
||||
'long_period': long_period,
|
||||
'stop_loss': 0.05,
|
||||
'take_profit': 0.15,
|
||||
'position_size': 0.3
|
||||
}
|
||||
strategy = MACrossStrategy(strategy_params)
|
||||
engine.set_strategy(strategy)
|
||||
|
||||
# 加载数据并运行回测
|
||||
if engine.load_data_from_database():
|
||||
if engine.run_backtest():
|
||||
report = engine.get_results()
|
||||
if report:
|
||||
total_return = report.total_return
|
||||
print(f"总收益率: {total_return*100:.2f}%")
|
||||
|
||||
if total_return > best_return:
|
||||
best_return = total_return
|
||||
best_params = strategy_params.copy()
|
||||
print("🎯 发现更优参数!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 参数测试失败: {e}")
|
||||
continue
|
||||
|
||||
print("\n🏆 参数优化结果:")
|
||||
if best_params:
|
||||
print(f"最佳参数: {best_params}")
|
||||
print(f"最佳收益率: {best_return*100:.2f}%")
|
||||
else:
|
||||
print("未找到有效的参数组合")
|
||||
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("QTrade 回测引擎演示")
|
||||
print("="*50)
|
||||
|
||||
while True:
|
||||
print("\n请选择操作:")
|
||||
print("1. 运行均线交叉策略回测")
|
||||
print("2. 运行参数优化")
|
||||
print("3. 退出")
|
||||
|
||||
choice = input("\n请输入选择 (1-3): ").strip()
|
||||
|
||||
if choice == '1':
|
||||
run_ma_cross_backtest()
|
||||
elif choice == '2':
|
||||
run_parameter_optimization()
|
||||
elif choice == '3':
|
||||
print("👋 再见!")
|
||||
break
|
||||
else:
|
||||
print("❌ 无效选择,请重新输入")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,74 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Final Encoding Test - 最终编码测试
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Fix encoding
|
||||
os.environ['PYTHONIOENCODING'] = 'utf-8'
|
||||
|
||||
print("=== Encoding Test Results ===")
|
||||
print(f"Python Version: {sys.version}")
|
||||
print(f"Default Encoding: {sys.getdefaultencoding()}")
|
||||
print(f"Filesystem Encoding: {sys.getfilesystemencoding()}")
|
||||
print(f"Console Encoding: {getattr(sys.stdout, 'encoding', 'unknown')}")
|
||||
|
||||
print("\n=== Module Import Test ===")
|
||||
|
||||
# Add current directory to path
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, current_dir)
|
||||
|
||||
# Test imports
|
||||
modules_to_test = [
|
||||
'strategy_base',
|
||||
'ma_cross_strategy',
|
||||
'backtest_engine',
|
||||
'multi_timeframe_ma_score_strategy',
|
||||
'test_multi_timeframe_simple',
|
||||
'run_multi_timeframe_score_backtest'
|
||||
]
|
||||
|
||||
success_count = 0
|
||||
for module_name in modules_to_test:
|
||||
try:
|
||||
__import__(module_name)
|
||||
print(f"✓ {module_name}")
|
||||
success_count += 1
|
||||
except Exception as e:
|
||||
print(f"✗ {module_name}: {e}")
|
||||
|
||||
print(f"\nImport Success Rate: {success_count}/{len(modules_to_test)} ({success_count/len(modules_to_test)*100:.1f}%)")
|
||||
|
||||
print("\n=== Strategy Test ===")
|
||||
|
||||
try:
|
||||
from multi_timeframe_ma_score_strategy import MultiTimeframeMAScoreStrategy
|
||||
|
||||
# Create strategy
|
||||
strategy = MultiTimeframeMAScoreStrategy()
|
||||
print(f"Strategy: {strategy.name}")
|
||||
print(f"Description: Multi-timeframe MA crossover scoring strategy")
|
||||
print(f"Timeframes: {strategy.timeframes}")
|
||||
print(f"MA Periods: Short={strategy.short_ma}, Long={strategy.long_ma}")
|
||||
|
||||
# Test initialization
|
||||
if strategy.initialize():
|
||||
print("✓ Strategy initialization: SUCCESS")
|
||||
else:
|
||||
print("✗ Strategy initialization: FAILED")
|
||||
|
||||
# Get strategy info
|
||||
info = strategy.get_strategy_info()
|
||||
print(f"Strategy Info: {len(info)} parameters configured")
|
||||
|
||||
except Exception as e:
|
||||
print(f"✗ Strategy test failed: {e}")
|
||||
|
||||
print("\n=== Test Completed ===")
|
||||
print("Note: All Chinese text has been replaced with English to avoid encoding issues")
|
||||
print("策略功能正常运行,编码问题已解决 (Strategy functions normally, encoding issues resolved)")
|
||||
@ -1,295 +0,0 @@
|
||||
"""
|
||||
均线金叉/死叉策略
|
||||
|
||||
实现基于双均线的交易策略:
|
||||
- 金叉(短期均线上穿长期均线)时买入
|
||||
- 死叉(短期均线下穿长期均线)时卖出
|
||||
"""
|
||||
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from datetime import datetime
|
||||
from typing import Dict, Any, Optional
|
||||
from strategy_base import StrategyBase, Signal
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class MACrossStrategy(StrategyBase):
|
||||
"""
|
||||
双均线交叉策略
|
||||
|
||||
策略逻辑:
|
||||
1. 计算短期和长期移动平均线
|
||||
2. 当短期均线上穿长期均线时(金叉),产生买入信号
|
||||
3. 当短期均线下穿长期均线时(死叉),产生卖出信号
|
||||
4. 支持止损和止盈设置
|
||||
"""
|
||||
|
||||
def __init__(self, params: Optional[Dict[str, Any]] = None):
|
||||
default_params = {
|
||||
'short_period': 5, # 短期均线周期
|
||||
'long_period': 20, # 长期均线周期
|
||||
'stop_loss': 0.05, # 止损比例(5%)
|
||||
'take_profit': 0.15, # 止盈比例(15%)
|
||||
'min_volume': 0, # 最小成交量过滤
|
||||
'position_size': 0.2 # 每次交易的仓位比例(20%)
|
||||
}
|
||||
|
||||
if params:
|
||||
default_params.update(params)
|
||||
|
||||
super().__init__("MA Cross Strategy", default_params)
|
||||
|
||||
# 策略状态变量
|
||||
self.ma_short_history = []
|
||||
self.ma_long_history = []
|
||||
self.last_signal = None
|
||||
self.entry_price = None
|
||||
|
||||
def initialize(self):
|
||||
"""策略初始化"""
|
||||
self.log_info(f"初始化均线交叉策略")
|
||||
self.log_info(f"短期均线: {self.get_parameter('short_period')}周期")
|
||||
self.log_info(f"长期均线: {self.get_parameter('long_period')}周期")
|
||||
self.log_info(f"止损: {self.get_parameter('stop_loss')*100:.1f}%")
|
||||
self.log_info(f"止盈: {self.get_parameter('take_profit')*100:.1f}%")
|
||||
|
||||
# 重置状态
|
||||
self.ma_short_history = []
|
||||
self.ma_long_history = []
|
||||
self.last_signal = None
|
||||
self.entry_price = None
|
||||
|
||||
def calculate_moving_averages(self, prices: pd.Series) -> tuple:
|
||||
"""
|
||||
计算移动平均线
|
||||
|
||||
Args:
|
||||
prices: 价格序列(通常是收盘价)
|
||||
|
||||
Returns:
|
||||
tuple: (短期均线值, 长期均线值)
|
||||
"""
|
||||
short_period = self.get_parameter('short_period')
|
||||
long_period = self.get_parameter('long_period')
|
||||
|
||||
if len(prices) < long_period:
|
||||
return None, None
|
||||
|
||||
ma_short = prices.rolling(window=short_period).mean().iloc[-1]
|
||||
ma_long = prices.rolling(window=long_period).mean().iloc[-1]
|
||||
|
||||
return ma_short, ma_long
|
||||
|
||||
def detect_cross_signal(self, ma_short_current: float, ma_long_current: float,
|
||||
ma_short_prev: float, ma_long_prev: float) -> Optional[str]:
|
||||
"""
|
||||
检测均线交叉信号
|
||||
|
||||
Args:
|
||||
ma_short_current: 当前短期均线值
|
||||
ma_long_current: 当前长期均线值
|
||||
ma_short_prev: 前一期短期均线值
|
||||
ma_long_prev: 前一期长期均线值
|
||||
|
||||
Returns:
|
||||
str: 'golden_cross'(金叉), 'death_cross'(死叉), None(无信号)
|
||||
"""
|
||||
# 检查金叉:短期均线从下方突破长期均线
|
||||
if (ma_short_prev <= ma_long_prev and
|
||||
ma_short_current > ma_long_current):
|
||||
return 'golden_cross'
|
||||
|
||||
# 检查死叉:短期均线从上方跌破长期均线
|
||||
if (ma_short_prev >= ma_long_prev and
|
||||
ma_short_current < ma_long_current):
|
||||
return 'death_cross'
|
||||
|
||||
return None
|
||||
|
||||
def check_stop_conditions(self, current_price: float, stock_code: str) -> Optional[str]:
|
||||
"""
|
||||
检查止损止盈条件
|
||||
|
||||
Args:
|
||||
current_price: 当前价格
|
||||
stock_code: 股票代码
|
||||
|
||||
Returns:
|
||||
str: 'stop_loss', 'take_profit', None
|
||||
"""
|
||||
if self.entry_price is None:
|
||||
return None
|
||||
|
||||
position = self.portfolio.get_position(stock_code)
|
||||
if not position or position.shares <= 0:
|
||||
return None
|
||||
|
||||
# 计算盈亏比例
|
||||
price_change = (current_price - self.entry_price) / self.entry_price
|
||||
|
||||
# 检查止损
|
||||
stop_loss = self.get_parameter('stop_loss')
|
||||
if price_change <= -stop_loss:
|
||||
return 'stop_loss'
|
||||
|
||||
# 检查止盈
|
||||
take_profit = self.get_parameter('take_profit')
|
||||
if price_change >= take_profit:
|
||||
return 'take_profit'
|
||||
|
||||
return None
|
||||
|
||||
def calculate_position_size(self, price: float) -> int:
|
||||
"""
|
||||
计算交易股数
|
||||
|
||||
Args:
|
||||
price: 股票价格
|
||||
|
||||
Returns:
|
||||
int: 应购买的股数
|
||||
"""
|
||||
position_ratio = self.get_parameter('position_size')
|
||||
available_cash = self.portfolio.cash
|
||||
target_value = available_cash * position_ratio
|
||||
|
||||
# 计算股数(向下取整到100的倍数,A股一手=100股)
|
||||
shares = int(target_value / price / 100) * 100
|
||||
|
||||
return max(shares, 0)
|
||||
|
||||
def on_data(self, data: pd.DataFrame, timestamp: datetime):
|
||||
"""
|
||||
处理新的K线数据
|
||||
|
||||
Args:
|
||||
data: K线数据DataFrame,包含时间序列的OHLCV数据
|
||||
timestamp: 当前时间戳
|
||||
"""
|
||||
try:
|
||||
if data.empty or len(data) < self.get_parameter('long_period'):
|
||||
return
|
||||
|
||||
# 获取股票代码(假设数据中只有一只股票)
|
||||
stock_code = getattr(data, 'stock_code', 'UNKNOWN')
|
||||
|
||||
# 使用收盘价计算均线
|
||||
close_prices = data['close_price'] if 'close_price' in data.columns else data['close']
|
||||
current_price = close_prices.iloc[-1]
|
||||
|
||||
# 检查成交量过滤
|
||||
min_volume = self.get_parameter('min_volume')
|
||||
if min_volume > 0:
|
||||
volume = data['volume'].iloc[-1] if 'volume' in data.columns else 0
|
||||
if volume < min_volume:
|
||||
return
|
||||
|
||||
# 计算当前均线值
|
||||
ma_short, ma_long = self.calculate_moving_averages(close_prices)
|
||||
|
||||
if ma_short is None or ma_long is None:
|
||||
return
|
||||
|
||||
# 检查是否有足够的历史数据来判断交叉
|
||||
if len(self.ma_short_history) > 0 and len(self.ma_long_history) > 0:
|
||||
ma_short_prev = self.ma_short_history[-1]
|
||||
ma_long_prev = self.ma_long_history[-1]
|
||||
|
||||
# 检测交叉信号
|
||||
cross_signal = self.detect_cross_signal(
|
||||
ma_short, ma_long, ma_short_prev, ma_long_prev
|
||||
)
|
||||
|
||||
# 检查止损止盈
|
||||
stop_condition = self.check_stop_conditions(current_price, stock_code)
|
||||
|
||||
# 处理信号
|
||||
if cross_signal == 'golden_cross':
|
||||
self._handle_buy_signal(timestamp, stock_code, current_price, "金叉买入")
|
||||
|
||||
elif cross_signal == 'death_cross':
|
||||
self._handle_sell_signal(timestamp, stock_code, current_price, "死叉卖出")
|
||||
|
||||
elif stop_condition == 'stop_loss':
|
||||
self._handle_sell_signal(timestamp, stock_code, current_price, "止损卖出")
|
||||
|
||||
elif stop_condition == 'take_profit':
|
||||
self._handle_sell_signal(timestamp, stock_code, current_price, "止盈卖出")
|
||||
|
||||
# 更新均线历史
|
||||
self.ma_short_history.append(ma_short)
|
||||
self.ma_long_history.append(ma_long)
|
||||
|
||||
# 保持历史长度不超过必要范围
|
||||
max_history = self.get_parameter('long_period') + 10
|
||||
if len(self.ma_short_history) > max_history:
|
||||
self.ma_short_history = self.ma_short_history[-max_history:]
|
||||
if len(self.ma_long_history) > max_history:
|
||||
self.ma_long_history = self.ma_long_history[-max_history:]
|
||||
|
||||
except Exception as e:
|
||||
self.log_error(f"数据处理失败: {e}")
|
||||
|
||||
def _handle_buy_signal(self, timestamp: datetime, stock_code: str,
|
||||
price: float, reason: str):
|
||||
"""处理买入信号"""
|
||||
try:
|
||||
# 检查是否已经持仓
|
||||
position = self.portfolio.get_position(stock_code)
|
||||
if position and position.shares > 0:
|
||||
self.log_info(f"已持仓,跳过买入信号: {stock_code}")
|
||||
return
|
||||
|
||||
# 计算买入股数
|
||||
shares = self.calculate_position_size(price)
|
||||
if shares <= 0:
|
||||
self.log_warning(f"资金不足,无法买入: {stock_code}")
|
||||
return
|
||||
|
||||
# 生成买入信号
|
||||
signal = self.generate_signal(timestamp, stock_code, 'BUY', 1.0, reason)
|
||||
|
||||
# 执行买入(这里只生成信号,实际执行由回测引擎处理)
|
||||
self.last_signal = 'BUY'
|
||||
self.entry_price = price
|
||||
|
||||
self.log_info(f"生成买入信号: {stock_code} @ {price:.2f}, 数量: {shares}")
|
||||
|
||||
except Exception as e:
|
||||
self.log_error(f"处理买入信号失败: {e}")
|
||||
|
||||
def _handle_sell_signal(self, timestamp: datetime, stock_code: str,
|
||||
price: float, reason: str):
|
||||
"""处理卖出信号"""
|
||||
try:
|
||||
# 检查是否有持仓
|
||||
position = self.portfolio.get_position(stock_code)
|
||||
if not position or position.shares <= 0:
|
||||
return
|
||||
|
||||
# 生成卖出信号
|
||||
signal = self.generate_signal(timestamp, stock_code, 'SELL', 1.0, reason)
|
||||
|
||||
# 重置状态
|
||||
self.last_signal = 'SELL'
|
||||
self.entry_price = None
|
||||
|
||||
self.log_info(f"生成卖出信号: {stock_code} @ {price:.2f}, 原因: {reason}")
|
||||
|
||||
except Exception as e:
|
||||
self.log_error(f"处理卖出信号失败: {e}")
|
||||
|
||||
def get_current_indicators(self) -> Dict[str, Any]:
|
||||
"""获取当前指标值"""
|
||||
if len(self.ma_short_history) == 0 or len(self.ma_long_history) == 0:
|
||||
return {}
|
||||
|
||||
return {
|
||||
'ma_short': self.ma_short_history[-1],
|
||||
'ma_long': self.ma_long_history[-1],
|
||||
'last_signal': self.last_signal,
|
||||
'entry_price': self.entry_price
|
||||
}
|
||||
@ -1,12 +1,12 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
多时间周期MA策略 - 回测专用版本(最新优化版)
|
||||
- 使用1分钟数据进行回测
|
||||
- 同时监听15分钟/30分钟/60分钟MA5/MA18交叉信号
|
||||
- 评分系统:每个金叉+1分,每个死叉-1分(分数最低为0)
|
||||
- 交易系统:分数从0变成1时全仓买入,仅当分数从1变成0时清仓并置0分
|
||||
- 持仓跟踪:跟踪持仓状态和分数变化
|
||||
- 无阈值判断:只要发生MA交叉就产生信号
|
||||
- 使用1分钟数据进行回测,买点每5分钟检查一次,卖点每15分钟检查一次
|
||||
- 评分系统:15/30/60分钟周期MA5/MA18交叉,金叉+1分,死叉-1分,起始分数为0
|
||||
- 买入条件:15分钟持续金叉且实时股价 > 日K5日线且分数>0且价格与当天分时均价差距<1%
|
||||
- 卖出条件:分数≤0时清仓卖出
|
||||
- T+1限制:当天买入的股票不能卖出
|
||||
- 止盈机制:可选择达到止盈点时清仓并置0分
|
||||
"""
|
||||
|
||||
import os
|
||||
@ -36,19 +36,22 @@ class MultiTimeframeMABacktestStrategy(StrategyBase):
|
||||
多时间周期MA策略 - 回测版本(最新优化版)
|
||||
|
||||
特点:
|
||||
- 回测数据:1分钟K线数据
|
||||
- 监听策略:同时监听15分钟/30分钟/60分钟MA5/MA18交叉
|
||||
- 评分系统:每个金叉+1分,每个死叉-1分(分数最低为0)
|
||||
- 交易规则:分数从0变成1时全仓买入,仅当分数从1变成0时清仓并置0分
|
||||
- 无阈值判断:只要发生MA交叉就产生信号
|
||||
- 回测数据:1分钟K线数据,买点每5分钟检查一次,卖点每15分钟检查一次
|
||||
- 评分系统:15/30/60分钟周期MA5/MA18交叉,金叉+1分,死叉-1分,起始分数0
|
||||
- 买入条件:15分钟金叉且实时股价 > 买入系数*日K5日线且分数>0且价格与分时均价差距<1%
|
||||
- 卖出条件:分数≤0时清仓卖出
|
||||
- T+1限制:当天买入的股票不能卖出
|
||||
- 止盈机制:可选择达到止盈点时清仓并置0分
|
||||
"""
|
||||
|
||||
def __init__(self, stock_code: str = "601398.SH"):
|
||||
def __init__(self, stock_code: str = "601398.SH", profit_target: Optional[float] = None, buy_low_ratio: float = 0.99):
|
||||
"""
|
||||
初始化策略
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
profit_target: 止盈阈值(小数形式,如0.03表示3%),None表示不设置止盈
|
||||
buy_low_ratio: 买入条件系数,股价大于该系数*日K5日线时可买入,默认0.97
|
||||
"""
|
||||
super().__init__(name="MultiTimeframeMABacktest")
|
||||
|
||||
@ -61,11 +64,22 @@ class MultiTimeframeMABacktestStrategy(StrategyBase):
|
||||
# 信号计算时间周期(用于计算交叉信号)
|
||||
self.signal_timeframes = ['15m', '30m', '60m']
|
||||
|
||||
# 日线数据用于买点条件判断
|
||||
self.daily_timeframe = '1d'
|
||||
|
||||
# 股票评分系统
|
||||
self.stock_scores = {stock_code: 0}
|
||||
|
||||
# 持仓状态跟踪
|
||||
self.holding_stocks = {stock_code: False} # 跟踪是否持有股票
|
||||
self.buy_dates = {stock_code: None} # 记录买入日期(用于T+1限制)
|
||||
self.buy_prices = {stock_code: 0.0} # 记录买入价格(用于止盈计算)
|
||||
|
||||
# 止盈参数
|
||||
self.profit_target = profit_target # 止盈阈值,None表示不设置止盈
|
||||
|
||||
# 买入条件参数
|
||||
self.buy_low_ratio = buy_low_ratio # 买入条件系数,股价 > buy_low_ratio * 日K5日线
|
||||
|
||||
# 交易参数 - 全仓交易模式
|
||||
# 不再使用固定金额,改为全仓买卖
|
||||
@ -100,7 +114,15 @@ class MultiTimeframeMABacktestStrategy(StrategyBase):
|
||||
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分")
|
||||
logger.info(f"[{self.name}] 买入判断: 每5分钟检查一次")
|
||||
logger.info(f"[{self.name}] 卖出判断: 每15分钟检查一次")
|
||||
logger.info(f"[{self.name}] 买入条件: 15分钟持续金叉且股价>日K5日线且分数>0且价格与分时均价差距<1%")
|
||||
logger.info(f"[{self.name}] 卖出条件: 分数≤0时清仓")
|
||||
logger.info(f"[{self.name}] T+1限制: 当天买入不能卖出")
|
||||
if self.profit_target is not None:
|
||||
logger.info(f"[{self.name}] 止盈设置: {self.profit_target*100:.1f}%")
|
||||
else:
|
||||
logger.info(f"[{self.name}] 止盈设置: 无止盈")
|
||||
|
||||
# 创建各时间周期的数据库模型
|
||||
self._create_timeframe_models()
|
||||
@ -120,9 +142,15 @@ class MultiTimeframeMABacktestStrategy(StrategyBase):
|
||||
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}")
|
||||
|
||||
# 创建日线模型用于5日均线计算
|
||||
self.model_cache[self.daily_timeframe] = create_stock_kline_model(self.stock_code, self.daily_timeframe)
|
||||
logger.info(f"[{self.name}] 创建 {self.daily_timeframe} 模型: {self.model_cache[self.daily_timeframe]._meta.table_name}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] 创建时间周期模型失败: {e}")
|
||||
|
||||
@ -275,6 +303,9 @@ class MultiTimeframeMABacktestStrategy(StrategyBase):
|
||||
"""
|
||||
处理新的1分钟数据
|
||||
|
||||
买点策略:每5分钟判断一次,查看当前15分钟持续金叉状态,且价格大于日K5日线,且价格与分时均价差距<1%
|
||||
卖点策略:每15分钟判断一次,查看当前股票分数,若≤0则清仓卖出
|
||||
|
||||
Args:
|
||||
data: 1分钟K线数据(用于回测)
|
||||
timestamp: 当前时间戳
|
||||
@ -285,123 +316,472 @@ class MultiTimeframeMABacktestStrategy(StrategyBase):
|
||||
if stock_code not in self.stock_scores:
|
||||
self.stock_scores[stock_code] = 0
|
||||
self.holding_stocks[stock_code] = False
|
||||
self.buy_dates[stock_code] = None
|
||||
self.buy_prices[stock_code] = 0.0
|
||||
|
||||
# 只在15分钟的倍数时间点检查买卖点
|
||||
# 因为15分钟周期的K线至少15分钟才会变化一次
|
||||
if timestamp.minute % 15 != 0:
|
||||
return # 不是15分钟倍数时间点,跳过检查
|
||||
# 获取当前价格
|
||||
if data.empty:
|
||||
return
|
||||
current_price = data['close'].iloc[-1]
|
||||
|
||||
# 记录交易前的分数
|
||||
old_score = self.stock_scores[stock_code]
|
||||
score_changes = [] # 记录分数变化
|
||||
# 每分钟都检查止盈条件(优先级最高)
|
||||
if self._check_profit_target(stock_code, current_price, timestamp):
|
||||
return # 已经执行止盈,直接返回
|
||||
|
||||
# 同时检查所有时间周期的交叉信号
|
||||
timeframes_to_check = self.signal_timeframes # 始终检查所有时间周期
|
||||
# 买点判断:每5分钟判断一次(0, 5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55)
|
||||
if timestamp.minute % 5 == 0:
|
||||
self._check_buy_signals(stock_code, current_price, timestamp)
|
||||
|
||||
# 为所有时间周期检查交叉信号
|
||||
for timeframe in timeframes_to_check:
|
||||
# 卖点判断:每15分钟判断一次(0, 15, 30, 45)
|
||||
if timestamp.minute % 15 == 0:
|
||||
# 先更新分数(检查所有时间周期的交叉信号)
|
||||
old_score = self.stock_scores[stock_code]
|
||||
new_score = self._update_score(stock_code, timestamp)
|
||||
self.stock_scores[stock_code] = new_score
|
||||
|
||||
# 获取时间周期数据(增加更多历史数据用于交叉判断)
|
||||
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分
|
||||
# 检查卖出条件
|
||||
self._check_sell_signals(stock_code, new_score, current_price, timestamp)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] 处理数据时出错: {e}")
|
||||
|
||||
def _check_profit_target(self, stock_code: str, current_price: float, timestamp: datetime) -> bool:
|
||||
"""
|
||||
检查止盈条件
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
current_price: 当前价格
|
||||
timestamp: 当前时间
|
||||
|
||||
# 计算总分数变化
|
||||
total_score_change = sum(score_changes)
|
||||
if total_score_change == 0:
|
||||
return # 没有分数变化,直接返回
|
||||
Returns:
|
||||
bool: 是否触发止盈
|
||||
"""
|
||||
# 如果没有设置止盈,直接返回False
|
||||
if self.profit_target is None:
|
||||
return False
|
||||
|
||||
# 应用分数变化,但分数最低为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:全仓买入
|
||||
if not self.holding_stocks[stock_code] or self.buy_prices[stock_code] <= 0:
|
||||
return False
|
||||
|
||||
buy_price = self.buy_prices[stock_code]
|
||||
profit_rate = (current_price - buy_price) / buy_price
|
||||
|
||||
if profit_rate >= self.profit_target:
|
||||
# 检查T+1限制
|
||||
if self._can_sell_today(stock_code, timestamp):
|
||||
# 触发止盈,清仓并置0分
|
||||
signal = Signal(
|
||||
stock_code=stock_code,
|
||||
action='BUY_ALL', # 全仓买入
|
||||
amount=0, # 全仓买入时amount设为0
|
||||
action='SELL_ALL',
|
||||
amount=0,
|
||||
price=None,
|
||||
timestamp=timestamp,
|
||||
reason=f"score_0_to_1_buy_all_change_{total_score_change}"
|
||||
reason=f"profit_target_{profit_rate:.2%}_reached"
|
||||
)
|
||||
self.signals.append(signal)
|
||||
|
||||
# 重置状态
|
||||
self.holding_stocks[stock_code] = False
|
||||
self.stock_scores[stock_code] = 0
|
||||
self.buy_dates[stock_code] = None
|
||||
self.buy_prices[stock_code] = 0.0
|
||||
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
def _check_price_above_ma5_daily(self, stock_code: str, current_price: float, timestamp: datetime) -> bool:
|
||||
"""
|
||||
检查当前股价是否大于买入阈值*日K5日均线
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
current_price: 当前价格
|
||||
timestamp: 当前时间
|
||||
|
||||
Returns:
|
||||
bool: 是否满足买入价格条件
|
||||
"""
|
||||
try:
|
||||
if self.daily_timeframe not in self.model_cache:
|
||||
logger.warning(f"[{self.name}] 日线模型未创建,跳过5日均线检查")
|
||||
return True # 如果没有日线数据,默认通过
|
||||
|
||||
# 获取日线数据
|
||||
daily_data = self._get_timeframe_data(self.daily_timeframe, timestamp, lookback_periods=10)
|
||||
|
||||
if daily_data.empty or 'MA5' not in daily_data.columns:
|
||||
logger.warning(f"[{self.name}] 无法获取日线MA5数据,跳过检查")
|
||||
return True # 如果没有足够数据,默认通过
|
||||
|
||||
# 获取最新的5日均线值
|
||||
latest_ma5 = daily_data['MA5'].iloc[-1]
|
||||
|
||||
if np.isnan(latest_ma5):
|
||||
logger.warning(f"[{self.name}] 5日均线数据无效,跳过检查")
|
||||
return True
|
||||
|
||||
# 检查当前价格是否大于5日均线(去掉阈值判断)
|
||||
is_above = current_price > latest_ma5
|
||||
|
||||
logger.info(f"[{self.name}] 价格条件检查: 当前价格={current_price:.4f}, 5日均线={latest_ma5:.4f}, 必须大于5日均线,满足条件={is_above}")
|
||||
|
||||
return is_above
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] 检查买入价格条件时出错: {e}")
|
||||
return True # 出错时默认通过
|
||||
|
||||
def _check_price_vs_intraday_avg(self, stock_code: str, current_price: float, timestamp: datetime) -> bool:
|
||||
"""
|
||||
检查实时股价与当天分时均价的差距
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
current_price: 当前价格
|
||||
timestamp: 当前时间
|
||||
|
||||
Returns:
|
||||
bool: 差距是否小于均价的3%
|
||||
"""
|
||||
try:
|
||||
# 获取当天开盘时间(9:30)
|
||||
trade_date = timestamp.date()
|
||||
market_open = datetime.combine(trade_date, datetime.strptime("09:30", "%H:%M").time())
|
||||
|
||||
# 如果当前时间在开盘前,无法计算分时均价
|
||||
if timestamp < market_open:
|
||||
logger.info(f"[{self.name}] 未到开盘时间,跳过分时均价检查")
|
||||
return True
|
||||
|
||||
# 获取当天从开盘到当前时间的1分钟数据
|
||||
if '1m' not in self.model_cache:
|
||||
logger.warning(f"[{self.name}] 1分钟模型未创建,跳过分时均价检查")
|
||||
return True
|
||||
|
||||
model = self.model_cache['1m']
|
||||
|
||||
# 查询当天的数据
|
||||
daily_records = (model.select()
|
||||
.where(
|
||||
(model.timestamp >= market_open) &
|
||||
(model.timestamp <= timestamp)
|
||||
)
|
||||
.order_by(model.timestamp))
|
||||
|
||||
if not daily_records.exists():
|
||||
logger.warning(f"[{self.name}] 没有找到当天的1分钟数据,跳过分时均价检查")
|
||||
return True
|
||||
|
||||
# 计算当天的分时均价 (VWAP - Volume Weighted Average Price)
|
||||
total_volume = 0
|
||||
total_amount = 0
|
||||
|
||||
for record in daily_records:
|
||||
if record.volume > 0: # 只计算有成交量的记录
|
||||
# 使用典型价格 (high + low + close) / 3 作为该分钟的代表价格
|
||||
typical_price = (record.high + record.low + record.close) / 3
|
||||
total_amount += typical_price * record.volume
|
||||
total_volume += record.volume
|
||||
|
||||
if total_volume <= 0:
|
||||
logger.warning(f"[{self.name}] 当天无有效成交量数据,跳过分时均价检查")
|
||||
return True
|
||||
|
||||
# 计算分时均价(VWAP)
|
||||
intraday_vwap = total_amount / total_volume
|
||||
|
||||
# 计算当前价格与分时均价的差距
|
||||
price_diff = abs(current_price - intraday_vwap)
|
||||
price_diff_ratio = price_diff / intraday_vwap
|
||||
|
||||
# 检查差距是否小于均价的1%(更严格的条件)
|
||||
threshold = 0.01 # 1%
|
||||
is_close_enough = price_diff_ratio < threshold
|
||||
|
||||
logger.info(f"[{self.name}] 分时均价检查: 当前价格={current_price:.4f}, 分时均价={intraday_vwap:.4f}, "
|
||||
f"差距比例={price_diff_ratio:.4f}({price_diff_ratio*100:.2f}%), "
|
||||
f"阈值={threshold*100:.1f}%, 满足条件={is_close_enough}")
|
||||
|
||||
return is_close_enough
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] 检查分时均价条件时出错: {e}")
|
||||
return True # 出错时默认通过
|
||||
|
||||
def _update_score(self, stock_code: str, timestamp: datetime) -> int:
|
||||
"""
|
||||
更新股票分数(检查所有时间周期)
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
timestamp: 当前时间
|
||||
|
||||
Returns:
|
||||
int: 新的分数
|
||||
"""
|
||||
current_score = self.stock_scores[stock_code]
|
||||
score_changes = []
|
||||
|
||||
# 检查所有时间周期
|
||||
for timeframe in self.signal_timeframes:
|
||||
tf_data = self._get_timeframe_data(timeframe, timestamp, lookback_periods=100)
|
||||
|
||||
if tf_data.empty:
|
||||
continue
|
||||
|
||||
# 检测交叉信号
|
||||
crossover = self._detect_ma_crossover(tf_data, timeframe)
|
||||
|
||||
if crossover:
|
||||
# 检查是否与上次信号重复
|
||||
last_status = self.last_crossover_status.get(timeframe, None)
|
||||
if last_status == crossover:
|
||||
continue # 重复信号,跳过
|
||||
|
||||
# 更新状态
|
||||
self.last_crossover_status[timeframe] = crossover
|
||||
|
||||
# 记录信号
|
||||
self._record_crossover_signal(stock_code, timestamp, timeframe, crossover, tf_data)
|
||||
|
||||
# 记录分数变化
|
||||
if crossover == 'golden_cross':
|
||||
score_changes.append(1) # 金叉+1分
|
||||
elif crossover == 'death_cross':
|
||||
score_changes.append(-1) # 死叉-1分
|
||||
|
||||
# 计算新分数(分数最低为0)
|
||||
total_change = sum(score_changes)
|
||||
new_score = max(0, current_score + total_change)
|
||||
|
||||
return new_score
|
||||
|
||||
def _check_buy_signals(self, stock_code: str, current_price: float, timestamp: datetime):
|
||||
"""
|
||||
检查买入信号(每5分钟调用一次)
|
||||
买入条件:当前15分钟已金叉且持续金叉状态 且 股价大于日K5日线
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
current_price: 当前价格
|
||||
timestamp: 当前时间
|
||||
"""
|
||||
# 如果已持仓,不需要再检查买入
|
||||
if self.holding_stocks[stock_code]:
|
||||
return
|
||||
|
||||
# 检查15分钟级别是否处于持续金叉状态
|
||||
tf_15m_data = self._get_timeframe_data('15m', timestamp, lookback_periods=50)
|
||||
if tf_15m_data.empty or 'MA5' not in tf_15m_data.columns or 'MA18' not in tf_15m_data.columns:
|
||||
return
|
||||
|
||||
# 检查是否为有效金叉状态:
|
||||
# 1. 当前MA5 > MA18
|
||||
# 2. 在最近的几个周期内都保持MA5 > MA18(确保金叉状态持续)
|
||||
recent_periods = min(5, len(tf_15m_data)) # 检查最近5个周期或全部数据
|
||||
recent_data = tf_15m_data.tail(recent_periods)
|
||||
|
||||
ma5_values = recent_data['MA5'].values
|
||||
ma18_values = recent_data['MA18'].values
|
||||
|
||||
# 检查是否为有效数值
|
||||
if np.isnan(ma5_values).any() or np.isnan(ma18_values).any():
|
||||
return
|
||||
|
||||
# 当前必须是金叉状态
|
||||
current_is_golden = ma5_values[-1] > ma18_values[-1]
|
||||
if not current_is_golden:
|
||||
return # 当前不是金叉状态,不买入
|
||||
|
||||
# 检查金叉状态的持续性:至少在最近3个周期内MA5都大于MA18
|
||||
# 这确保不是刚刚发生的临时交叉
|
||||
if len(ma5_values) >= 3:
|
||||
recent_3_periods = ma5_values[-3:] > ma18_values[-3:]
|
||||
golden_persistence = np.sum(recent_3_periods) >= 2 # 至少3个周期中有2个是金叉
|
||||
|
||||
if not golden_persistence:
|
||||
logger.info(f"[{self.name}] 15分钟金叉状态不够稳定,暂不买入")
|
||||
return
|
||||
|
||||
logger.info(f"[{self.name}] 15分钟确认持续金叉状态: MA5={ma5_values[-1]:.4f} > MA18={ma18_values[-1]:.4f}")
|
||||
|
||||
# 检查股价是否大于日K5日线(去掉阈值判断)
|
||||
if not self._check_price_above_ma5_daily(stock_code, current_price, timestamp):
|
||||
return # 价格条件不满足,不买入
|
||||
|
||||
# 检查当前分数是否大于0
|
||||
if self.stock_scores[stock_code] <= 0:
|
||||
return # 分数不够,不买入
|
||||
|
||||
# 检查实时股价与当天分时均价的差距(新增条件)
|
||||
if not self._check_price_vs_intraday_avg(stock_code, current_price, timestamp):
|
||||
return # 价格与分时均价差距过大,不买入
|
||||
|
||||
# 满足所有买入条件,执行买入
|
||||
signal = Signal(
|
||||
stock_code=stock_code,
|
||||
action='BUY_ALL',
|
||||
amount=0,
|
||||
price=None,
|
||||
timestamp=timestamp,
|
||||
reason=f"15m_golden_cross_and_price_above_ma5_and_close_to_vwap_1pct"
|
||||
)
|
||||
self.signals.append(signal)
|
||||
|
||||
# 更新持仓状态
|
||||
self.holding_stocks[stock_code] = True
|
||||
self.buy_dates[stock_code] = timestamp
|
||||
|
||||
logger.info(f"[{self.name}] 买入信号: 15分钟金叉状态且股价>日K5日线且分数={self.stock_scores[stock_code]}且价格与分时均价差距<1%")
|
||||
|
||||
def _check_sell_signals(self, stock_code: str, current_score: int, current_price: float, timestamp: datetime):
|
||||
"""
|
||||
检查卖出信号(每15分钟调用一次)
|
||||
卖出条件:当前股票分数≤0
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
current_score: 当前分数
|
||||
current_price: 当前价格
|
||||
timestamp: 当前时间
|
||||
"""
|
||||
# 如果未持仓,不需要检查卖出
|
||||
if not self.holding_stocks[stock_code]:
|
||||
return
|
||||
|
||||
# 检查卖出条件:分数≤0
|
||||
if current_score <= 0:
|
||||
# 检查T+1限制
|
||||
if self._can_sell_today(stock_code, timestamp):
|
||||
signal = Signal(
|
||||
stock_code=stock_code,
|
||||
action='SELL_ALL',
|
||||
amount=0,
|
||||
price=None,
|
||||
timestamp=timestamp,
|
||||
reason=f"score_{current_score}_sell_all"
|
||||
)
|
||||
self.signals.append(signal)
|
||||
|
||||
# 更新持仓状态
|
||||
self.holding_stocks[stock_code] = True
|
||||
self.holding_stocks[stock_code] = False
|
||||
self.buy_dates[stock_code] = None
|
||||
self.buy_prices[stock_code] = 0.0
|
||||
|
||||
elif old_score == 1 and new_score == 0:
|
||||
# 仅当分数从1变成0时:清仓并重置分数为0
|
||||
logger.info(f"[{self.name}] 卖出信号: 分数={current_score}≤0,清仓卖出")
|
||||
else:
|
||||
logger.info(f"[{self.name}] 卖出信号被T+1限制,暂不卖出")
|
||||
|
||||
def _handle_trading_signals(self, stock_code: str, old_score: int, new_score: int,
|
||||
current_price: float, timestamp: datetime):
|
||||
"""
|
||||
处理交易信号
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
old_score: 旧分数
|
||||
new_score: 新分数
|
||||
current_price: 当前价格
|
||||
timestamp: 当前时间
|
||||
"""
|
||||
# 更新分数
|
||||
self.stock_scores[stock_code] = new_score
|
||||
|
||||
# 检查买入条件:分数>0且股价>买入阈值*日K5日线且未持仓
|
||||
if (new_score > 0 and
|
||||
not self.holding_stocks[stock_code] and
|
||||
self._check_price_above_ma5_daily(stock_code, current_price, timestamp)):
|
||||
|
||||
# 执行买入
|
||||
signal = Signal(
|
||||
stock_code=stock_code,
|
||||
action='BUY_ALL',
|
||||
amount=0,
|
||||
price=None,
|
||||
timestamp=timestamp,
|
||||
reason=f"score_{new_score}_above_ma5_daily_buy"
|
||||
)
|
||||
self.signals.append(signal)
|
||||
|
||||
# 更新持仓状态
|
||||
self.holding_stocks[stock_code] = True
|
||||
self.buy_dates[stock_code] = timestamp
|
||||
|
||||
logger.info(f"[{self.name}] 买入信号: 分数={new_score}>0且股价满足买入条件")
|
||||
|
||||
# 检查卖出条件:分数从>0变成0且持有股票
|
||||
elif (old_score > 0 and new_score == 0 and self.holding_stocks[stock_code]):
|
||||
|
||||
# 检查T+1限制
|
||||
if self._can_sell_today(stock_code, timestamp):
|
||||
signal = Signal(
|
||||
stock_code=stock_code,
|
||||
action='SELL_ALL', # 清仓
|
||||
action='SELL_ALL',
|
||||
amount=0,
|
||||
price=None,
|
||||
timestamp=timestamp,
|
||||
reason=f"score_1_to_0_sell_all_change_{total_score_change}"
|
||||
reason=f"score_to_0_sell_all"
|
||||
)
|
||||
self.signals.append(signal)
|
||||
|
||||
# 更新持仓状态和重置分数
|
||||
# 更新持仓状态
|
||||
self.holding_stocks[stock_code] = False
|
||||
self.stock_scores[stock_code] = 0 # 清仓后分数重置为0
|
||||
self.buy_dates[stock_code] = None
|
||||
self.buy_prices[stock_code] = 0.0
|
||||
|
||||
logger.info(f"[{self.name}] 卖出信号: 分数变为0")
|
||||
else:
|
||||
logger.info(f"[{self.name}] 卖出信号被T+1限制,暂不卖出")
|
||||
|
||||
def _can_sell_today(self, stock_code: str, timestamp: datetime) -> bool:
|
||||
"""
|
||||
检查是否可以在当天卖出(T+1限制)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] 处理数据时出错: {e}")
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
timestamp: 当前时间
|
||||
|
||||
Returns:
|
||||
bool: 是否可以卖出
|
||||
"""
|
||||
if stock_code not in self.buy_dates or self.buy_dates[stock_code] is None:
|
||||
return True # 没有买入记录,可以卖出
|
||||
|
||||
buy_date = self.buy_dates[stock_code].date()
|
||||
current_date = timestamp.date()
|
||||
|
||||
return current_date > buy_date # 只有在买入日期之后才能卖出
|
||||
|
||||
def _record_crossover_signal(self, stock_code: str, timestamp: datetime, timeframe: str, crossover: str, tf_data: pd.DataFrame):
|
||||
"""记录交叉信号"""
|
||||
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
|
||||
|
||||
def update_buy_price(self, stock_code: str, buy_price: float):
|
||||
"""
|
||||
更新买入价格(由回测引擎调用)
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
buy_price: 买入价格
|
||||
"""
|
||||
self.buy_prices[stock_code] = buy_price
|
||||
|
||||
def get_signal_statistics(self) -> Dict:
|
||||
"""获取信号统计信息"""
|
||||
|
||||
@ -1,493 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
多时间周期移动平均线交叉策略 - 评分版本
|
||||
基于用户要求的评分系统:
|
||||
- 每个时间周期发生金叉 +1分,死叉 -1分
|
||||
- 分数从-1变成0时发出买入信号
|
||||
- 分数从0变成-1时发出卖出信号
|
||||
- 最低分数为-1(不会降到更低)
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import pandas as pd
|
||||
import logging
|
||||
from datetime import datetime
|
||||
from typing import Dict, List, Optional
|
||||
|
||||
# 添加项目路径
|
||||
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, create_all_timeframe_models, SUPPORTED_PERIODS
|
||||
except ImportError as e:
|
||||
print(f"导入错误: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class MultiTimeframeMAScoreStrategy(StrategyBase):
|
||||
"""
|
||||
多时间周期均线交叉评分策略(修正版)
|
||||
|
||||
策略逻辑:
|
||||
1. 监控15分钟、30分钟、60分钟三个时间周期
|
||||
2. 每个时间周期只使用MA5和MA20两根移动平均线
|
||||
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]):
|
||||
"""
|
||||
初始化策略
|
||||
|
||||
Args:
|
||||
ma_periods: 移动平均线周期列表,默认[5, 20]期(仅用于兼容性)
|
||||
"""
|
||||
super().__init__(
|
||||
name="MultiTimeframeMAScore"
|
||||
)
|
||||
|
||||
self.description = "多时间周期均线交叉评分策略(修正版)"
|
||||
|
||||
# 简化为只使用MA5和MA20
|
||||
self.ma_periods = [5, 20]
|
||||
|
||||
# 使用支持的时间周期:15分钟、30分钟、60分钟
|
||||
self.timeframes = SUPPORTED_PERIODS # ['15m', '30m', '60m']
|
||||
|
||||
# 股票评分系统 - 为每个股票维护分数,默认为0
|
||||
self.stock_scores = {}
|
||||
|
||||
# 交易参数
|
||||
self.trade_amount = 100000 # 每次交易金额(元)
|
||||
|
||||
# 各时间周期的预加载数据缓存
|
||||
self.timeframe_data = {}
|
||||
|
||||
# 各时间周期上次检查状态
|
||||
self.last_crossover_status = {}
|
||||
|
||||
# 数据库模型缓存,避免重复创建
|
||||
self.model_cache = {}
|
||||
|
||||
# 信号记录功能(可选,由外部设置)
|
||||
# 这些属性将在需要时由回测脚本添加
|
||||
# self.crossover_signals = [] # 详细信号记录
|
||||
# self.signal_stats = {} # 信号统计
|
||||
|
||||
def initialize(self) -> bool:
|
||||
"""初始化策略并预加载所有时间周期数据"""
|
||||
try:
|
||||
# 初始化数据库连接
|
||||
init_database()
|
||||
|
||||
logger.info(f"[{self.name}] Multi-timeframe MA crossover strategy initialized")
|
||||
logger.info(f"[{self.name}] MA periods: {self.ma_periods}")
|
||||
logger.info(f"[{self.name}] Monitoring timeframes: {self.timeframes}")
|
||||
|
||||
# 预加载所有时间周期的数据
|
||||
self._preload_timeframe_data()
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] 策略初始化失败: {e}")
|
||||
return False
|
||||
|
||||
def _preload_timeframe_data(self):
|
||||
"""预加载所有时间周期的数据"""
|
||||
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:
|
||||
logger.warning(f"[{self.name}] {timeframe} 模型不存在,跳过")
|
||||
continue
|
||||
|
||||
model_class = self.model_cache[timeframe]
|
||||
|
||||
# 查询2025年所有数据(根据您的数据),按时间排序
|
||||
query = model_class.select().where(
|
||||
(model_class.timestamp >= '2025-01-01') &
|
||||
(model_class.timestamp <= '2025-07-31')
|
||||
).order_by(model_class.timestamp)
|
||||
|
||||
# 转换为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 data:
|
||||
df = pd.DataFrame(data)
|
||||
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
||||
df = df.set_index('timestamp').sort_index()
|
||||
|
||||
# 只计算MA5和MA20
|
||||
df['MA5'] = df['close'].rolling(window=5).mean()
|
||||
df['MA20'] = df['close'].rolling(window=20).mean()
|
||||
|
||||
# 缓存数据
|
||||
self.timeframe_data[timeframe] = df
|
||||
|
||||
logger.info(f"[{self.name}] ✅ 预加载 {timeframe} 数据: {len(df)} 条记录 "
|
||||
f"({df.index.min().strftime('%Y-%m-%d')} 到 {df.index.max().strftime('%Y-%m-%d')})")
|
||||
else:
|
||||
logger.warning(f"[{self.name}] ⚠️ {timeframe} 没有数据")
|
||||
self.timeframe_data[timeframe] = pd.DataFrame()
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] 预加载 {timeframe} 数据失败: {e}")
|
||||
self.timeframe_data[timeframe] = pd.DataFrame()
|
||||
|
||||
def get_timeframe_data_at_time(self, timeframe: str, timestamp: datetime, lookback_periods: int = 50) -> pd.DataFrame:
|
||||
"""
|
||||
获取指定时间周期在指定时间点之前的数据
|
||||
|
||||
Args:
|
||||
timeframe: 时间周期 ('15m', '30m', '60m')
|
||||
timestamp: 当前时间点
|
||||
lookback_periods: 向前查看的周期数
|
||||
|
||||
Returns:
|
||||
pd.DataFrame: 包含移动平均线的历史数据
|
||||
"""
|
||||
try:
|
||||
if timeframe not in self.timeframe_data:
|
||||
return pd.DataFrame()
|
||||
|
||||
df = self.timeframe_data[timeframe]
|
||||
if df.empty:
|
||||
return pd.DataFrame()
|
||||
|
||||
# 获取指定时间点之前的数据
|
||||
mask = df.index <= timestamp
|
||||
filtered_df = df[mask]
|
||||
|
||||
if len(filtered_df) == 0:
|
||||
return pd.DataFrame()
|
||||
|
||||
# 取最后lookback_periods个数据点
|
||||
if len(filtered_df) > lookback_periods:
|
||||
filtered_df = filtered_df.tail(lookback_periods)
|
||||
|
||||
return filtered_df
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] 获取{timeframe}在{timestamp}的数据失败: {e}")
|
||||
return pd.DataFrame()
|
||||
|
||||
def calculate_ma_crossovers(self, df: pd.DataFrame) -> List[tuple]:
|
||||
"""
|
||||
计算MA5和MA20的交叉状态
|
||||
|
||||
简化逻辑:
|
||||
- 只计算MA5和MA20的交叉
|
||||
- MA5上穿MA20 = 金叉
|
||||
- MA5下穿MA20 = 死叉
|
||||
|
||||
Returns:
|
||||
List[tuple]: [(交叉类型, 短期均线, 长期均线, 短期值, 长期值)]
|
||||
"""
|
||||
crossovers = []
|
||||
|
||||
# 只需要MA5和MA20
|
||||
if len(df) < 20: # 至少需要20个数据点计算MA20
|
||||
return crossovers
|
||||
|
||||
# 计算MA5和MA20(避免 SettingWithCopyWarning)
|
||||
df = df.copy()
|
||||
df['ma_5'] = df['close'].rolling(window=5).mean()
|
||||
df['ma_20'] = df['close'].rolling(window=20).mean()
|
||||
|
||||
# 需要至少两个数据点来检测交叉
|
||||
if len(df) < 2:
|
||||
return crossovers
|
||||
|
||||
# 最新和前一个数据点
|
||||
current = df.iloc[-1]
|
||||
previous = df.iloc[-2]
|
||||
|
||||
# 跳过NaN值
|
||||
if (pd.isna(current['ma_5']) or pd.isna(current['ma_20']) or
|
||||
pd.isna(previous['ma_5']) or pd.isna(previous['ma_20'])):
|
||||
return crossovers
|
||||
|
||||
# 检查金叉:MA5从下方穿越到上方
|
||||
if (previous['ma_5'] <= previous['ma_20'] and
|
||||
current['ma_5'] > current['ma_20']):
|
||||
crossovers.append((
|
||||
'golden',
|
||||
5,
|
||||
20,
|
||||
current['ma_5'],
|
||||
current['ma_20']
|
||||
))
|
||||
|
||||
# 检查死叉:MA5从上方穿越到下方
|
||||
elif (previous['ma_5'] >= previous['ma_20'] and
|
||||
current['ma_5'] < current['ma_20']):
|
||||
crossovers.append((
|
||||
'death',
|
||||
5,
|
||||
20,
|
||||
current['ma_5'],
|
||||
current['ma_20']
|
||||
))
|
||||
|
||||
return crossovers
|
||||
|
||||
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, trade_signals, crossover_details)
|
||||
"""
|
||||
# 初始化股票分数为0
|
||||
if stock_code not in self.stock_scores:
|
||||
self.stock_scores[stock_code] = 0
|
||||
|
||||
old_score = self.stock_scores[stock_code]
|
||||
score_change = 0
|
||||
crossover_details = []
|
||||
|
||||
# 统计金叉和死叉数量
|
||||
for crossover_type, short_period, long_period, short_value, long_value in crossovers:
|
||||
if crossover_type == 'golden':
|
||||
score_change += 1
|
||||
crossover_details.append(f"MA{short_period}↗MA{long_period}")
|
||||
elif crossover_type == 'death':
|
||||
score_change -= 1
|
||||
crossover_details.append(f"MA{short_period}↘MA{long_period}")
|
||||
|
||||
# 更新分数,确保最低分数为0
|
||||
new_score = max(0, old_score + score_change)
|
||||
self.stock_scores[stock_code] = new_score
|
||||
|
||||
# 生成交易信号
|
||||
trade_signals = []
|
||||
actual_score_change = new_score - old_score
|
||||
|
||||
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]:
|
||||
"""
|
||||
策略核心逻辑 - 检查各时间周期的均线交叉
|
||||
|
||||
Args:
|
||||
data: 1分钟K线数据 (包含stock_code信息)
|
||||
timestamp: 当前时间戳
|
||||
|
||||
Returns:
|
||||
List[Signal]: 生成的交易信号列表
|
||||
"""
|
||||
signals = []
|
||||
|
||||
try:
|
||||
# 从数据中提取股票代码,假设数据索引包含股票信息或有stock_code列
|
||||
# 由于回测引擎的限制,我们需要从其他方式获取股票代码
|
||||
# 这里使用我们知道的测试股票代码
|
||||
stock_code = "601398.SH" # 暂时硬编码,实际应该从data中获取
|
||||
|
||||
# 获取当前股价
|
||||
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] = 0
|
||||
|
||||
# 限制检查频率 - 只在每15分钟检查一次各时间周期
|
||||
# 这可以显著减少数据库查询次数
|
||||
minute = timestamp.minute
|
||||
if minute % 15 != 0:
|
||||
return signals
|
||||
|
||||
# 为每个时间周期检查均线交叉
|
||||
for timeframe in self.timeframes:
|
||||
# 从预加载的数据中获取指定时间点的历史数据
|
||||
df = self.get_timeframe_data_at_time(timeframe, timestamp)
|
||||
|
||||
if df.empty:
|
||||
continue
|
||||
|
||||
# 计算多条均线交叉
|
||||
crossovers = self.calculate_ma_crossovers(df)
|
||||
|
||||
if 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:
|
||||
logger.info(f"[{self.name}] {stock_code} {timeframe} Found {crossover_type} crossover: "
|
||||
f"MA{short_period}={short_value:.3f} vs MA{long_period}={long_value:.3f}")
|
||||
|
||||
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)}")
|
||||
|
||||
# 生成交易信号
|
||||
for trade_signal in trade_signals:
|
||||
signal = Signal(
|
||||
timestamp=timestamp,
|
||||
stock_code=stock_code,
|
||||
action=trade_signal['action'],
|
||||
strength=1.0,
|
||||
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 {trade_signal['action']} signal: {stock_code} "
|
||||
f"Reason: {trade_signal['reason']}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"[{self.name}] Error processing data: {e}")
|
||||
|
||||
return signals
|
||||
|
||||
def get_strategy_info(self) -> Dict:
|
||||
"""获取策略信息"""
|
||||
return {
|
||||
'name': self.name,
|
||||
'description': self.description,
|
||||
'timeframes': self.timeframes,
|
||||
'ma_periods': self.ma_periods,
|
||||
'current_scores': self.stock_scores.copy()
|
||||
}
|
||||
|
||||
def test_strategy():
|
||||
"""测试策略功能"""
|
||||
print("🧪 测试多时间周期评分策略...")
|
||||
|
||||
# 创建策略实例
|
||||
strategy = MultiTimeframeMAScoreStrategy()
|
||||
|
||||
# 初始化策略
|
||||
if not strategy.initialize():
|
||||
print("❌ 策略初始化失败")
|
||||
return
|
||||
|
||||
print("✅ 策略初始化成功")
|
||||
|
||||
# 模拟数据处理
|
||||
test_data = pd.DataFrame({
|
||||
'timestamp': [datetime.now()],
|
||||
'open': [7.55],
|
||||
'high': [7.60],
|
||||
'low': [7.50],
|
||||
'close': [7.57],
|
||||
'volume': [1000000]
|
||||
})
|
||||
|
||||
test_stock = "601398.SH"
|
||||
test_time = datetime.now()
|
||||
|
||||
print(f"📊 测试股票: {test_stock}")
|
||||
|
||||
# 调用策略 (注意:测试时股票代码是硬编码在策略内部的)
|
||||
signals = strategy.on_data(test_data, test_time)
|
||||
|
||||
print(f"🎯 生成信号数量: {len(signals)}")
|
||||
for signal in signals:
|
||||
print(f" 📈 {signal.action}: {signal.reason}")
|
||||
|
||||
# 显示策略信息
|
||||
info = strategy.get_strategy_info()
|
||||
print("\n📋 策略信息:")
|
||||
for key, value in info.items():
|
||||
print(f" {key}: {value}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_strategy()
|
||||
@ -1,784 +0,0 @@
|
||||
"""
|
||||
多时间周期均线交叉策略
|
||||
|
||||
基于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()
|
||||
@ -1,326 +0,0 @@
|
||||
"""
|
||||
多时间周期均线交叉策略
|
||||
|
||||
基于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
|
||||
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):
|
||||
"""多时间周期均线交叉策略"""
|
||||
|
||||
def __init__(self, name: str = "MultiTimeFrameMA", params: Optional[Dict[str, Any]] = None):
|
||||
"""初始化策略"""
|
||||
super().__init__(name, params)
|
||||
|
||||
# 策略参数
|
||||
self.short_ma = self.get_parameter('short_ma', 5)
|
||||
self.long_ma = self.get_parameter('long_ma', 20)
|
||||
self.position_size = self.get_parameter('position_size', 0.5)
|
||||
|
||||
# 时间周期配置
|
||||
self.timeframes = ['15m', '30m', '60m']
|
||||
|
||||
# 技术指标计算器
|
||||
self.indicators = TechnicalIndicators()
|
||||
|
||||
# 股票分数系统
|
||||
self.stock_scores = {}
|
||||
self.previous_scores = {}
|
||||
self.ma_states = {}
|
||||
|
||||
self.log_info("多时间周期均线交叉策略初始化完成")
|
||||
|
||||
def initialize(self):
|
||||
"""策略初始化"""
|
||||
self.log_info("策略初始化完成")
|
||||
|
||||
def on_data(self, data: pd.DataFrame, timestamp: datetime):
|
||||
"""处理新的数据"""
|
||||
try:
|
||||
if 'symbol' in data.columns and not data.empty:
|
||||
symbol = data['symbol'].iloc[0]
|
||||
|
||||
bar_data = {
|
||||
'symbol': symbol,
|
||||
'datetime': timestamp,
|
||||
'close': data['close'].iloc[-1]
|
||||
}
|
||||
|
||||
signals = self.process_bar(bar_data)
|
||||
|
||||
for signal_data in signals:
|
||||
self.generate_signal(
|
||||
timestamp=signal_data['timestamp'],
|
||||
stock_code=signal_data['symbol'],
|
||||
action=signal_data['action'],
|
||||
strength=1.0,
|
||||
reason=signal_data['reason']
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.log_error(f"处理数据失败: {e}")
|
||||
|
||||
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] = {}
|
||||
|
||||
for timeframe in self.timeframes:
|
||||
self.ma_states[symbol][timeframe] = {
|
||||
'short_ma': [],
|
||||
'long_ma': [],
|
||||
'last_cross': None
|
||||
}
|
||||
|
||||
def detect_ma_crossover(self, short_ma: List[float], long_ma: List[float]) -> Optional[str]:
|
||||
"""检测均线金叉死叉"""
|
||||
if len(short_ma) < 2 or len(long_ma) < 2:
|
||||
return None
|
||||
|
||||
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:
|
||||
"""加载指定时间周期的历史数据"""
|
||||
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.timestamp <= current_time)
|
||||
.order_by(KlineModel.timestamp.desc())
|
||||
.limit(periods_needed))
|
||||
|
||||
data = []
|
||||
for record in query:
|
||||
data.append({
|
||||
'datetime': record.timestamp,
|
||||
'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]:
|
||||
"""更新各时间周期的均线分析"""
|
||||
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
|
||||
cross_type = "金叉" if crossover == 'golden' else "死叉"
|
||||
logger.info(f"[{symbol}] {timeframe} 检测到{cross_type}")
|
||||
|
||||
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]:
|
||||
"""更新股票分数"""
|
||||
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")
|
||||
|
||||
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[Dict[str, Any]]:
|
||||
"""处理新的K线数据"""
|
||||
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:
|
||||
signal_data = {
|
||||
'symbol': symbol,
|
||||
'action': 'BUY',
|
||||
'price': current_price,
|
||||
'timestamp': current_time,
|
||||
'reason': f"多时间周期金叉,分数: {previous_score}->{new_score}"
|
||||
}
|
||||
signals.append(signal_data)
|
||||
logger.info(f"[{symbol}] 买入信号: 分数{previous_score}->{new_score}")
|
||||
|
||||
elif previous_score == 1 and new_score == 0:
|
||||
signal_data = {
|
||||
'symbol': symbol,
|
||||
'action': 'SELL',
|
||||
'price': current_price,
|
||||
'timestamp': current_time,
|
||||
'reason': f"多时间周期死叉,分数: {previous_score}->{new_score}"
|
||||
}
|
||||
signals.append(signal_data)
|
||||
logger.info(f"[{symbol}] 卖出信号: 分数{previous_score}->{new_score}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理{symbol}数据失败: {e}")
|
||||
|
||||
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,
|
||||
'current_scores': self.stock_scores.copy()
|
||||
}
|
||||
|
||||
|
||||
def create_multi_timeframe_strategy(params: Optional[Dict[str, Any]] = None) -> MultiTimeFrameMAStrategy:
|
||||
"""创建多时间周期均线交叉策略实例"""
|
||||
if params is None:
|
||||
params = {
|
||||
'short_ma': 5,
|
||||
'long_ma': 20,
|
||||
'position_size': 0.3
|
||||
}
|
||||
|
||||
return MultiTimeFrameMAStrategy("MultiTimeFrameMA", params)
|
||||
|
||||
|
||||
def test_multi_timeframe_strategy():
|
||||
"""测试多时间周期策略"""
|
||||
print("🧪 测试多时间周期均线交叉策略")
|
||||
|
||||
try:
|
||||
if not init_database():
|
||||
print("❌ 数据库连接失败")
|
||||
return False
|
||||
|
||||
strategy = create_multi_timeframe_strategy()
|
||||
print("✅ 策略实例创建成功")
|
||||
|
||||
test_data = {
|
||||
'symbol': '601398.SH',
|
||||
'datetime': datetime(2024, 8, 1, 10, 0, 0),
|
||||
'close': 5.05
|
||||
}
|
||||
|
||||
print("📊 处理测试数据...")
|
||||
signals = strategy.process_bar(test_data)
|
||||
|
||||
print(f"✅ 处理完成,生成{len(signals)}个信号")
|
||||
for signal in signals:
|
||||
print(f" 信号: {signal['action']} {signal['symbol']} @ {signal['price']}")
|
||||
|
||||
info = strategy.get_strategy_info()
|
||||
print(f"📋 策略信息: {info['name']}")
|
||||
print(f" 描述: {info['description']}")
|
||||
print(f" 时间周期: {info['timeframes']}")
|
||||
print(f" 当前分数: {info['current_scores']}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_multi_timeframe_strategy()
|
||||
@ -1,362 +0,0 @@
|
||||
"""
|
||||
多时间周期均线交叉策略 - 无TA-Lib依赖版本
|
||||
|
||||
基于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
|
||||
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 SimpleMovingAverage:
|
||||
"""简单移动平均线计算器(不依赖TA-Lib)"""
|
||||
|
||||
@staticmethod
|
||||
def calculate_ma(data: pd.Series, period: int) -> pd.Series:
|
||||
"""计算简单移动平均线"""
|
||||
return data.rolling(window=period, min_periods=period).mean()
|
||||
|
||||
@staticmethod
|
||||
def ma_from_df(df: pd.DataFrame, periods: List[int]) -> Dict[str, pd.Series]:
|
||||
"""从DataFrame计算多个周期的移动平均线"""
|
||||
close = df['close']
|
||||
result = {}
|
||||
for period in periods:
|
||||
result[f'ma{period}'] = SimpleMovingAverage.calculate_ma(close, period)
|
||||
return result
|
||||
|
||||
|
||||
class MultiTimeFrameMAStrategy(StrategyBase):
|
||||
"""多时间周期均线交叉策略"""
|
||||
|
||||
def __init__(self, name: str = "MultiTimeFrameMA", params: Optional[Dict[str, Any]] = None):
|
||||
"""初始化策略"""
|
||||
super().__init__(name, params)
|
||||
|
||||
# 策略参数
|
||||
self.short_ma = self.get_parameter('short_ma', 5)
|
||||
self.long_ma = self.get_parameter('long_ma', 20)
|
||||
self.position_size = self.get_parameter('position_size', 0.3)
|
||||
|
||||
# 时间周期配置
|
||||
self.timeframes = ['15m', '30m', '60m']
|
||||
|
||||
# 移动平均线计算器
|
||||
self.ma_calculator = SimpleMovingAverage()
|
||||
|
||||
# 股票分数系统
|
||||
self.stock_scores = {}
|
||||
self.previous_scores = {}
|
||||
self.ma_states = {}
|
||||
|
||||
self.log_info("多时间周期均线交叉策略初始化完成")
|
||||
self.log_info(f"短期均线: {self.short_ma}日, 长期均线: {self.long_ma}日")
|
||||
self.log_info(f"监控时间周期: {self.timeframes}")
|
||||
|
||||
def initialize(self):
|
||||
"""策略初始化"""
|
||||
self.log_info("策略初始化完成")
|
||||
|
||||
def on_data(self, data: pd.DataFrame, timestamp: datetime):
|
||||
"""处理新的数据"""
|
||||
try:
|
||||
if 'symbol' in data.columns and not data.empty:
|
||||
symbol = data['symbol'].iloc[0]
|
||||
|
||||
bar_data = {
|
||||
'symbol': symbol,
|
||||
'datetime': timestamp,
|
||||
'close': data['close'].iloc[-1]
|
||||
}
|
||||
|
||||
signals = self.process_bar(bar_data)
|
||||
|
||||
for signal_data in signals:
|
||||
self.generate_signal(
|
||||
timestamp=signal_data['timestamp'],
|
||||
stock_code=signal_data['symbol'],
|
||||
action=signal_data['action'],
|
||||
strength=1.0,
|
||||
reason=signal_data['reason']
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.log_error(f"处理数据失败: {e}")
|
||||
|
||||
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] = {}
|
||||
|
||||
for timeframe in self.timeframes:
|
||||
self.ma_states[symbol][timeframe] = {
|
||||
'short_ma': [],
|
||||
'long_ma': [],
|
||||
'last_cross': None
|
||||
}
|
||||
|
||||
def detect_ma_crossover(self, short_ma: List[float], long_ma: List[float]) -> Optional[str]:
|
||||
"""检测均线金叉死叉"""
|
||||
if len(short_ma) < 2 or len(long_ma) < 2:
|
||||
return None
|
||||
|
||||
# 检查数据有效性
|
||||
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:
|
||||
"""加载指定时间周期的历史数据"""
|
||||
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.timestamp <= current_time)
|
||||
.order_by(KlineModel.timestamp.desc())
|
||||
.limit(periods_needed))
|
||||
|
||||
data = []
|
||||
for record in query:
|
||||
data.append({
|
||||
'datetime': record.timestamp,
|
||||
'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]:
|
||||
"""更新各时间周期的均线分析"""
|
||||
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.ma_calculator.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}']
|
||||
|
||||
# 转换为列表并过滤NaN值
|
||||
short_ma_values = short_ma_series.dropna().tolist()
|
||||
long_ma_values = long_ma_series.dropna().tolist()
|
||||
|
||||
if len(short_ma_values) < 2 or len(long_ma_values) < 2:
|
||||
continue
|
||||
|
||||
# 检测交叉
|
||||
crossover = self.detect_ma_crossover(short_ma_values, long_ma_values)
|
||||
|
||||
if crossover:
|
||||
crossovers[timeframe] = crossover
|
||||
cross_type = "金叉" if crossover == 'golden' else "死叉"
|
||||
logger.info(f"[{symbol}] {timeframe} 检测到{cross_type}: "
|
||||
f"短期MA={short_ma_values[-1]:.3f}, 长期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]:
|
||||
"""更新股票分数"""
|
||||
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[Dict[str, Any]]:
|
||||
"""处理新的K线数据"""
|
||||
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:
|
||||
signal_data = {
|
||||
'symbol': symbol,
|
||||
'action': 'BUY',
|
||||
'price': current_price,
|
||||
'timestamp': current_time,
|
||||
'reason': f"多时间周期金叉,分数: {previous_score}->{new_score}"
|
||||
}
|
||||
signals.append(signal_data)
|
||||
logger.info(f"[{symbol}] 买入信号: 分数{previous_score}->{new_score}, 价格: {current_price}")
|
||||
|
||||
elif previous_score == 1 and new_score == 0:
|
||||
signal_data = {
|
||||
'symbol': symbol,
|
||||
'action': 'SELL',
|
||||
'price': current_price,
|
||||
'timestamp': current_time,
|
||||
'reason': f"多时间周期死叉,分数: {previous_score}->{new_score}"
|
||||
}
|
||||
signals.append(signal_data)
|
||||
logger.info(f"[{symbol}] 卖出信号: 分数{previous_score}->{new_score}, 价格: {current_price}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理{symbol}数据失败: {e}")
|
||||
|
||||
return signals
|
||||
|
||||
def get_strategy_info(self) -> Dict[str, Any]:
|
||||
"""获取策略信息"""
|
||||
return {
|
||||
'name': 'MultiTimeFrameMAStrategy',
|
||||
'description': '多时间周期均线交叉策略(无TA-Lib)',
|
||||
'timeframes': self.timeframes,
|
||||
'short_ma': self.short_ma,
|
||||
'long_ma': self.long_ma,
|
||||
'current_scores': self.stock_scores.copy()
|
||||
}
|
||||
|
||||
|
||||
def create_multi_timeframe_strategy(params: Optional[Dict[str, Any]] = None) -> MultiTimeFrameMAStrategy:
|
||||
"""创建多时间周期均线交叉策略实例"""
|
||||
if params is None:
|
||||
params = {
|
||||
'short_ma': 5,
|
||||
'long_ma': 20,
|
||||
'position_size': 0.3
|
||||
}
|
||||
|
||||
return MultiTimeFrameMAStrategy("MultiTimeFrameMA", params)
|
||||
|
||||
|
||||
def test_multi_timeframe_strategy():
|
||||
"""测试多时间周期策略"""
|
||||
print("🧪 测试多时间周期均线交叉策略 (无TA-Lib版本)")
|
||||
|
||||
try:
|
||||
# 初始化数据库
|
||||
if not init_database():
|
||||
print("❌ 数据库连接失败")
|
||||
return False
|
||||
|
||||
# 创建策略实例
|
||||
strategy = create_multi_timeframe_strategy()
|
||||
print("✅ 策略实例创建成功")
|
||||
|
||||
# 测试数据
|
||||
test_data = {
|
||||
'symbol': '601398.SH',
|
||||
'datetime': datetime(2024, 8, 1, 10, 0, 0),
|
||||
'close': 5.05
|
||||
}
|
||||
|
||||
print("📊 处理测试数据...")
|
||||
signals = strategy.process_bar(test_data)
|
||||
|
||||
print(f"✅ 处理完成,生成{len(signals)}个信号")
|
||||
for signal in signals:
|
||||
print(f" 信号: {signal['action']} {signal['symbol']} @ {signal['price']}")
|
||||
|
||||
# 显示策略信息
|
||||
info = strategy.get_strategy_info()
|
||||
print(f"\n📋 策略信息: {info['name']}")
|
||||
print(f" 描述: {info['description']}")
|
||||
print(f" 时间周期: {info['timeframes']}")
|
||||
print(f" 短期均线: {info['short_ma']}日")
|
||||
print(f" 长期均线: {info['long_ma']}日")
|
||||
print(f" 当前分数: {info['current_scores']}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_multi_timeframe_strategy()
|
||||
@ -1,393 +0,0 @@
|
||||
"""
|
||||
多时间周期均线交叉策略 v2.0
|
||||
|
||||
基于15分钟、30分钟、60分钟三个时间周期的均线金叉/死叉信号:
|
||||
- 每个时间周期发生金叉时,股票分数+1
|
||||
- 每个时间周期发生死叉时,股票分数-1
|
||||
- 分数从0变为1时,发出买入信号
|
||||
- 分数从1变为0时,发出卖出信号
|
||||
- 分数 # 查询数据
|
||||
query = (KlineModel.select()
|
||||
.where(KlineModel.timestamp <= current_time)
|
||||
.order_by(KlineModel.timestamp.desc())
|
||||
.limit(periods_needed))
|
||||
|
||||
data = []
|
||||
for record in query:
|
||||
data.append({
|
||||
'datetime': record.timestamp,
|
||||
'open': float(record.open),
|
||||
'high': float(record.high),
|
||||
'low': float(record.low),
|
||||
'close': float(record.close),
|
||||
'volume': int(record.volume)
|
||||
})
|
||||
|
||||
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
|
||||
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):
|
||||
"""
|
||||
多时间周期均线交叉策略
|
||||
|
||||
基于多个时间周期的均线交叉进行评分,分数变化触发交易信号
|
||||
"""
|
||||
|
||||
def __init__(self, name: str = "MultiTimeFrameMA", params: Optional[Dict[str, Any]] = None):
|
||||
"""初始化策略"""
|
||||
super().__init__(name, params)
|
||||
|
||||
# 策略参数
|
||||
self.short_ma = self.get_parameter('short_ma', 5)
|
||||
self.long_ma = self.get_parameter('long_ma', 20)
|
||||
self.position_size = self.get_parameter('position_size', 0.5)
|
||||
self.stop_loss = self.get_parameter('stop_loss', 0.05)
|
||||
self.take_profit = self.get_parameter('take_profit', 0.10)
|
||||
|
||||
# 时间周期配置
|
||||
self.timeframes = ['15m', '30m', '60m']
|
||||
|
||||
# 技术指标计算器
|
||||
self.indicators = TechnicalIndicators()
|
||||
|
||||
# 股票分数系统
|
||||
self.stock_scores = {} # {symbol: score}
|
||||
self.previous_scores = {} # 记录上一次的分数
|
||||
|
||||
# 各时间周期的均线状态
|
||||
self.ma_states = {}
|
||||
|
||||
self.log_info("多时间周期均线交叉策略初始化完成")
|
||||
self.log_info(f"短期均线: {self.short_ma}日, 长期均线: {self.long_ma}日")
|
||||
self.log_info(f"监控时间周期: {self.timeframes}")
|
||||
|
||||
def initialize(self):
|
||||
"""策略初始化"""
|
||||
self.log_info("策略初始化完成")
|
||||
|
||||
def on_data(self, data: pd.DataFrame, timestamp: datetime):
|
||||
"""处理新的数据"""
|
||||
try:
|
||||
# 假设数据包含symbol列,取第一个股票
|
||||
if 'symbol' in data.columns and not data.empty:
|
||||
symbol = data['symbol'].iloc[0]
|
||||
|
||||
# 构造数据字典
|
||||
bar_data = {
|
||||
'symbol': symbol,
|
||||
'datetime': timestamp,
|
||||
'open': data['open'].iloc[-1],
|
||||
'high': data['high'].iloc[-1],
|
||||
'low': data['low'].iloc[-1],
|
||||
'close': data['close'].iloc[-1],
|
||||
'volume': data['volume'].iloc[-1]
|
||||
}
|
||||
|
||||
# 处理数据并生成信号
|
||||
signals = self.process_bar(bar_data)
|
||||
|
||||
# 将信号转换为标准格式
|
||||
for signal_data in signals:
|
||||
self.generate_signal(
|
||||
timestamp=signal_data['timestamp'],
|
||||
stock_code=signal_data['symbol'],
|
||||
action=signal_data['action'],
|
||||
strength=1.0,
|
||||
reason=signal_data['reason']
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
self.log_error(f"处理数据失败: {e}")
|
||||
|
||||
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] = {}
|
||||
|
||||
for timeframe in self.timeframes:
|
||||
self.ma_states[symbol][timeframe] = {
|
||||
'short_ma': [],
|
||||
'long_ma': [],
|
||||
'last_cross': None
|
||||
}
|
||||
|
||||
def detect_ma_crossover(self, short_ma: List[float], long_ma: List[float]) -> Optional[str]:
|
||||
"""检测均线金叉死叉"""
|
||||
if len(short_ma) < 2 or len(long_ma) < 2:
|
||||
return None
|
||||
|
||||
# 检查数据有效性
|
||||
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:
|
||||
"""加载指定时间周期的历史数据"""
|
||||
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]:
|
||||
"""更新各时间周期的均线分析"""
|
||||
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
|
||||
cross_type = "金叉" if crossover == 'golden' else "死叉"
|
||||
logger.info(f"[{symbol}] {timeframe} 检测到{cross_type}: "
|
||||
f"短期MA={short_ma_values[-1]:.3f}, "
|
||||
f"长期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]:
|
||||
"""更新股票分数"""
|
||||
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[Dict[str, Any]]:
|
||||
"""处理新的K线数据,返回信号字典列表"""
|
||||
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_data = {
|
||||
'symbol': symbol,
|
||||
'action': 'BUY',
|
||||
'price': current_price,
|
||||
'timestamp': current_time,
|
||||
'reason': f"多时间周期金叉,分数: {previous_score}->{new_score}"
|
||||
}
|
||||
signals.append(signal_data)
|
||||
logger.info(f"[{symbol}] 买入信号: 分数{previous_score}->{new_score}, 价格: {current_price}")
|
||||
|
||||
elif previous_score == 1 and new_score == 0:
|
||||
# 分数从1变为0,发出卖出信号
|
||||
signal_data = {
|
||||
'symbol': symbol,
|
||||
'action': 'SELL',
|
||||
'price': current_price,
|
||||
'timestamp': current_time,
|
||||
'reason': f"多时间周期死叉,分数: {previous_score}->{new_score}"
|
||||
}
|
||||
signals.append(signal_data)
|
||||
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 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,
|
||||
'current_scores': self.stock_scores.copy()
|
||||
}
|
||||
|
||||
|
||||
def create_multi_timeframe_strategy(params: Optional[Dict[str, Any]] = None) -> MultiTimeFrameMAStrategy:
|
||||
"""创建多时间周期均线交叉策略实例"""
|
||||
if params is None:
|
||||
params = {
|
||||
'short_ma': 5,
|
||||
'long_ma': 20,
|
||||
'position_size': 0.3,
|
||||
'stop_loss': 0.05,
|
||||
'take_profit': 0.10
|
||||
}
|
||||
|
||||
return MultiTimeFrameMAStrategy("MultiTimeFrameMA", params)
|
||||
|
||||
|
||||
# 测试函数
|
||||
def test_multi_timeframe_strategy():
|
||||
"""测试多时间周期策略"""
|
||||
print("🧪 测试多时间周期均线交叉策略")
|
||||
|
||||
try:
|
||||
# 初始化数据库
|
||||
if not init_database():
|
||||
print("❌ 数据库连接失败")
|
||||
return False
|
||||
|
||||
# 创建策略实例
|
||||
strategy = create_multi_timeframe_strategy()
|
||||
print("✅ 策略实例创建成功")
|
||||
|
||||
# 测试数据
|
||||
test_data = {
|
||||
'symbol': '601398.SH',
|
||||
'datetime': datetime(2024, 8, 1, 10, 0, 0),
|
||||
'open': 5.0,
|
||||
'high': 5.1,
|
||||
'low': 4.9,
|
||||
'close': 5.05,
|
||||
'volume': 1000000
|
||||
}
|
||||
|
||||
# 处理测试数据
|
||||
print("📊 处理测试数据...")
|
||||
signals = strategy.process_bar(test_data)
|
||||
|
||||
print(f"✅ 处理完成,生成{len(signals)}个信号")
|
||||
for signal in signals:
|
||||
print(f" 信号: {signal['action']} {signal['symbol']} @ {signal['price']}")
|
||||
|
||||
# 显示策略信息
|
||||
info = strategy.get_strategy_info()
|
||||
print("\n📋 策略信息:")
|
||||
print(f" 名称: {info['name']}")
|
||||
print(f" 描述: {info['description']}")
|
||||
print(f" 时间周期: {info['timeframes']}")
|
||||
print(f" 当前分数: {info['current_scores']}")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_multi_timeframe_strategy()
|
||||
@ -34,6 +34,7 @@ class PerformanceReport:
|
||||
# 总体指标
|
||||
total_return: float
|
||||
annual_return: float
|
||||
benchmark_return: float # 基准收益(股票涨跌幅)
|
||||
max_drawdown: float
|
||||
max_drawdown_duration: int
|
||||
sharpe_ratio: float
|
||||
@ -76,7 +77,7 @@ class PerformanceAnalyzer:
|
||||
self.benchmark_values.append((timestamp, value))
|
||||
|
||||
def calculate_returns(self, values: List[Tuple[datetime, float]]) -> pd.Series:
|
||||
"""计算收益率序列"""
|
||||
"""计算日收益率序列"""
|
||||
if len(values) < 2:
|
||||
return pd.Series()
|
||||
|
||||
@ -84,8 +85,14 @@ class PerformanceAnalyzer:
|
||||
df.set_index('timestamp', inplace=True)
|
||||
df.sort_index(inplace=True)
|
||||
|
||||
# 按日重采样,取最后一个值
|
||||
daily_values = df.resample('D').last().dropna()
|
||||
|
||||
# 计算日收益率
|
||||
returns = df['value'].pct_change().dropna()
|
||||
if len(daily_values) < 2:
|
||||
return pd.Series()
|
||||
|
||||
returns = daily_values['value'].pct_change().dropna()
|
||||
return returns
|
||||
|
||||
def calculate_max_drawdown(self, values: List[Tuple[datetime, float]]) -> Tuple[float, int]:
|
||||
@ -111,16 +118,27 @@ class PerformanceAnalyzer:
|
||||
# 最大回撤
|
||||
max_drawdown = df['drawdown'].min()
|
||||
|
||||
# 计算最大回撤持续时间
|
||||
# 计算最大回撤持续时间(以天为单位)
|
||||
max_dd_duration = 0
|
||||
current_dd_duration = 0
|
||||
current_dd_start = None
|
||||
in_drawdown = False
|
||||
|
||||
for dd in df['drawdown']:
|
||||
if dd < 0:
|
||||
current_dd_duration += 1
|
||||
max_dd_duration = max(max_dd_duration, current_dd_duration)
|
||||
else:
|
||||
current_dd_duration = 0
|
||||
for timestamp, dd in zip(df.index, df['drawdown']):
|
||||
if dd < 0: # 处于回撤中
|
||||
if not in_drawdown: # 刚开始回撤
|
||||
current_dd_start = timestamp
|
||||
in_drawdown = True
|
||||
else: # 回撤结束
|
||||
if in_drawdown and current_dd_start is not None:
|
||||
# 计算回撤持续天数
|
||||
duration_days = (timestamp - current_dd_start).days
|
||||
max_dd_duration = max(max_dd_duration, duration_days)
|
||||
in_drawdown = False
|
||||
|
||||
# 处理回测结束时仍在回撤的情况
|
||||
if in_drawdown and current_dd_start is not None:
|
||||
duration_days = (df.index[-1] - current_dd_start).days
|
||||
max_dd_duration = max(max_dd_duration, duration_days)
|
||||
|
||||
return abs(max_drawdown), max_dd_duration
|
||||
|
||||
@ -287,6 +305,13 @@ class PerformanceAnalyzer:
|
||||
years = days / 365.25
|
||||
annual_return = (1 + total_return) ** (1 / years) - 1 if years > 0 else 0
|
||||
|
||||
# 计算基准收益(股票涨跌幅)
|
||||
benchmark_return = 0.0
|
||||
if len(self.benchmark_values) >= 2:
|
||||
initial_benchmark = self.benchmark_values[0][1]
|
||||
final_benchmark = self.benchmark_values[-1][1]
|
||||
benchmark_return = (final_benchmark - initial_benchmark) / initial_benchmark
|
||||
|
||||
# 计算最大回撤
|
||||
max_drawdown, max_dd_duration = self.calculate_max_drawdown(self.portfolio_values)
|
||||
|
||||
@ -309,6 +334,7 @@ class PerformanceAnalyzer:
|
||||
report = PerformanceReport(
|
||||
total_return=total_return,
|
||||
annual_return=annual_return,
|
||||
benchmark_return=benchmark_return,
|
||||
max_drawdown=max_drawdown,
|
||||
max_drawdown_duration=max_dd_duration,
|
||||
sharpe_ratio=sharpe_ratio,
|
||||
@ -336,6 +362,7 @@ class PerformanceAnalyzer:
|
||||
|
||||
print(f"\n📊 总体指标:")
|
||||
print(f"总收益率: {report.total_return*100:>8.2f}%")
|
||||
print(f"基准收益: {report.benchmark_return*100:>8.2f}%")
|
||||
print(f"年化收益率: {report.annual_return*100:>8.2f}%")
|
||||
print(f"最大回撤: {report.max_drawdown*100:>8.2f}%")
|
||||
print(f"回撤持续: {report.max_drawdown_duration:>8d} 天")
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
"""
|
||||
真实数据库回测脚本
|
||||
|
||||
使用真实数据库数据对601658.SH(邮储银行)进行回测
|
||||
回测期间:2025年1月1日 - 2025年7月31日
|
||||
使用真实数据库数据对300339.SZ进行回测
|
||||
回测期间:2025年3月1日 - 2025年7月31日
|
||||
使用修改后的多时间周期MA评分策略
|
||||
"""
|
||||
|
||||
@ -10,6 +10,12 @@ import sys
|
||||
import os
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
import matplotlib.dates as mdates
|
||||
from matplotlib.patches import FancyBboxPatch
|
||||
import numpy as np
|
||||
import glob
|
||||
|
||||
# 添加项目路径
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
@ -31,6 +37,245 @@ logging.basicConfig(
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def draw_kline_chart(engine, strategy, stock_code, save_path=None):
|
||||
"""
|
||||
绘制K线图,包含MA5、MA18均线和买卖点标注
|
||||
X轴使用连续索引,避免非交易日的空白
|
||||
|
||||
Args:
|
||||
engine: 回测引擎
|
||||
strategy: 交易策略
|
||||
stock_code: 股票代码
|
||||
save_path: 图片保存路径,默认为None表示显示而不保存
|
||||
"""
|
||||
try:
|
||||
print("\n🎨 绘制K线图...")
|
||||
|
||||
# 设置中文字体
|
||||
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei']
|
||||
plt.rcParams['axes.unicode_minus'] = False
|
||||
|
||||
# 获取日线数据
|
||||
from data_process_model.stock_models import create_stock_kline_model
|
||||
from data_process_model.database_config import init_database, close_database
|
||||
|
||||
init_database()
|
||||
daily_model = create_stock_kline_model(stock_code, "1d")
|
||||
|
||||
# 查询回测期间的日线数据
|
||||
start_date = engine.start_date.date()
|
||||
end_date = engine.end_date.date()
|
||||
|
||||
daily_data = daily_model.select().where(
|
||||
(daily_model.timestamp >= start_date) &
|
||||
(daily_model.timestamp <= end_date)
|
||||
).order_by(daily_model.timestamp)
|
||||
|
||||
# 转换为DataFrame
|
||||
df_data = []
|
||||
for record in daily_data:
|
||||
df_data.append({
|
||||
'date': record.timestamp,
|
||||
'open': record.open,
|
||||
'high': record.high,
|
||||
'low': record.low,
|
||||
'close': record.close,
|
||||
'volume': record.volume
|
||||
})
|
||||
|
||||
close_database()
|
||||
|
||||
if not df_data:
|
||||
print("❌ 没有找到日线数据")
|
||||
return
|
||||
|
||||
df = pd.DataFrame(df_data)
|
||||
df['date'] = pd.to_datetime(df['date'])
|
||||
|
||||
# 将Decimal类型的价格数据转换为float,避免类型混合运算错误
|
||||
numeric_cols = ['open', 'high', 'low', 'close']
|
||||
for col in numeric_cols:
|
||||
df[col] = pd.to_numeric(df[col], errors='coerce')
|
||||
|
||||
# 创建连续的索引,避免非交易日的空白
|
||||
df['index'] = range(len(df))
|
||||
|
||||
# 计算MA5和MA18
|
||||
df['ma5'] = df['close'].rolling(window=5).mean()
|
||||
df['ma18'] = df['close'].rolling(window=18).mean()
|
||||
|
||||
# 获取交易记录
|
||||
trades = engine.portfolio.trades
|
||||
buy_trades = []
|
||||
sell_trades = []
|
||||
|
||||
for trade in trades:
|
||||
if hasattr(trade, 'timestamp') and trade.timestamp:
|
||||
trade_date = trade.timestamp.date()
|
||||
# 查找对应的索引
|
||||
matching_rows = df[df['date'].dt.date == trade_date]
|
||||
if not matching_rows.empty:
|
||||
index = matching_rows.iloc[0]['index']
|
||||
if trade.action in ['BUY', 'BUY_ALL']:
|
||||
buy_trades.append({'index': index, 'date': trade_date, 'price': trade.price})
|
||||
elif trade.action in ['SELL', 'SELL_ALL']:
|
||||
sell_trades.append({'index': index, 'date': trade_date, 'price': trade.price})
|
||||
|
||||
# 创建图形
|
||||
fig, ax = plt.subplots(figsize=(16, 10))
|
||||
|
||||
# 绘制K线 - 使用索引作为X轴
|
||||
for i, row in df.iterrows():
|
||||
x_pos = row['index']
|
||||
open_price = row['open']
|
||||
high_price = row['high']
|
||||
low_price = row['low']
|
||||
close_price = row['close']
|
||||
|
||||
# 确定K线颜色(红涨绿跌)
|
||||
color = 'red' if close_price >= open_price else 'green'
|
||||
edge_color = 'red' if close_price >= open_price else 'green'
|
||||
face_color = 'white' if close_price >= open_price else 'green'
|
||||
|
||||
# 绘制影线
|
||||
ax.plot([x_pos, x_pos], [low_price, high_price], color='black', linewidth=0.8)
|
||||
|
||||
# 绘制实体
|
||||
body_height = abs(close_price - open_price)
|
||||
if body_height > 0:
|
||||
body_bottom = min(open_price, close_price)
|
||||
rect = plt.Rectangle((x_pos - 0.3, body_bottom),
|
||||
0.6, body_height,
|
||||
facecolor=face_color, edgecolor=edge_color, linewidth=0.8)
|
||||
ax.add_patch(rect)
|
||||
else:
|
||||
# 十字星
|
||||
ax.plot([x_pos - 0.3, x_pos + 0.3],
|
||||
[close_price, close_price], color='black', linewidth=1)
|
||||
|
||||
# 绘制MA5和MA18 - 使用索引作为X轴
|
||||
valid_ma5_mask = ~df['ma5'].isna()
|
||||
if valid_ma5_mask.any():
|
||||
ma5_x = df.loc[valid_ma5_mask, 'index']
|
||||
ma5_y = df.loc[valid_ma5_mask, 'ma5']
|
||||
ax.plot(ma5_x, ma5_y, label='MA5', color='blue', linewidth=1.5, alpha=0.8)
|
||||
|
||||
valid_ma18_mask = ~df['ma18'].isna()
|
||||
if valid_ma18_mask.any():
|
||||
ma18_x = df.loc[valid_ma18_mask, 'index']
|
||||
ma18_y = df.loc[valid_ma18_mask, 'ma18']
|
||||
ax.plot(ma18_x, ma18_y, label='MA18', color='orange', linewidth=1.5, alpha=0.8)
|
||||
|
||||
# 标注买卖点 - 使用索引位置
|
||||
for i, trade in enumerate(buy_trades):
|
||||
x_pos = trade['index']
|
||||
# 获取对应K线的高价
|
||||
row = df[df['index'] == x_pos].iloc[0]
|
||||
bar_high = row['high']
|
||||
|
||||
# 添加图例标记(仅第一个点)
|
||||
if i == 0:
|
||||
ax.scatter([], [], color='red', s=0, marker='s', label='买入', alpha=0)
|
||||
|
||||
# 价格标注框位置在K线上方
|
||||
text_y_offset = (ax.get_ylim()[1] - ax.get_ylim()[0]) * 0.08 # 相对于价格范围的8%
|
||||
|
||||
# 标注买入价格,箭头指向K线
|
||||
ax.annotate(f'买入: {trade["price"]:.2f}',
|
||||
xy=(x_pos, bar_high), # 箭头指向K线最高点
|
||||
xytext=(x_pos, bar_high + text_y_offset), # 文字框位置
|
||||
fontsize=9, ha='center', va='bottom', color='red', weight='bold',
|
||||
bbox=dict(boxstyle='round,pad=0.3', facecolor='white',
|
||||
edgecolor='red', alpha=0.95, linewidth=1.5),
|
||||
arrowprops=dict(arrowstyle='->', lw=1.2, color='red', alpha=0.8))
|
||||
|
||||
for i, trade in enumerate(sell_trades):
|
||||
x_pos = trade['index']
|
||||
# 获取对应K线的低价
|
||||
row = df[df['index'] == x_pos].iloc[0]
|
||||
bar_low = row['low']
|
||||
|
||||
# 添加图例标记(仅第一个点)
|
||||
if i == 0:
|
||||
ax.scatter([], [], color='green', s=0, marker='s', label='卖出', alpha=0)
|
||||
|
||||
# 价格标注框位置在K线下方
|
||||
text_y_offset = (ax.get_ylim()[1] - ax.get_ylim()[0]) * 0.08 # 相对于价格范围的8%
|
||||
|
||||
# 标注卖出价格,箭头指向K线
|
||||
ax.annotate(f'卖出: {trade["price"]:.2f}',
|
||||
xy=(x_pos, bar_low), # 箭头指向K线最低点
|
||||
xytext=(x_pos, bar_low - text_y_offset), # 文字框位置
|
||||
fontsize=9, ha='center', va='top', color='green', weight='bold',
|
||||
bbox=dict(boxstyle='round,pad=0.3', facecolor='white',
|
||||
edgecolor='green', alpha=0.95, linewidth=1.5),
|
||||
arrowprops=dict(arrowstyle='->', lw=1.2, color='green', alpha=0.8))
|
||||
|
||||
# 设置图形属性
|
||||
ax.set_title(f'{stock_code}日线K线图 - 多时间周期MA策略回测\n'
|
||||
f'回测期间: {start_date} ~ {end_date}', fontsize=16, pad=20)
|
||||
ax.set_xlabel('交易日期', fontsize=12)
|
||||
ax.set_ylabel('价格 (元)', fontsize=12)
|
||||
|
||||
# 设置X轴刻度 - 显示实际日期但使用连续索引
|
||||
# 每隔一定间隔显示日期
|
||||
n_ticks = min(10, len(df)) # 最多显示10个日期刻度
|
||||
if len(df) > 0:
|
||||
step = max(1, len(df) // n_ticks)
|
||||
tick_positions = range(0, len(df), step)
|
||||
tick_labels = [df.iloc[i]['date'].strftime('%m-%d') for i in tick_positions if i < len(df)]
|
||||
|
||||
ax.set_xticks(tick_positions)
|
||||
ax.set_xticklabels(tick_labels, rotation=45)
|
||||
|
||||
# 设置X轴范围
|
||||
ax.set_xlim(-1, len(df))
|
||||
|
||||
# 添加网格
|
||||
ax.grid(True, alpha=0.3)
|
||||
|
||||
# 添加图例
|
||||
ax.legend(loc='upper left', fontsize=10)
|
||||
|
||||
# 紧凑布局
|
||||
plt.tight_layout()
|
||||
|
||||
# 保存或显示
|
||||
if save_path:
|
||||
# 清理同名的旧图片
|
||||
if os.path.exists(save_path):
|
||||
os.remove(save_path)
|
||||
plt.savefig(save_path, dpi=300, bbox_inches='tight')
|
||||
print(f"✅ K线图已保存到: {save_path}")
|
||||
else:
|
||||
# 获取当前脚本所在目录(back_trader目录)
|
||||
script_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
|
||||
# 清理旧的K线图文件
|
||||
pattern = os.path.join(script_dir, f"kline_chart_{stock_code}_*.png")
|
||||
old_files = glob.glob(pattern)
|
||||
for old_file in old_files:
|
||||
try:
|
||||
os.remove(old_file)
|
||||
except:
|
||||
pass # 忽略删除失败的情况
|
||||
|
||||
# 生成默认文件名,保存到back_trader目录
|
||||
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
|
||||
filename = os.path.join(script_dir, f"kline_chart_{stock_code}_{timestamp}.png")
|
||||
plt.savefig(filename, dpi=300, bbox_inches='tight')
|
||||
print(f"✅ K线图已保存到: {filename}")
|
||||
|
||||
# plt.show() # 注释掉显示,只保存文件
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ K线图绘制失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
finally:
|
||||
plt.close('all') # 关闭所有图形
|
||||
|
||||
|
||||
def progress_callback(current, total, message):
|
||||
"""进度回调函数 - 每5%输出一次"""
|
||||
progress = (current / total) * 100
|
||||
@ -49,11 +294,35 @@ def run_real_backtest():
|
||||
try:
|
||||
print("🚀 启动真实数据库回测")
|
||||
print("="*60)
|
||||
print("📊 测试股票: 601658.SH (邮储银行)")
|
||||
print("📊 测试股票: 300339.SZ")
|
||||
print("📅 回测期间: 2025-01-01 ~ 2025-07-31")
|
||||
print("🎯 策略: 多时间周期MA评分策略(修正版)")
|
||||
print("="*60)
|
||||
|
||||
# 回测配置参数
|
||||
# =====================================
|
||||
STOCK_CODE = "300339.SZ" # 股票代码
|
||||
INITIAL_CAPITAL = 100000 # 初始资金
|
||||
START_DATE = "2025-03-01 09:00" # 回测开始时间
|
||||
END_DATE = "2025-07-31 15:00" # 回测结束时间
|
||||
|
||||
# 止盈设置说明:
|
||||
# None - 不设置止盈(默认)
|
||||
# 0.03 - 3%止盈
|
||||
# 0.05 - 5%止盈
|
||||
# 0.08 - 8%止盈
|
||||
# 0.10 - 10%止盈
|
||||
PROFIT_TARGET = None # 止盈阈值(默认无止盈)
|
||||
|
||||
# 买入条件系数说明:
|
||||
# 股价 > buy_low_ratio * 日K5日均线 时可买入
|
||||
# 0.95 - 95%日K5日线
|
||||
# 0.99 - 99%日K5日线(默认)
|
||||
# 1.00 - 100%日K5日线(原策略)
|
||||
# 1.02 - 102%日K5日线
|
||||
BUY_LOW_RATIO = 0.99 # 买入条件系数(默认0.99)
|
||||
# =====================================
|
||||
|
||||
# 1. 检查数据库连接
|
||||
print("\n1️⃣ 检查数据库连接...")
|
||||
try:
|
||||
@ -82,21 +351,25 @@ def run_real_backtest():
|
||||
|
||||
# 3. 创建回测引擎
|
||||
print("\n3️⃣ 创建回测引擎...")
|
||||
engine = BacktestEngine(initial_capital=100000.0)
|
||||
print(f"✅ 回测引擎创建成功,初始资金: {engine.initial_capital:,.2f} 元")
|
||||
engine = BacktestEngine(initial_capital=INITIAL_CAPITAL)
|
||||
print(f"✅ 回测引擎创建成功,初始资金: {INITIAL_CAPITAL:,.2f} 元")
|
||||
|
||||
# 4. 设置回测参数
|
||||
print("\n4️⃣ 设置回测参数...")
|
||||
stock_codes = ["601658.SH"] # 邮储银行
|
||||
engine.set_universe(stock_codes)
|
||||
engine.set_period("2025-01-01", "2025-07-31", "1m")
|
||||
print(f"✅ 股票池: {stock_codes}")
|
||||
print("✅ 回测期间: 2025-01-01 ~ 2025-07-31")
|
||||
print("✅ 数据周期: 分钟线(1m)")
|
||||
engine.set_universe([STOCK_CODE])
|
||||
engine.set_period(START_DATE.split()[0], END_DATE.split()[0], "1m")
|
||||
print(f"✅ 股票池: ['{STOCK_CODE}']")
|
||||
print(f"✅ 回测期间: {START_DATE.split()[0]} ~ {END_DATE.split()[0]}")
|
||||
print(f"✅ 数据周期: 分钟线(1m)")
|
||||
|
||||
# 5. 创建多时间周期MA回测策略
|
||||
print("\n5️⃣ 创建交易策略...")
|
||||
strategy = MultiTimeframeMABacktestStrategy(stock_code="601658.SH")
|
||||
# 使用配置的参数:止盈和买入条件系数
|
||||
strategy = MultiTimeframeMABacktestStrategy(
|
||||
stock_code=STOCK_CODE,
|
||||
profit_target=PROFIT_TARGET,
|
||||
buy_low_ratio=BUY_LOW_RATIO
|
||||
)
|
||||
engine.set_strategy(strategy)
|
||||
|
||||
print(f"✅ 策略创建成功: {strategy.name}")
|
||||
@ -115,16 +388,18 @@ def run_real_backtest():
|
||||
print(f" - 策略名称: 多时间周期MA回测策略(最新优化版)")
|
||||
print(f" - 移动平均线: MA5 和 MA18")
|
||||
print(f" - 交叉判定: 无阈值限制(只要发生交叉就产生信号)")
|
||||
print(f" - 监听策略: 同时监听15分钟、30分钟、60分钟周期")
|
||||
print(f" - 回测数据周期: 1分钟")
|
||||
print(f" - 检查频率: 每15分钟一次")
|
||||
print(f" - 买入检查: 每5分钟一次")
|
||||
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" * 起始分数: 0分")
|
||||
print(f" * 15/30/60分钟金叉: +1分,死叉: -1分(分数最低为0)")
|
||||
print(f" * 买入条件: 15分钟持续金叉且股价>日K5日线且分数>0时全仓买入")
|
||||
print(f" * 卖出条件: 分数≤0时清仓卖出")
|
||||
print(f" * T+1限制: 当天买入的股票不能卖出")
|
||||
if strategy.profit_target is not None:
|
||||
print(f" * 止盈机制: 达到{strategy.profit_target*100:.1f}%止盈点时清仓并置0分")
|
||||
else:
|
||||
print(f" * 止盈机制: 无止盈设置")
|
||||
print(f" - 📊 已启用信号记录功能")
|
||||
|
||||
# 6. 加载历史数据
|
||||
@ -134,7 +409,7 @@ def run_real_backtest():
|
||||
print(" 请确认:")
|
||||
print(" - 数据库中存在对应的股票数据表")
|
||||
print(" - 数据时间范围覆盖回测期间")
|
||||
print(" - 股票代码格式正确(601658.SH)")
|
||||
print(" - 股票代码格式正确(300339.SZ)")
|
||||
return False
|
||||
|
||||
print("✅ 历史数据加载成功")
|
||||
@ -143,21 +418,35 @@ 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)
|
||||
# 临时调整日志级别,屏蔽详细日志,只显示进度
|
||||
import logging
|
||||
original_levels = {}
|
||||
loggers_to_silence = [
|
||||
'src.back_trader.backtest_engine',
|
||||
'src.back_trader.multi_timeframe_ma_backtest_strategy',
|
||||
'data_process_model.database_config',
|
||||
'data_process_model.stock_models',
|
||||
'peewee' # 数据库ORM日志
|
||||
]
|
||||
|
||||
for logger_name in loggers_to_silence:
|
||||
logger = logging.getLogger(logger_name)
|
||||
original_levels[logger_name] = logger.level
|
||||
logger.setLevel(logging.CRITICAL) # 只显示严重错误
|
||||
|
||||
# 设置根日志级别
|
||||
root_logger = logging.getLogger()
|
||||
original_root_level = root_logger.level
|
||||
root_logger.setLevel(logging.CRITICAL)
|
||||
|
||||
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)
|
||||
for logger_name, original_level in original_levels.items():
|
||||
logging.getLogger(logger_name).setLevel(original_level)
|
||||
root_logger.setLevel(original_root_level)
|
||||
|
||||
duration = (end_time - start_time).total_seconds()
|
||||
|
||||
@ -169,14 +458,14 @@ def run_real_backtest():
|
||||
print("="*60)
|
||||
engine.print_summary()
|
||||
|
||||
# 9. 保存详细结果
|
||||
print("\n9️⃣ 保存回测结果...")
|
||||
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}")
|
||||
# 9. 保存详细结果 (暂时禁用JSON输出)
|
||||
# print("\n9️⃣ 保存回测结果...")
|
||||
# result_file = f"backtest_601288_SH_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
|
||||
# if engine.save_results(result_file):
|
||||
# print(f"✅ 详细结果已保存到: {result_file}")
|
||||
|
||||
# 10. 显示投资组合最终状态
|
||||
print("\n🔟 投资组合最终状态:")
|
||||
# 9. 显示投资组合最终状态
|
||||
print("\n9️⃣ 投资组合最终状态:")
|
||||
print(f" 现金余额: {engine.portfolio.cash:,.2f} 元")
|
||||
print(f" 总资产: {engine.portfolio.total_value:,.2f} 元")
|
||||
total_return = ((engine.portfolio.total_value - 100000) / 100000) * 100
|
||||
@ -308,6 +597,15 @@ def run_real_backtest():
|
||||
|
||||
print("="*120)
|
||||
|
||||
# 10. 绘制K线图
|
||||
print("\n🔟 绘制K线图...")
|
||||
try:
|
||||
# 直接使用已知的股票代码
|
||||
target_stock = STOCK_CODE # 使用配置的股票代码
|
||||
draw_kline_chart(engine, strategy, target_stock)
|
||||
except Exception as e:
|
||||
print(f"❌ K线图绘制过程出错: {e}")
|
||||
|
||||
return True
|
||||
|
||||
else:
|
||||
@ -341,13 +639,14 @@ def check_data_availability():
|
||||
print("❌ 无法连接数据库")
|
||||
return False
|
||||
|
||||
# 检查是否存在601658.SH的分钟数据
|
||||
# 检查是否存在配置股票的分钟数据
|
||||
stock_code = "300339.SZ" # 配置的股票代码
|
||||
try:
|
||||
model_class = create_stock_kline_model("601658.SH", "1m")
|
||||
model_class = create_stock_kline_model(stock_code, "1m")
|
||||
|
||||
# 检查表是否存在数据
|
||||
count = model_class.select().count()
|
||||
print(f"✅ 找到 601658.SH 分钟数据: {count} 条记录")
|
||||
print(f"✅ 找到 {stock_code} 分钟数据: {count} 条记录")
|
||||
|
||||
if count == 0:
|
||||
print("⚠️ 数据表为空,请先运行数据下载脚本")
|
||||
@ -391,14 +690,14 @@ def check_data_availability():
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("🏦 邮储银行(601658.SH)真实数据回测")
|
||||
print("📈 300339.SZ真实数据回测")
|
||||
print("="*60)
|
||||
|
||||
# 首先检查数据可用性
|
||||
if not check_data_availability():
|
||||
print("\n💡 建议操作:")
|
||||
print("1. 确认已运行数据下载脚本 (data_process_model/main.py)")
|
||||
print("2. 确认数据库中存在 601658.SH 的历史数据")
|
||||
print("2. 确认数据库中存在 300339.SZ 的历史数据")
|
||||
print("3. 确认数据时间范围覆盖 2025年1-7月")
|
||||
return
|
||||
|
||||
@ -407,7 +706,7 @@ def main():
|
||||
|
||||
if success:
|
||||
print("\n🎉 回测完成!")
|
||||
print(" 可以查看生成的 JSON 文件获取详细结果")
|
||||
# print(" 可以查看生成的 JSON 文件获取详细结果") # 暂时禁用JSON输出提示
|
||||
else:
|
||||
print("\n😞 回测失败,请检查错误信息")
|
||||
|
||||
|
||||
@ -1,162 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
多时间周期评分策略回测
|
||||
使用多时间周期均线交叉评分策略进行回测
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# 添加项目路径
|
||||
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.append(project_root)
|
||||
|
||||
try:
|
||||
from backtest_engine import BacktestEngine
|
||||
from multi_timeframe_ma_score_strategy import MultiTimeframeMAScoreStrategy
|
||||
from data_process_model.database_config import init_database
|
||||
except ImportError as e:
|
||||
print(f"导入错误: {e}")
|
||||
sys.exit(1)
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(
|
||||
level=logging.WARNING, # 只显示WARNING及以上级别的日志
|
||||
format='%(asctime)s - %(levelname)s:%(name)s:%(message)s',
|
||||
handlers=[
|
||||
logging.FileHandler('multi_timeframe_score_backtest.log', encoding='utf-8'),
|
||||
logging.StreamHandler()
|
||||
]
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# 设置特定模块的日志级别
|
||||
logging.getLogger('data_process_model.stock_models').setLevel(logging.CRITICAL) # 关闭模型创建日志
|
||||
logging.getLogger('data_process_model.database_config').setLevel(logging.WARNING) # 减少数据库连接日志
|
||||
logging.getLogger('multi_timeframe_ma_score_strategy').setLevel(logging.INFO)
|
||||
logging.getLogger('backtest_engine').setLevel(logging.WARNING) # 减少回测引擎日志
|
||||
|
||||
def run_multi_timeframe_score_backtest():
|
||||
"""运行多时间周期评分策略回测"""
|
||||
|
||||
print("🚀 开始多时间周期评分策略回测...")
|
||||
|
||||
try:
|
||||
# 初始化数据库
|
||||
init_database()
|
||||
logger.info("✅ 数据库连接成功")
|
||||
|
||||
# 创建回测引擎
|
||||
engine = BacktestEngine(initial_capital=1000000.0)
|
||||
|
||||
# 设置回测参数
|
||||
engine.set_universe(["601398.SH"]) # 测试股票
|
||||
engine.set_period("2024-01-01", "2024-12-31", "1m") # 回测时间范围:全年分钟数据
|
||||
|
||||
print(f"📊 回测配置:")
|
||||
print(f" 开始日期: 2024-01-01")
|
||||
print(f" 结束日期: 2024-12-31")
|
||||
print(f" 数据周期: 分钟级数据")
|
||||
print(f" 初始资金: 1,000,000元")
|
||||
print(f" 测试股票: ['601398.SH']")
|
||||
print(f" 手续费率: 默认")
|
||||
|
||||
# 创建策略实例
|
||||
strategy = MultiTimeframeMAScoreStrategy()
|
||||
|
||||
print(f"📈 策略配置:")
|
||||
print(f" 策略名称: {strategy.name}")
|
||||
print(f" 策略描述: {strategy.description}")
|
||||
print(f" 均线周期: {strategy.ma_periods}")
|
||||
print(f" 监控周期: {strategy.timeframes}")
|
||||
|
||||
# 设置策略
|
||||
engine.set_strategy(strategy)
|
||||
|
||||
print("\n" + "="*60)
|
||||
print("🔥 开始数据加载...")
|
||||
|
||||
# 加载历史数据
|
||||
if not engine.load_data_from_database():
|
||||
print("❌ 数据加载失败")
|
||||
return
|
||||
|
||||
print("✅ 数据加载完成")
|
||||
print("🔥 开始回测执行...")
|
||||
|
||||
# 运行回测
|
||||
success = engine.run_backtest()
|
||||
|
||||
print("="*60)
|
||||
if success:
|
||||
print("📊 回测完成,结果分析:")
|
||||
|
||||
# 获取投资组合信息
|
||||
portfolio = engine.portfolio
|
||||
performance = engine.performance_analyzer
|
||||
|
||||
print(f"\n💰 资金变化:")
|
||||
print(f" 初始资金: {engine.initial_capital:,.2f}元")
|
||||
print(f" 最终价值: {portfolio.get_total_value():,.2f}元")
|
||||
total_return = portfolio.get_total_value() - engine.initial_capital
|
||||
return_rate = portfolio.get_return_rate()
|
||||
print(f" 总收益: {total_return:,.2f}元")
|
||||
print(f" 收益率: {return_rate*100:.2f}%")
|
||||
|
||||
print(f"\n📈 交易统计:")
|
||||
trades = portfolio.trades
|
||||
print(f" 总交易次数: {len(trades)}次")
|
||||
|
||||
# 计算盈利亏损交易
|
||||
winning_trades = 0
|
||||
losing_trades = 0
|
||||
for i in range(1, len(trades), 2): # 买卖成对
|
||||
if i < len(trades):
|
||||
buy_trade = trades[i-1]
|
||||
sell_trade = trades[i]
|
||||
if sell_trade.action == 'SELL' and buy_trade.action == 'BUY':
|
||||
profit = (sell_trade.price - buy_trade.price) * buy_trade.shares
|
||||
if profit > 0:
|
||||
winning_trades += 1
|
||||
else:
|
||||
losing_trades += 1
|
||||
|
||||
total_trade_pairs = winning_trades + losing_trades
|
||||
win_rate = winning_trades / total_trade_pairs if total_trade_pairs > 0 else 0
|
||||
|
||||
print(f" 盈利交易: {winning_trades}次")
|
||||
print(f" 亏损交易: {losing_trades}次")
|
||||
print(f" 胜率: {win_rate*100:.1f}%")
|
||||
|
||||
print(f"\n🎯 信号统计:")
|
||||
buy_signals = sum(1 for trade in trades if trade.action == 'BUY')
|
||||
sell_signals = sum(1 for trade in trades if trade.action == 'SELL')
|
||||
print(f" 买入信号: {buy_signals}个")
|
||||
print(f" 卖出信号: {sell_signals}个")
|
||||
|
||||
# 显示策略特有信息
|
||||
strategy_info = strategy.get_strategy_info()
|
||||
print(f"\n⚡ 策略状态:")
|
||||
print(f" 当前评分: {strategy_info.get('current_scores', {})}")
|
||||
|
||||
else:
|
||||
print("❌ 回测失败")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"回测执行失败: {e}")
|
||||
print(f"❌ 回测执行失败: {e}")
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
try:
|
||||
run_multi_timeframe_score_backtest()
|
||||
except KeyboardInterrupt:
|
||||
print("\n👋 用户中断回测")
|
||||
except Exception as e:
|
||||
print(f"❌ 程序执行错误: {e}")
|
||||
logger.error(f"程序执行错误: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,62 +0,0 @@
|
||||
"""
|
||||
快速回测脚本
|
||||
|
||||
简单的单文件回测示例,可以直接运行
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加项目路径
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
project_root = os.path.dirname(os.path.dirname(current_dir))
|
||||
sys.path.append(project_root)
|
||||
|
||||
def quick_backtest():
|
||||
"""快速回测函数"""
|
||||
try:
|
||||
# 导入必要模块
|
||||
from src.back_trader.backtest_engine import BacktestEngine
|
||||
from src.back_trader.ma_cross_strategy import MACrossStrategy
|
||||
|
||||
print("🚀 快速回测开始")
|
||||
print("="*40)
|
||||
|
||||
# 创建回测引擎
|
||||
engine = BacktestEngine(initial_capital=1000000.0)
|
||||
|
||||
# 设置参数
|
||||
engine.set_universe(["601658.SH"]) # 邮储银行
|
||||
engine.set_period("2024-01-01", "2024-12-31", "1d")
|
||||
|
||||
# 创建策略
|
||||
strategy = MACrossStrategy({
|
||||
'short_period': 5,
|
||||
'long_period': 20,
|
||||
'stop_loss': 0.05,
|
||||
'take_profit': 0.15,
|
||||
'position_size': 0.3
|
||||
})
|
||||
engine.set_strategy(strategy)
|
||||
|
||||
# 执行回测
|
||||
print("📥 加载数据...")
|
||||
if not engine.load_data_from_database():
|
||||
print("❌ 数据加载失败")
|
||||
return
|
||||
|
||||
print("🔄 执行回测...")
|
||||
if engine.run_backtest():
|
||||
print("✅ 回测完成")
|
||||
engine.print_summary()
|
||||
else:
|
||||
print("❌ 回测失败")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 错误: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
quick_backtest()
|
||||
@ -1,293 +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
|
||||
|
||||
from strategy_base import StrategyBase, Portfolio
|
||||
from performance_analyzer import PerformanceAnalyzer
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SimpleBacktestEngine:
|
||||
"""
|
||||
简化回测引擎
|
||||
|
||||
用于演示和测试,使用模拟数据而不依赖数据库
|
||||
"""
|
||||
|
||||
def __init__(self, initial_capital: float = 1000000.0):
|
||||
self.initial_capital = initial_capital
|
||||
self.portfolio = Portfolio(initial_capital)
|
||||
self.strategy: Optional[StrategyBase] = None
|
||||
self.performance_analyzer = PerformanceAnalyzer()
|
||||
|
||||
# 回测配置
|
||||
self.stock_codes: List[str] = []
|
||||
self.start_date: Optional[datetime] = None
|
||||
self.end_date: Optional[datetime] = None
|
||||
|
||||
# 模拟数据
|
||||
self.mock_data: Dict[str, pd.DataFrame] = {}
|
||||
|
||||
def set_strategy(self, strategy: StrategyBase):
|
||||
"""设置交易策略"""
|
||||
self.strategy = strategy
|
||||
self.strategy.set_portfolio(self.portfolio)
|
||||
|
||||
def set_universe(self, stock_codes: List[str]):
|
||||
"""设置股票池"""
|
||||
self.stock_codes = stock_codes
|
||||
|
||||
def set_period(self, start_date: str, end_date: str):
|
||||
"""设置回测时间范围"""
|
||||
self.start_date = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
self.end_date = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
|
||||
def generate_mock_data(self, stock_code: str,
|
||||
start_price: float = 100.0,
|
||||
days: int = 252) -> pd.DataFrame:
|
||||
"""
|
||||
生成模拟股票数据
|
||||
|
||||
Args:
|
||||
stock_code: 股票代码
|
||||
start_price: 起始价格
|
||||
days: 天数
|
||||
|
||||
Returns:
|
||||
pd.DataFrame: 模拟的K线数据
|
||||
"""
|
||||
# 生成时间序列
|
||||
dates = pd.date_range(start=self.start_date, periods=days, freq='D')
|
||||
|
||||
# 生成随机收益率(正态分布)
|
||||
returns = np.random.normal(0.001, 0.02, days) # 年化1%收益,2%波动
|
||||
|
||||
# 计算价格序列
|
||||
prices = [start_price]
|
||||
for ret in returns[1:]:
|
||||
prices.append(prices[-1] * (1 + ret))
|
||||
|
||||
# 生成OHLCV数据
|
||||
data = []
|
||||
for i, (date, price) in enumerate(zip(dates, prices)):
|
||||
# 简化的OHLC生成
|
||||
high = price * (1 + np.random.uniform(0, 0.03))
|
||||
low = price * (1 - np.random.uniform(0, 0.03))
|
||||
open_price = prices[i-1] if i > 0 else price
|
||||
close_price = price
|
||||
volume = np.random.randint(1000000, 10000000)
|
||||
|
||||
data.append({
|
||||
'timestamp': date,
|
||||
'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
|
||||
})
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
df.set_index('timestamp', inplace=True)
|
||||
df.stock_code = stock_code
|
||||
|
||||
return df
|
||||
|
||||
def load_mock_data(self):
|
||||
"""加载模拟数据"""
|
||||
if not self.start_date or not self.end_date:
|
||||
logger.error("未设置回测时间范围")
|
||||
return False
|
||||
|
||||
days = (self.end_date - self.start_date).days + 1
|
||||
|
||||
for i, stock_code in enumerate(self.stock_codes):
|
||||
# 为不同股票设置不同的起始价格
|
||||
start_price = 50.0 + i * 10.0
|
||||
df = self.generate_mock_data(stock_code, start_price, days)
|
||||
self.mock_data[stock_code] = df
|
||||
logger.info(f"生成 {stock_code} 模拟数据: {len(df)} 条记录")
|
||||
|
||||
return True
|
||||
|
||||
def get_data_at_date(self, target_date: datetime, stock_code: str,
|
||||
lookback_days: int = 100) -> pd.DataFrame:
|
||||
"""获取指定日期的历史数据"""
|
||||
if stock_code not in self.mock_data:
|
||||
return pd.DataFrame()
|
||||
|
||||
df = self.mock_data[stock_code]
|
||||
|
||||
# 获取目标日期之前的数据
|
||||
mask = df.index <= target_date
|
||||
historical_data = df[mask]
|
||||
|
||||
# 限制数据长度
|
||||
if len(historical_data) > lookback_days:
|
||||
historical_data = historical_data.tail(lookback_days)
|
||||
|
||||
historical_data.stock_code = stock_code
|
||||
return historical_data
|
||||
|
||||
def execute_signals(self, timestamp: datetime):
|
||||
"""执行策略生成的交易信号"""
|
||||
if not self.strategy or not self.strategy.signals:
|
||||
return
|
||||
|
||||
# 处理当前时间戳的信号
|
||||
current_signals = [s for s in self.strategy.signals
|
||||
if s.timestamp == timestamp]
|
||||
|
||||
for signal in current_signals:
|
||||
try:
|
||||
if signal.stock_code not in self.mock_data:
|
||||
continue
|
||||
|
||||
df = self.mock_data[signal.stock_code]
|
||||
price_data = df[df.index == timestamp]
|
||||
|
||||
if price_data.empty:
|
||||
continue
|
||||
|
||||
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
|
||||
|
||||
if shares > 0:
|
||||
success = self.portfolio.execute_trade(
|
||||
timestamp, signal.stock_code, 'BUY', shares, current_price
|
||||
)
|
||||
if success:
|
||||
self.performance_analyzer.add_trade(self.portfolio.trades[-1])
|
||||
|
||||
elif signal.action == 'SELL':
|
||||
# 全部卖出
|
||||
position = self.portfolio.get_position(signal.stock_code)
|
||||
if position and position.shares > 0:
|
||||
success = self.portfolio.execute_trade(
|
||||
timestamp, signal.stock_code, 'SELL', position.shares, current_price
|
||||
)
|
||||
if success:
|
||||
self.performance_analyzer.add_trade(self.portfolio.trades[-1])
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"执行信号失败: {e}")
|
||||
|
||||
# 清空已处理的信号
|
||||
self.strategy.signals = [s for s in self.strategy.signals
|
||||
if s.timestamp != timestamp]
|
||||
|
||||
def update_portfolio_values(self, timestamp: datetime):
|
||||
"""更新投资组合价值"""
|
||||
try:
|
||||
# 获取当前所有持仓的价格
|
||||
current_prices = {}
|
||||
for stock_code in self.portfolio.positions.keys():
|
||||
if stock_code in self.mock_data:
|
||||
df = self.mock_data[stock_code]
|
||||
price_data = df[df.index == timestamp]
|
||||
if not price_data.empty:
|
||||
current_prices[stock_code] = price_data['close'].iloc[0]
|
||||
|
||||
# 更新投资组合市值
|
||||
self.portfolio.update_market_values(current_prices)
|
||||
|
||||
# 记录到性能分析器
|
||||
self.performance_analyzer.add_portfolio_value(timestamp, self.portfolio.total_value)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"更新投资组合价值失败: {e}")
|
||||
|
||||
def run_backtest(self, progress_callback=None) -> bool:
|
||||
"""运行回测"""
|
||||
try:
|
||||
logger.info("开始简化回测...")
|
||||
|
||||
# 检查必要条件
|
||||
if not self.strategy:
|
||||
logger.error("未设置交易策略")
|
||||
return False
|
||||
|
||||
# 生成模拟数据
|
||||
if not self.load_mock_data():
|
||||
logger.error("模拟数据生成失败")
|
||||
return False
|
||||
|
||||
# 初始化策略
|
||||
self.strategy.initialize()
|
||||
|
||||
# 获取所有交易日期
|
||||
all_dates = set()
|
||||
for df in self.mock_data.values():
|
||||
all_dates.update(df.index)
|
||||
|
||||
trading_dates = sorted(list(all_dates))
|
||||
total_days = len(trading_dates)
|
||||
|
||||
if total_days == 0:
|
||||
logger.error("无交易数据")
|
||||
return False
|
||||
|
||||
logger.info(f"回测期间: {trading_dates[0]} ~ {trading_dates[-1]}")
|
||||
logger.info(f"交易日数: {total_days}")
|
||||
|
||||
# 记录初始投资组合价值
|
||||
self.performance_analyzer.add_portfolio_value(trading_dates[0], self.portfolio.total_value)
|
||||
|
||||
# 逐日回测
|
||||
for i, current_date in enumerate(trading_dates):
|
||||
try:
|
||||
# 更新进度
|
||||
if progress_callback:
|
||||
progress_callback(i + 1, total_days, f"处理 {current_date.strftime('%Y-%m-%d')}")
|
||||
|
||||
# 为每只股票准备数据并调用策略
|
||||
for stock_code in self.stock_codes:
|
||||
if stock_code in self.mock_data:
|
||||
# 获取历史数据
|
||||
historical_data = self.get_data_at_date(current_date, stock_code)
|
||||
|
||||
if not historical_data.empty:
|
||||
# 调用策略处理数据
|
||||
self.strategy.on_data(historical_data, current_date)
|
||||
|
||||
# 执行交易信号
|
||||
self.execute_signals(current_date)
|
||||
|
||||
# 更新投资组合价值
|
||||
self.update_portfolio_values(current_date)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"处理 {current_date} 数据失败: {e}")
|
||||
continue
|
||||
|
||||
logger.info("回测完成")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"回测运行失败: {e}")
|
||||
return False
|
||||
|
||||
def get_results(self):
|
||||
"""获取回测结果"""
|
||||
return self.performance_analyzer.generate_report()
|
||||
|
||||
def print_summary(self):
|
||||
"""打印回测摘要"""
|
||||
report = self.get_results()
|
||||
if report:
|
||||
self.performance_analyzer.print_report(report)
|
||||
else:
|
||||
print("无可用的回测结果")
|
||||
@ -1,79 +0,0 @@
|
||||
"""
|
||||
简单回测演示
|
||||
使用模拟数据运行均线交叉策略
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import logging
|
||||
|
||||
# 添加当前目录到路径
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, current_dir)
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO, format='%(levelname)s: %(message)s')
|
||||
|
||||
def simple_demo():
|
||||
"""简单演示"""
|
||||
try:
|
||||
print("🚀 QTrade 简化回测演示")
|
||||
print("="*50)
|
||||
|
||||
# 导入模块
|
||||
from simple_backtest_engine import SimpleBacktestEngine
|
||||
from ma_cross_strategy import MACrossStrategy
|
||||
|
||||
# 创建回测引擎
|
||||
engine = SimpleBacktestEngine(initial_capital=1000000.0)
|
||||
|
||||
# 设置股票池
|
||||
stock_codes = ["STOCK_A", "STOCK_B"]
|
||||
engine.set_universe(stock_codes)
|
||||
|
||||
# 设置回测期间
|
||||
engine.set_period("2024-01-01", "2024-12-31")
|
||||
|
||||
# 创建均线交叉策略
|
||||
strategy_params = {
|
||||
'short_period': 5, # 5日均线
|
||||
'long_period': 20, # 20日均线
|
||||
'stop_loss': 0.05, # 5%止损
|
||||
'take_profit': 0.15, # 15%止盈
|
||||
'position_size': 0.3 # 每次30%仓位
|
||||
}
|
||||
strategy = MACrossStrategy(strategy_params)
|
||||
engine.set_strategy(strategy)
|
||||
|
||||
# 进度回调函数
|
||||
def progress_callback(current, total, message):
|
||||
progress = (current / total) * 100
|
||||
print(f"\r进度: {progress:.1f}% - {message}", end="", flush=True)
|
||||
if current == total:
|
||||
print()
|
||||
|
||||
# 运行回测
|
||||
print("\n🔄 开始执行回测...")
|
||||
success = engine.run_backtest(progress_callback)
|
||||
|
||||
if success:
|
||||
print("\n✅ 回测完成")
|
||||
|
||||
# 显示结果
|
||||
print("\n📊 回测结果:")
|
||||
engine.print_summary()
|
||||
|
||||
return True
|
||||
else:
|
||||
print("\n❌ 回测失败")
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 演示失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
return False
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
simple_demo()
|
||||
@ -1,70 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
测试编码修复
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import locale
|
||||
|
||||
# 修复编码问题
|
||||
def fix_encoding():
|
||||
"""修复编码设置"""
|
||||
try:
|
||||
# 设置环境变量
|
||||
os.environ['PYTHONIOENCODING'] = 'utf-8'
|
||||
os.environ['LANG'] = 'zh_CN.UTF-8'
|
||||
|
||||
print("✅ 编码设置修复完成")
|
||||
print(f"系统默认编码: {sys.getdefaultencoding()}")
|
||||
print(f"文件系统编码: {sys.getfilesystemencoding()}")
|
||||
print(f"控制台编码: {getattr(sys.stdout, 'encoding', 'unknown')}")
|
||||
print(f"区域设置: {locale.getdefaultlocale()}")
|
||||
|
||||
except Exception as e:
|
||||
print(f"编码设置失败: {e}")
|
||||
|
||||
# 应用编码修复
|
||||
fix_encoding()
|
||||
|
||||
# 添加当前目录到路径
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, current_dir)
|
||||
|
||||
print(f"当前目录: {current_dir}")
|
||||
print(f"Python路径: {sys.path[:3]}")
|
||||
|
||||
# 测试中文输出
|
||||
print("🔍 测试中文输出:")
|
||||
print(" 📊 数据库连接成功")
|
||||
print(" ✅ 策略初始化完成")
|
||||
print(" 🚀 开始回测执行")
|
||||
print(" 💰 资金变化统计")
|
||||
print(" 📈 交易信号生成")
|
||||
|
||||
try:
|
||||
import strategy_base
|
||||
print("✅ strategy_base 导入成功")
|
||||
print(f"策略基类: {strategy_base.StrategyBase}")
|
||||
except Exception as e:
|
||||
print(f"❌ strategy_base 导入失败: {e}")
|
||||
|
||||
try:
|
||||
import ma_cross_strategy
|
||||
print("✅ ma_cross_strategy 导入成功")
|
||||
except Exception as e:
|
||||
print(f"❌ ma_cross_strategy 导入失败: {e}")
|
||||
|
||||
try:
|
||||
import backtest_engine
|
||||
print("✅ backtest_engine 导入成功")
|
||||
except Exception as e:
|
||||
print(f"❌ backtest_engine 导入失败: {e}")
|
||||
|
||||
try:
|
||||
import multi_timeframe_ma_score_strategy
|
||||
print("✅ multi_timeframe_ma_score_strategy 导入成功")
|
||||
except Exception as e:
|
||||
print(f"❌ multi_timeframe_ma_score_strategy 导入失败: {e}")
|
||||
@ -1,44 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
测试模块导入
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 修复编码问题
|
||||
os.environ['PYTHONIOENCODING'] = 'utf-8'
|
||||
|
||||
# 添加当前目录到路径
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, current_dir)
|
||||
|
||||
print(f"Current Directory: {current_dir}")
|
||||
print(f"Python Path: {sys.path[:3]}")
|
||||
|
||||
try:
|
||||
import strategy_base
|
||||
print("Success: strategy_base imported successfully")
|
||||
print(f"Strategy Base Class: {strategy_base.StrategyBase}")
|
||||
except Exception as e:
|
||||
print(f"Error: strategy_base import failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
try:
|
||||
import ma_cross_strategy
|
||||
print("Success: ma_cross_strategy imported successfully")
|
||||
except Exception as e:
|
||||
print(f"Error: ma_cross_strategy import failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
try:
|
||||
import backtest_engine
|
||||
print("Success: backtest_engine imported successfully")
|
||||
except Exception as e:
|
||||
print(f"Error: backtest_engine import failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
@ -1,147 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
快速测试多均线交叉逻辑
|
||||
使用一个简化的版本来测试2024年数据中的均线交叉情况
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import pandas as pd
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# 添加项目路径
|
||||
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.append(project_root)
|
||||
|
||||
from data_process_model.database_config import init_database
|
||||
from data_process_model.stock_models import create_stock_kline_model
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def calculate_moving_averages(data, periods=[5, 10, 20]):
|
||||
"""计算移动平均线"""
|
||||
for period in periods:
|
||||
if len(data) >= period:
|
||||
data[f'MA{period}'] = data['close'].rolling(window=period).mean()
|
||||
return data
|
||||
|
||||
def detect_ma_crossovers(data, periods=[5, 10, 20]):
|
||||
"""检测均线交叉"""
|
||||
crossovers = []
|
||||
|
||||
if len(data) < 2:
|
||||
return crossovers
|
||||
|
||||
# 检查所有可能的均线组合
|
||||
for i in range(len(periods)):
|
||||
for j in range(i + 1, len(periods)):
|
||||
short_ma = f'MA{periods[i]}'
|
||||
long_ma = f'MA{periods[j]}'
|
||||
|
||||
if short_ma in data.columns and long_ma in data.columns:
|
||||
# 当前值和前一个值
|
||||
if len(data) >= 2:
|
||||
current_short = data[short_ma].iloc[-1]
|
||||
current_long = data[long_ma].iloc[-1]
|
||||
prev_short = data[short_ma].iloc[-2]
|
||||
prev_long = data[long_ma].iloc[-2]
|
||||
|
||||
# 检查交叉
|
||||
if (prev_short <= prev_long and current_short > current_long):
|
||||
# 金叉
|
||||
crossovers.append(('golden', periods[i], periods[j], current_short, current_long))
|
||||
elif (prev_short >= prev_long and current_short < current_long):
|
||||
# 死叉
|
||||
crossovers.append(('death', periods[i], periods[j], current_short, current_long))
|
||||
|
||||
return crossovers
|
||||
|
||||
def test_ma_crossovers_quick():
|
||||
"""快速测试均线交叉"""
|
||||
print("🧪 快速测试多均线交叉逻辑...")
|
||||
|
||||
try:
|
||||
# 初始化数据库
|
||||
init_database()
|
||||
print("✅ 数据库连接成功")
|
||||
|
||||
stock_code = "601398.SH"
|
||||
timeframes = ['15m', '30m', '60m']
|
||||
ma_periods = [5, 10, 20]
|
||||
|
||||
total_crossovers = 0
|
||||
|
||||
for timeframe in timeframes:
|
||||
print(f"\n📊 检查 {timeframe} 时间周期...")
|
||||
|
||||
# 创建模型
|
||||
model_class = create_stock_kline_model(stock_code, timeframe)
|
||||
|
||||
# 查询2024年数据,按时间排序
|
||||
query = model_class.select().where(
|
||||
(model_class.timestamp >= '2024-01-01') &
|
||||
(model_class.timestamp <= '2024-12-31')
|
||||
).order_by(model_class.timestamp)
|
||||
|
||||
# 转换为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:
|
||||
print(f"❌ {timeframe} 没有数据")
|
||||
continue
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
||||
df = df.set_index('timestamp').sort_index()
|
||||
|
||||
print(f" 数据量: {len(df)} 条记录")
|
||||
print(f" 时间范围: {df.index.min()} 到 {df.index.max()}")
|
||||
|
||||
# 计算移动平均线
|
||||
df = calculate_moving_averages(df, ma_periods)
|
||||
|
||||
# 逐个时间点检查交叉
|
||||
crossover_count = 0
|
||||
for i in range(max(ma_periods), len(df)):
|
||||
subset = df.iloc[:i+1] # 取到当前时间点的所有数据
|
||||
crossovers = detect_ma_crossovers(subset, ma_periods)
|
||||
|
||||
if crossovers:
|
||||
timestamp = subset.index[-1]
|
||||
crossover_count += len(crossovers)
|
||||
|
||||
print(f" 🎯 {timestamp.strftime('%Y-%m-%d %H:%M')} 发现 {len(crossovers)} 个交叉:")
|
||||
for crossover_type, short_period, long_period, short_value, long_value in crossovers:
|
||||
signal_type = "金叉" if crossover_type == "golden" else "死叉"
|
||||
print(f" {signal_type}: MA{short_period}({short_value:.3f}) vs MA{long_period}({long_value:.3f})")
|
||||
|
||||
print(f" ✅ {timeframe} 总交叉次数: {crossover_count}")
|
||||
total_crossovers += crossover_count
|
||||
|
||||
print(f"\n🎉 测试完成!")
|
||||
print(f"📈 2024年全年所有时间周期总交叉次数: {total_crossovers}")
|
||||
|
||||
if total_crossovers == 0:
|
||||
print("\n🤔 没有检测到交叉信号,可能的原因:")
|
||||
print(" 1. 均线设置参数过于相近")
|
||||
print(" 2. 市场趋势较为平稳")
|
||||
print(" 3. 检测逻辑需要调整")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
logger.error(f"测试失败: {e}")
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_ma_crossovers_quick()
|
||||
@ -1,43 +0,0 @@
|
||||
"""
|
||||
简单测试脚本
|
||||
"""
|
||||
import sys
|
||||
import os
|
||||
|
||||
# 添加路径
|
||||
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
|
||||
try:
|
||||
print("1. 测试导入策略基类...")
|
||||
from back_trader.strategy_base import StrategyBase, Portfolio, Position, Trade
|
||||
print("✅ 策略基类导入成功")
|
||||
|
||||
print("2. 测试导入均线策略...")
|
||||
from back_trader.ma_cross_strategy import MACrossStrategy
|
||||
print("✅ 均线策略导入成功")
|
||||
|
||||
print("3. 测试导入性能分析器...")
|
||||
from back_trader.performance_analyzer import PerformanceAnalyzer
|
||||
print("✅ 性能分析器导入成功")
|
||||
|
||||
print("4. 测试导入简化回测引擎...")
|
||||
from back_trader.simple_backtest_engine import SimpleBacktestEngine
|
||||
print("✅ 简化回测引擎导入成功")
|
||||
|
||||
print("5. 测试创建策略实例...")
|
||||
strategy = MACrossStrategy({
|
||||
'short_period': 5,
|
||||
'long_period': 20
|
||||
})
|
||||
print(f"✅ 策略实例创建成功: {strategy.name}")
|
||||
|
||||
print("6. 测试创建回测引擎实例...")
|
||||
engine = SimpleBacktestEngine(100000)
|
||||
print(f"✅ 回测引擎创建成功, 初始资金: {engine.initial_capital}")
|
||||
|
||||
print("\n🎉 所有模块测试通过!")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
@ -1,85 +0,0 @@
|
||||
"""
|
||||
测试多时间周期均线交叉策略
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# 添加项目路径
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
src_dir = os.path.dirname(current_dir)
|
||||
sys.path.insert(0, src_dir)
|
||||
|
||||
# 导入策略模块
|
||||
try:
|
||||
from multi_timeframe_ma_strategy import MultiTimeframeMAStrategy
|
||||
print("✅ 策略模块导入成功")
|
||||
except Exception as e:
|
||||
print(f"❌ 策略模块导入失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
exit(1)
|
||||
|
||||
def test_strategy():
|
||||
"""测试策略基本功能"""
|
||||
print("\n🧪 开始测试多时间周期均线交叉策略")
|
||||
|
||||
try:
|
||||
# 创建策略实例
|
||||
strategy = MultiTimeframeMAStrategy({
|
||||
'short_ma_period': 5,
|
||||
'long_ma_period': 20,
|
||||
'timeframes': ['15m', '30m', '60m'],
|
||||
'position_size': 0.3
|
||||
})
|
||||
|
||||
print("✅ 策略实例创建成功")
|
||||
|
||||
# 初始化策略
|
||||
strategy.initialize()
|
||||
print("✅ 策略初始化完成")
|
||||
|
||||
# 创建测试数据
|
||||
test_data = pd.DataFrame({
|
||||
'open': [5.80, 5.82, 5.85],
|
||||
'high': [5.90, 5.88, 5.92],
|
||||
'low': [5.75, 5.78, 5.80],
|
||||
'close': [5.85, 5.86, 5.88],
|
||||
'volume': [1000000, 1200000, 900000]
|
||||
}, index=pd.date_range(start=datetime.now(), periods=3, freq='1min'))
|
||||
|
||||
print("✅ 测试数据创建完成")
|
||||
|
||||
# 测试数据处理
|
||||
timestamps = [datetime.now() + timedelta(minutes=i) for i in range(len(test_data))]
|
||||
|
||||
for i, (idx, row) in enumerate(test_data.iterrows()):
|
||||
timestamp = timestamps[i]
|
||||
print(f"\n📊 处理第 {i+1} 条数据: {timestamp}")
|
||||
|
||||
strategy.on_data(pd.DataFrame([row]), timestamp)
|
||||
print(f" 当前信号数量: {len(strategy.signals)}")
|
||||
|
||||
# 显示策略信息
|
||||
info = strategy.get_strategy_info()
|
||||
print(f"\n📈 策略信息:")
|
||||
for key, value in info.items():
|
||||
print(f" {key}: {value}")
|
||||
|
||||
# 显示生成的信号
|
||||
print(f"\n🎯 生成的交易信号 ({len(strategy.signals)} 个):")
|
||||
for i, signal in enumerate(strategy.signals):
|
||||
print(f" {i+1}. {signal.timestamp} - {signal.action} {signal.stock_code}: {signal.reason}")
|
||||
|
||||
print("\n✅ 策略测试完成")
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 策略测试失败: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
if __name__ == "__main__":
|
||||
test_strategy()
|
||||
@ -1,179 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
简单的多时间周期策略测试
|
||||
测试从多个时间周期表读取数据并进行均线交叉分析
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import pandas as pd
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
# 添加项目路径
|
||||
project_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.append(project_root)
|
||||
|
||||
from data_process_model.database_config import init_database
|
||||
from data_process_model.stock_models import create_stock_kline_model
|
||||
|
||||
# 配置日志
|
||||
logging.basicConfig(level=logging.INFO, format='%(levelname)s:%(name)s:%(message)s')
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class SimpleMultiTimeframeTest:
|
||||
"""简单多时间周期测试类"""
|
||||
|
||||
def __init__(self):
|
||||
self.stock_code = "601398.SH"
|
||||
self.timeframes = ['15m', '30m', '60m']
|
||||
self.ma_periods = [5, 10, 20] # 三根均线
|
||||
self.scores = {self.stock_code: 0} # 股票评分系统
|
||||
|
||||
def init_database_connection(self):
|
||||
"""初始化数据库连接"""
|
||||
try:
|
||||
init_database()
|
||||
logger.info("✅ 数据库连接成功")
|
||||
return True
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 数据库连接失败: {e}")
|
||||
return False
|
||||
|
||||
def load_data_from_timeframe(self, timeframe, limit=50):
|
||||
"""从指定时间周期表加载数据"""
|
||||
try:
|
||||
# 创建对应的模型类
|
||||
model_class = create_stock_kline_model(self.stock_code, timeframe)
|
||||
|
||||
# 查询最新数据
|
||||
query = model_class.select().order_by(model_class.timestamp.desc()).limit(limit)
|
||||
|
||||
# 转换为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:
|
||||
logger.warning(f"⚠️ 未找到{timeframe}数据")
|
||||
return pd.DataFrame()
|
||||
|
||||
df = pd.DataFrame(data)
|
||||
df['timestamp'] = pd.to_datetime(df['timestamp'])
|
||||
df = df.set_index('timestamp').sort_index()
|
||||
|
||||
logger.info(f"✅ 成功加载{timeframe}数据: {len(df)}条记录")
|
||||
return df
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"❌ 加载{timeframe}数据失败: {e}")
|
||||
return pd.DataFrame()
|
||||
|
||||
def calculate_ma_crossover(self, df):
|
||||
"""计算均线交叉"""
|
||||
if len(df) < self.long_ma:
|
||||
return None, None, None
|
||||
|
||||
# 计算移动平均线
|
||||
df['ma_short'] = df['close'].rolling(window=self.short_ma).mean()
|
||||
df['ma_long'] = df['close'].rolling(window=self.long_ma).mean()
|
||||
|
||||
# 获取最近两个点的数据
|
||||
if len(df) < 2:
|
||||
return None, None, None
|
||||
|
||||
# 最新和前一个数据点
|
||||
current = df.iloc[-1]
|
||||
previous = df.iloc[-2]
|
||||
|
||||
# 检查交叉
|
||||
crossover = None
|
||||
if (previous['ma_short'] <= previous['ma_long'] and
|
||||
current['ma_short'] > current['ma_long']):
|
||||
crossover = 'golden' # 金叉
|
||||
elif (previous['ma_short'] >= previous['ma_long'] and
|
||||
current['ma_short'] < current['ma_long']):
|
||||
crossover = 'death' # 死叉
|
||||
|
||||
return crossover, current['ma_short'], current['ma_long']
|
||||
|
||||
def update_score(self, crossover):
|
||||
"""更新股票评分"""
|
||||
old_score = self.scores[self.stock_code]
|
||||
|
||||
if crossover == 'golden':
|
||||
self.scores[self.stock_code] += 1
|
||||
logger.info(f"📈 发现金叉,分数+1: {old_score} -> {self.scores[self.stock_code]}")
|
||||
elif crossover == 'death':
|
||||
self.scores[self.stock_code] = max(0, self.scores[self.stock_code] - 1)
|
||||
logger.info(f"📉 发现死叉,分数-1: {old_score} -> {self.scores[self.stock_code]}")
|
||||
|
||||
# 检查买卖信号
|
||||
current_score = self.scores[self.stock_code]
|
||||
if old_score == 0 and current_score == 1:
|
||||
return "BUY"
|
||||
elif old_score == 1 and current_score == 0:
|
||||
return "SELL"
|
||||
|
||||
return None
|
||||
|
||||
def run_test(self):
|
||||
"""运行测试"""
|
||||
print("🔍 开始多时间周期策略测试...")
|
||||
|
||||
# 初始化数据库
|
||||
if not self.init_database_connection():
|
||||
return
|
||||
|
||||
print(f"📊 测试股票: {self.stock_code}")
|
||||
print(f"⏰ 时间周期: {self.timeframes}")
|
||||
print(f"📈 短期均线: {self.short_ma}期,长期均线: {self.long_ma}期")
|
||||
print(f"🎯 初始评分: {self.scores[self.stock_code]}")
|
||||
print("-" * 50)
|
||||
|
||||
signals = []
|
||||
|
||||
# 逐个检查各时间周期
|
||||
for timeframe in self.timeframes:
|
||||
print(f"\n🔍 分析{timeframe}时间周期...")
|
||||
|
||||
# 加载数据
|
||||
df = self.load_data_from_timeframe(timeframe)
|
||||
if df.empty:
|
||||
continue
|
||||
|
||||
# 计算均线交叉
|
||||
crossover, ma_short, ma_long = self.calculate_ma_crossover(df)
|
||||
|
||||
if crossover:
|
||||
print(f" ⚡ 发现{crossover}交叉! MA{self.short_ma}={ma_short:.3f}, MA{self.long_ma}={ma_long:.3f}")
|
||||
signal = self.update_score(crossover)
|
||||
if signal:
|
||||
signals.append((timeframe, signal))
|
||||
print(f" 🚨 生成{signal}信号!")
|
||||
else:
|
||||
print(f" ✅ 无交叉信号 (MA{self.short_ma}={ma_short:.3f}, MA{self.long_ma}={ma_long:.3f})")
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print(f"📊 最终评分: {self.scores[self.stock_code]}")
|
||||
print(f"🎯 生成信号数量: {len(signals)}")
|
||||
if signals:
|
||||
for timeframe, signal in signals:
|
||||
print(f" 📈 {timeframe}: {signal}")
|
||||
else:
|
||||
print(" ✅ 无交易信号")
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
test = SimpleMultiTimeframeTest()
|
||||
test.run_test()
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -1,66 +0,0 @@
|
||||
#!/usr/bin/env python
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
Multi-Timeframe Strategy Test (中英文混合测试)
|
||||
"""
|
||||
|
||||
import sys
|
||||
import os
|
||||
|
||||
# Fix encoding issues
|
||||
os.environ['PYTHONIOENCODING'] = 'utf-8'
|
||||
|
||||
# Add current directory to path
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, current_dir)
|
||||
|
||||
print(f"Current Directory: {current_dir}")
|
||||
print(f"Python Environment: xtquant conda")
|
||||
|
||||
# Test multi-timeframe strategy
|
||||
print("\n=== Multi-Timeframe Strategy Test ===")
|
||||
|
||||
try:
|
||||
import multi_timeframe_ma_score_strategy
|
||||
print("Success: multi_timeframe_ma_score_strategy imported")
|
||||
|
||||
# Create strategy instance
|
||||
strategy = multi_timeframe_ma_score_strategy.MultiTimeframeMAScoreStrategy()
|
||||
print(f"Strategy Name: {strategy.name}")
|
||||
print(f"Strategy Description: {strategy.description}")
|
||||
print(f"Short MA Period: {strategy.short_ma}")
|
||||
print(f"Long MA Period: {strategy.long_ma}")
|
||||
print(f"Timeframes: {strategy.timeframes}")
|
||||
|
||||
# Test initialization
|
||||
if strategy.initialize():
|
||||
print("Success: Strategy initialized successfully")
|
||||
else:
|
||||
print("Error: Strategy initialization failed")
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error: multi_timeframe_ma_score_strategy import failed: {e}")
|
||||
import traceback
|
||||
traceback.print_exc()
|
||||
|
||||
# Test simple multi-timeframe test
|
||||
print("\n=== Simple Multi-Timeframe Test ===")
|
||||
|
||||
try:
|
||||
import test_multi_timeframe_simple
|
||||
print("Success: test_multi_timeframe_simple imported")
|
||||
except Exception as e:
|
||||
print(f"Error: test_multi_timeframe_simple import failed: {e}")
|
||||
|
||||
# Test backtest runner
|
||||
print("\n=== Backtest Runner Test ===")
|
||||
|
||||
try:
|
||||
import run_multi_timeframe_score_backtest
|
||||
print("Success: run_multi_timeframe_score_backtest imported")
|
||||
except Exception as e:
|
||||
print(f"Error: run_multi_timeframe_score_backtest import failed: {e}")
|
||||
|
||||
print("\n=== All Tests Completed ===")
|
||||
print("Note: Using English output to avoid encoding issues in conda environment")
|
||||
@ -1,169 +0,0 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
测试新的3根均线交叉逻辑
|
||||
验证MA5、MA10、MA20的交叉检测
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
import pandas as pd
|
||||
import numpy as np
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# 修复编码问题
|
||||
os.environ['PYTHONIOENCODING'] = 'utf-8'
|
||||
|
||||
# 添加项目路径
|
||||
current_dir = os.path.dirname(os.path.abspath(__file__))
|
||||
sys.path.insert(0, current_dir)
|
||||
|
||||
from multi_timeframe_ma_score_strategy import MultiTimeframeMAScoreStrategy
|
||||
|
||||
def create_test_data_with_crossovers():
|
||||
"""创建包含均线交叉的测试数据"""
|
||||
|
||||
# 创建模拟价格数据,确保产生各种交叉
|
||||
dates = [datetime.now() - timedelta(days=30-i) for i in range(30)]
|
||||
|
||||
# 设计价格走势:先下跌再上涨,制造交叉
|
||||
base_price = 7.5
|
||||
prices = []
|
||||
|
||||
for i in range(30):
|
||||
if i < 10:
|
||||
# 前10天:下跌趋势
|
||||
price = base_price - (i * 0.05)
|
||||
elif i < 15:
|
||||
# 中间5天:震荡
|
||||
price = base_price - 0.5 + (0.1 * (i % 3))
|
||||
else:
|
||||
# 后15天:上涨趋势,制造金叉
|
||||
price = base_price - 0.3 + ((i - 15) * 0.08)
|
||||
|
||||
# 添加随机波动
|
||||
noise = np.random.normal(0, 0.02)
|
||||
prices.append(max(price + noise, 0.1))
|
||||
|
||||
df = pd.DataFrame({
|
||||
'timestamp': dates,
|
||||
'open': prices,
|
||||
'high': [p * 1.02 for p in prices],
|
||||
'low': [p * 0.98 for p in prices],
|
||||
'close': prices,
|
||||
'volume': [1000000] * 30
|
||||
})
|
||||
|
||||
df.set_index('timestamp', inplace=True)
|
||||
return df
|
||||
|
||||
def test_ma_crossover_logic():
|
||||
"""测试均线交叉逻辑"""
|
||||
|
||||
print("=== Testing 3-MA Crossover Logic ===")
|
||||
|
||||
# 创建策略实例
|
||||
strategy = MultiTimeframeMAScoreStrategy()
|
||||
|
||||
print(f"Strategy: {strategy.name}")
|
||||
print(f"MA Periods: {strategy.ma_periods}")
|
||||
|
||||
# 创建测试数据
|
||||
test_df = create_test_data_with_crossovers()
|
||||
|
||||
print(f"\nTest Data: {len(test_df)} periods")
|
||||
print(f"Price Range: {test_df['close'].min():.3f} - {test_df['close'].max():.3f}")
|
||||
|
||||
# 计算均线交叉
|
||||
crossovers = strategy.calculate_ma_crossovers(test_df)
|
||||
|
||||
print(f"\nCrossover Analysis:")
|
||||
if crossovers:
|
||||
print(f"Found {len(crossovers)} crossovers:")
|
||||
for crossover_type, short_period, long_period, short_value, long_value in crossovers:
|
||||
print(f" {crossover_type.upper()}: MA{short_period}({short_value:.3f}) vs MA{long_period}({long_value:.3f})")
|
||||
else:
|
||||
print(" No crossovers detected")
|
||||
|
||||
# 显示最后几天的均线值
|
||||
print(f"\nRecent MA Values (last 5 periods):")
|
||||
for period in strategy.ma_periods:
|
||||
test_df[f'ma_{period}'] = test_df['close'].rolling(window=period).mean()
|
||||
|
||||
recent_data = test_df.tail(5)
|
||||
for idx, row in recent_data.iterrows():
|
||||
print(f" {idx.strftime('%Y-%m-%d')}: Close={row['close']:.3f}, " +
|
||||
f"MA5={row['ma_5']:.3f}, MA10={row['ma_10']:.3f}, MA20={row['ma_20']:.3f}")
|
||||
|
||||
# 测试评分系统
|
||||
print(f"\nScore Update Test:")
|
||||
stock_code = "TEST.SH"
|
||||
if crossovers:
|
||||
old_score, new_score, signal, details = strategy.update_stock_score(stock_code, crossovers)
|
||||
print(f" Score Change: {old_score} -> {new_score}")
|
||||
print(f" Signal Generated: {signal}")
|
||||
print(f" Crossover Details: {details}")
|
||||
else:
|
||||
print(" No crossovers to test scoring")
|
||||
|
||||
return crossovers
|
||||
|
||||
def test_multiple_crossovers():
|
||||
"""测试多个交叉组合的情况"""
|
||||
|
||||
print("\n=== Testing Multiple Crossover Combinations ===")
|
||||
|
||||
strategy = MultiTimeframeMAScoreStrategy()
|
||||
|
||||
# 模拟多个交叉同时发生的情况
|
||||
mock_crossovers = [
|
||||
('golden', 5, 10, 7.60, 7.55), # MA5上穿MA10
|
||||
('golden', 5, 20, 7.60, 7.45), # MA5上穿MA20
|
||||
('death', 10, 20, 7.48, 7.50), # MA10下穿MA20
|
||||
]
|
||||
|
||||
print("Simulated crossovers:")
|
||||
for crossover_type, short, long, short_val, long_val in mock_crossovers:
|
||||
print(f" {crossover_type.upper()}: MA{short}({short_val:.3f}) vs MA{long}({long_val:.3f})")
|
||||
|
||||
stock_code = "TEST2.SH"
|
||||
old_score, new_score, signal, details = strategy.update_stock_score(stock_code, mock_crossovers)
|
||||
|
||||
print(f"\nScoring Result:")
|
||||
print(f" Golden crosses: 2 (+2 points)")
|
||||
print(f" Death crosses: 1 (-1 point)")
|
||||
print(f" Net change: +1 point")
|
||||
print(f" Final score: {old_score} -> {new_score}")
|
||||
print(f" Signal: {signal}")
|
||||
print(f" Details: {details}")
|
||||
|
||||
def main():
|
||||
"""主测试函数"""
|
||||
|
||||
print("Three Moving Average Crossover Logic Test")
|
||||
print("Testing MA5, MA10, MA20 crossover detection")
|
||||
print("=" * 50)
|
||||
|
||||
# 测试基本交叉逻辑
|
||||
crossovers = test_ma_crossover_logic()
|
||||
|
||||
# 测试多重交叉
|
||||
test_multiple_crossovers()
|
||||
|
||||
print("\n" + "=" * 50)
|
||||
print("Test Summary:")
|
||||
print("✓ 3-MA crossover detection implemented")
|
||||
print("✓ Score calculation with multiple crossovers")
|
||||
print("✓ Signal generation based on score changes")
|
||||
print("\nLogic verification:")
|
||||
print("- MA5 ↗ MA10/MA20 = Golden Cross (+1 each)")
|
||||
print("- MA5 ↘ MA10/MA20 = Death Cross (-1 each)")
|
||||
print("- MA10 ↗ MA20 = Golden Cross (+1)")
|
||||
print("- MA10 ↘ MA20 = Death Cross (-1)")
|
||||
print("- Score 0→1+ triggers BUY signal")
|
||||
print("- Score 1+→0 triggers SELL signal")
|
||||
print("- Minimum score = 0 (no negative)")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@ -16,10 +16,13 @@ from stockdata_manager import get_stock_data_manager
|
||||
# ============== 全局配置参数 ==============
|
||||
# 使用标准化的股票代码格式
|
||||
g_stock_code_list = [
|
||||
normalize_stock_code("601658.SH"),
|
||||
normalize_stock_code("510310.SH"),
|
||||
normalize_stock_code("601398.SH"),
|
||||
normalize_stock_code("601288.SH")
|
||||
#normalize_stock_code("601658.SH"),
|
||||
#normalize_stock_code("510310.SH"),
|
||||
#normalize_stock_code("601398.SH"),
|
||||
#normalize_stock_code("601288.SH"),
|
||||
#normalize_stock_code("601609.SH"),
|
||||
#normalize_stock_code("601288.SH"),
|
||||
normalize_stock_code("300339.SZ")
|
||||
] # 标准化后的股票代码
|
||||
|
||||
# 调整时间范围到最近的一个月,避免跨度过大导致数据获取问题
|
||||
|
||||
@ -38,16 +38,16 @@ class StockKlineBase(BaseModel):
|
||||
amount = DecimalField(max_digits=20, decimal_places=2, help_text="成交额", null=True)
|
||||
|
||||
# 支持的K线周期常量
|
||||
SUPPORTED_PERIODS = ['1m', '5m', '15m', '30m', '60m', '1d']
|
||||
SUPPORTED_PERIODS = ['1m', '15m', '30m', '60m', '1d'] # 添加1d用于回测数据
|
||||
|
||||
def create_stock_kline_model(stock_code: str, period: str):
|
||||
"""
|
||||
动态创建股票K线数据表模型
|
||||
专门用于创建1分钟、15分钟、30分钟、60分钟、日线周期的K线数据模型
|
||||
专门用于创建1分钟、15分钟、30分钟、60分钟周期的K线数据模型
|
||||
|
||||
Args:
|
||||
stock_code (str): 股票代码,如 "601398.SH", "000001.SZ"
|
||||
period (str): 数据周期,支持 "1m", "15m", "30m", "60m", "1d"
|
||||
period (str): 数据周期,支持 "1m", "15m", "30m", "60m"
|
||||
|
||||
Returns:
|
||||
type: 动态创建的股票K线模型类
|
||||
|
||||
Loading…
Reference in New Issue
Block a user