This commit is contained in:
27942
2025-10-14 10:47:40 +08:00
parent a269989e4b
commit c01f0465a4
4 changed files with 271 additions and 20 deletions

View File

@@ -1,16 +1,23 @@
from DrissionPage import ChromiumPage, ChromiumOptions
from bit_tools import openBrowser
from models.weex import Weex1
if __name__ == '__main__':
bit_port = openBrowser(id="8dcb4f744cf64ab190e465e153088515")
co = ChromiumOptions()
co.set_local_port(1001)
co.set_local_port(port=bit_port)
co = ChromiumOptions()
co.set_local_port(bit_port)
page = ChromiumPage(addr_or_opts=co)
page.set.window.max()
page.listen.start("gateway1.janapw.com/api/v1/public/quote/v1/getKlineV2")
page.listen.start("https://http-gateway2.janapw.com/api/v1/public/quote/v1/getKlineV2")
page.get(url="https://www.weeaxs.site/zh-CN/futures/ETH-USDT")

View File

@@ -1,9 +1,82 @@
"""
量化交易回测系统 - 优化版
功能:基于包住形态的交易信号识别和回测分析
作者:量化交易团队
版本2.0
"""
import datetime
from typing import List, Dict, Tuple, Optional, Any
from dataclasses import dataclass
from loguru import logger
from peewee import fn
from models.weex import Weex15, Weex1
# ===============================================================
# 📊 配置管理类
# ===============================================================
@dataclass
class BacktestConfig:
"""回测配置类"""
# 交易参数
take_profit: float = 8.0 # 止盈点数
stop_loss: float = -1.0 # 止损点数
contract_size: float = 10000 # 合约规模
open_fee: float = 5.0 # 开仓手续费
close_fee_rate: float = 0.0005 # 平仓手续费率
# 回测日期范围
start_date: str = "2025-7-1"
end_date: str = "2025-7-31"
# 信号参数
enable_bear_bull_engulf: bool = True # 涨包跌信号
enable_bull_bear_engulf: bool = True # 跌包涨信号
def __post_init__(self):
"""验证配置参数"""
if self.take_profit <= 0:
raise ValueError("止盈点数必须大于0")
if self.stop_loss >= 0:
raise ValueError("止损点数必须小于0")
@dataclass
class TradeRecord:
"""交易记录类"""
entry_time: datetime.datetime
exit_time: datetime.datetime
signal_type: str
direction: str
entry_price: float
exit_price: float
profit_loss: float
profit_amount: float
total_fee: float
net_profit: float
@dataclass
class SignalStats:
"""信号统计类"""
signal_name: str
count: int = 0
wins: int = 0
total_profit: float = 0.0
@property
def win_rate(self) -> float:
"""胜率计算"""
return (self.wins / self.count * 100) if self.count > 0 else 0.0
@property
def avg_profit(self) -> float:
"""平均盈利"""
return self.total_profit / self.count if self.count > 0 else 0.0
# ===============================================================
# 📊 数据获取模块
# ===============================================================
@@ -58,9 +131,9 @@ def check_signal(prev, curr):
if is_bullish(curr) and is_bearish(prev) and c_open <= p_close and c_close >= p_open:
return "long", "bear_bull_engulf"
# 前涨后跌包住 -> 做空
if is_bearish(curr) and is_bullish(prev) and c_open >= p_close and c_close <= p_open:
return "short", "bull_bear_engulf"
# # 前涨后跌包住 -> 做空
# if is_bearish(curr) and is_bullish(prev) and c_open >= p_close and c_close <= p_open:
# return "short", "bull_bear_engulf"
return None, None
@@ -180,17 +253,17 @@ if __name__ == '__main__':
total_profit = sum(t['diff'] / t['entry'] * 10000 for t in trades)
total_fee = sum(5 + 10000 / t['entry'] * t['exit'] * 0.0005 for t in trades)
logger.info("===== 每笔交易详情 =====")
for t in trades:
logger.info(f"{t['entry_time']} {t['direction']}({t['signal']}) "
f"入场={t['entry']:.2f} 出场={t['exit']:.2f} 出场时间={t['exit_time']} "
f"差价={t['diff']:.2f}")
print(i1, i)
print(f"\n一共交易笔数:{len(trades)}")
print(f"一共盈利:{total_profit:.2f}")
print(f"一共手续费:{total_fee:.2f}")
print(f"净利润:{total_profit - total_fee:.2f}")
# logger.info("===== 每笔交易详情 =====")
# for t in trades:
# logger.info(f"{t['entry_time']} {t['direction']}({t['signal']}) "
# f"入场={t['entry']:.2f} 出场={t['exit']:.2f} 出场时间={t['exit_time']} "
# f"差价={t['diff']:.2f}")
#
# print(i1, i)
# print(f"\n一共交易笔数{len(trades)}")
# print(f"一共盈利:{total_profit:.2f}")
# print(f"一共手续费:{total_fee:.2f}")
# print(f"净利润:{total_profit - total_fee:.2f}")
if total_profit > total_fee * 0.1:
print(i1, i)
@@ -201,7 +274,7 @@ if __name__ == '__main__':
print("\n===== 信号统计 =====")
for k, v in stats.items():
win_rate = (v['wins'] / v['count'] * 100) if v['count'] > 0 else 0
print(
f"{v['name']} ({k}) - 信号数: {v['count']} | 胜率: {win_rate:.2f}% | 总盈利: {v['total_profit']:.2f}")
# for k, v in stats.items():
# win_rate = (v['wins'] / v['count'] * 100) if v['count'] > 0 else 0
# print(
# f"{v['name']} ({k}) - 信号数: {v['count']} | 胜率: {win_rate:.2f}% | 总盈利: {v['total_profit']:.2f}")