Files
codex_jxs_code/strategy/run_bb_202602_detail.py
2026-02-26 16:34:30 +08:00

68 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""
bb_trade.py 策略回测 — 2026年2月输出详细交易明细
200U 本金 | 1% 仓位/单 | 万五手续费 | 90% 返佣次日8点到账
按北京时间加载数据 (与交易所/网页显示一致)
"""
import sys
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parents[1]))
import pandas as pd
from pathlib import Path
from strategy.bb_backtest import BBConfig, run_bb_backtest
from strategy.data_loader import load_klines
out_dir = Path(__file__).resolve().parent / "results"
out_dir.mkdir(parents=True, exist_ok=True)
# 按北京时间加载 2026-02-01 00:00 ~ 2026-03-01 00:00
df = load_klines('5m', '2026-02-01', '2026-03-01', tz='Asia/Shanghai')
cfg = BBConfig(
bb_period=10, bb_std=2.5, leverage=50, initial_capital=200.0,
margin_pct=0.01, max_daily_loss=50.0, fee_rate=0.0005,
rebate_pct=0.90, rebate_hour_utc=0, pyramid_enabled=False, # 不加仓
pyramid_step=0.01, pyramid_max=3, slippage_pct=0.0, liq_enabled=True,
cross_margin=True, # 全仓:仅权益<=0 时爆仓
fill_at_close=True, # 真实成交:检测到信号后在 K 线收盘价成交
)
r = run_bb_backtest(df, cfg)
# 数据库/回测使用 UTC转为北京时间输出
def to_beijing(ts):
if hasattr(ts, 'tz_localize'):
return ts.tz_localize('UTC').tz_convert('Asia/Shanghai').strftime('%Y-%m-%d %H:%M:%S')
return str(ts)[:19]
# 构建交易明细 DataFrame
rows = []
for i, t in enumerate(r.trades, 1):
rows.append({
"序号": i,
"方向": "做多" if t.side == "long" else "做空",
"开仓时间": to_beijing(t.entry_time),
"平仓时间": to_beijing(t.exit_time),
"开仓价": round(t.entry_price, 2),
"平仓价": round(t.exit_price, 2),
"保证金": round(t.margin, 2),
"杠杆": t.leverage,
"数量": round(t.qty, 4),
"毛盈亏": round(t.gross_pnl, 2),
"手续费": round(t.fee, 2),
"净盈亏": round(t.net_pnl, 2),
})
trade_df = pd.DataFrame(rows)
# 保存 CSV
csv_path = out_dir / "bb_202602_trade_detail.csv"
trade_df.to_csv(csv_path, index=False, encoding="utf-8-sig")
print(f"交易明细已保存: {csv_path}")
# 打印到控制台
print("\n" + "=" * 150)
print(f" 交易明细 (共 {len(r.trades)} 笔)")
print("=" * 150)
print(trade_df.to_string(index=False))