180 lines
6.3 KiB
Python
180 lines
6.3 KiB
Python
|
|
#!/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_price),
|
||
|
|
'high': float(record.high_price),
|
||
|
|
'low': float(record.low_price),
|
||
|
|
'close': float(record.close_price),
|
||
|
|
'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()
|