- data_v2.py: исправлен критический баг с лейблами (prices вместо returns) - retest_all.py: ретест всех экспериментов с корректными данными - retest_isolated.py: изолированные тесты астро/техн с временными лагами - regime_analysis.py: анализ прибыльных/убыточных рыночных режимов - shape_confirm_backtest.py: стратегия подтверждения формы + манименеджмент - astro_trade_analysis.py: поиск астро-паттернов в прибыльных сделках - final_backtest.py: финальный бэктест с астро-фильтрами + JSON логирование Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
458 lines
15 KiB
Python
458 lines
15 KiB
Python
"""
|
|
Shape confirmation strategy with money management.
|
|
|
|
Idea:
|
|
1. Model predicts shape for next 7 days
|
|
2. Wait K days, check if actual price follows predicted shape
|
|
3. If correlation > threshold → open position in predicted direction
|
|
4. Hold until end of prediction window (7-K days remaining)
|
|
|
|
Money management:
|
|
- Fixed risk per trade (2% of equity)
|
|
- Stop-loss at max predicted deviation
|
|
- Position sizing based on stop distance
|
|
- Commission: 0.1% per trade (entry + exit)
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import warnings
|
|
|
|
import numpy as np
|
|
import torch
|
|
import torch.nn as nn
|
|
|
|
from data_v2 import fetch_asset
|
|
|
|
warnings.filterwarnings("ignore")
|
|
|
|
# -- Config ------------------------------------------------------------------
|
|
|
|
ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"]
|
|
WINDOW_SIZE = 64
|
|
N_STEPS = 20
|
|
TOTAL_TIME = 0.5
|
|
EPOCHS = 200
|
|
FINETUNE_EPOCHS = 50
|
|
LR = 3e-3
|
|
|
|
# Strategy params
|
|
CONFIRM_DAYS = [1, 2, 3] # K: days to wait for confirmation
|
|
CORR_THRESHOLDS = [0.5, 0.7, 0.9] # minimum correlation to enter
|
|
SHIFT = 7 # prediction horizon
|
|
|
|
# Money management
|
|
INITIAL_EQUITY = 10000.0
|
|
RISK_PER_TRADE = 0.02 # 2% of equity risked per trade
|
|
COMMISSION = 0.001 # 0.1% per side (entry + exit = 0.2% total)
|
|
STOP_MULT = 1.5 # stop-loss at 1.5x predicted range
|
|
|
|
|
|
# -- Model -------------------------------------------------------------------
|
|
|
|
from models import EnhancedRemizovNet
|
|
|
|
|
|
def create_model():
|
|
return EnhancedRemizovNet(
|
|
grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME,
|
|
dx=1.0 / WINDOW_SIZE, use_sde=True,
|
|
)
|
|
|
|
|
|
def train_model(model, windows, targets, epochs):
|
|
g = torch.tensor(windows, dtype=torch.float32)
|
|
y = torch.tensor(targets, dtype=torch.float32)
|
|
opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4)
|
|
crit = nn.MSELoss()
|
|
bs = min(64, len(windows))
|
|
for _ in range(epochs):
|
|
model.train()
|
|
perm = torch.randperm(len(g))
|
|
for i in range(0, len(g), bs):
|
|
idx = perm[i:i + bs]
|
|
opt.zero_grad()
|
|
loss = crit(model(g[idx], stochastic=True), y[idx])
|
|
loss.backward()
|
|
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
|
|
opt.step()
|
|
|
|
|
|
# -- Data Preparation -------------------------------------------------------
|
|
|
|
def prepare_sequential_data(prices: np.ndarray) -> list[dict]:
|
|
"""Create sequential prediction windows (no normalization overlap issues).
|
|
|
|
Each entry:
|
|
- input_window: 64 prices ending at decision point
|
|
- future_prices: next 7 actual prices (for confirmation + PnL)
|
|
- norm_input: z-scored input window (for model)
|
|
- norm_target: z-scored target window (for training)
|
|
"""
|
|
n = len(prices)
|
|
data = []
|
|
|
|
for t in range(WINDOW_SIZE, n - SHIFT, SHIFT): # non-overlapping decisions
|
|
w = prices[t - WINDOW_SIZE:t].copy()
|
|
future = prices[t:t + SHIFT].copy()
|
|
|
|
if len(future) < SHIFT:
|
|
continue
|
|
|
|
mu, std = w.mean(), w.std()
|
|
if std < 1e-10:
|
|
continue
|
|
|
|
# Also need the shifted window for training
|
|
s = prices[t - WINDOW_SIZE + SHIFT:t + SHIFT].copy()
|
|
|
|
data.append({
|
|
"price_at_entry": prices[t - 1],
|
|
"future_prices": future,
|
|
"norm_input": (w - mu) / std,
|
|
"norm_target": (s - mu) / std,
|
|
"mu": mu,
|
|
"std": std,
|
|
})
|
|
|
|
return data
|
|
|
|
|
|
# -- Shape Confirmation Logic -----------------------------------------------
|
|
|
|
def check_shape_confirmation(
|
|
predicted_shape: np.ndarray,
|
|
actual_prices: np.ndarray,
|
|
mu: float,
|
|
std: float,
|
|
confirm_days: int,
|
|
corr_threshold: float,
|
|
) -> dict | None:
|
|
"""Check if actual prices follow predicted shape for first K days.
|
|
|
|
Returns trade signal or None.
|
|
"""
|
|
if confirm_days >= SHIFT:
|
|
return None
|
|
|
|
# Predicted shape is normalized — convert actual prices to same normalization
|
|
actual_norm = (actual_prices[:confirm_days] - mu) / std
|
|
|
|
# The predicted shape's corresponding segment
|
|
# predicted_shape is the full 64-point shifted window
|
|
# The "new" points are the last SHIFT points
|
|
pred_new = predicted_shape[-SHIFT:]
|
|
pred_confirm = pred_new[:confirm_days]
|
|
pred_remaining = pred_new[confirm_days:]
|
|
|
|
if len(pred_confirm) < 2:
|
|
# Need at least 2 points for correlation
|
|
# Use simple sign agreement for K=1
|
|
pred_dir = pred_confirm[0] - predicted_shape[-SHIFT - 1]
|
|
actual_dir = actual_norm[0] - (actual_prices[0] - mu) / std
|
|
# Not enough for correlation, skip
|
|
return None
|
|
|
|
# Correlation between predicted and actual shape
|
|
corr = np.corrcoef(pred_confirm, actual_norm)[0, 1]
|
|
|
|
if np.isnan(corr) or corr < corr_threshold:
|
|
return None
|
|
|
|
# Direction: where does the predicted shape end relative to confirmation point?
|
|
entry_price = actual_prices[confirm_days - 1]
|
|
pred_end_norm = pred_new[-1]
|
|
pred_at_confirm_norm = pred_new[confirm_days - 1]
|
|
pred_direction = pred_end_norm - pred_at_confirm_norm
|
|
|
|
if abs(pred_direction) < 1e-10:
|
|
return None
|
|
|
|
# Convert predicted range to price space for stop-loss
|
|
pred_range_norm = np.max(np.abs(pred_remaining - pred_at_confirm_norm))
|
|
pred_range_price = pred_range_norm * std
|
|
|
|
direction = 1 if pred_direction > 0 else -1
|
|
expected_move = pred_direction * std # in price units
|
|
|
|
return {
|
|
"correlation": corr,
|
|
"direction": direction,
|
|
"entry_price": entry_price,
|
|
"expected_move": expected_move,
|
|
"stop_distance": max(pred_range_price * STOP_MULT, entry_price * 0.005),
|
|
"hold_days": SHIFT - confirm_days,
|
|
"confirm_day": confirm_days,
|
|
}
|
|
|
|
|
|
# -- Backtest Engine ---------------------------------------------------------
|
|
|
|
def backtest_strategy(
|
|
data: list[dict],
|
|
model,
|
|
confirm_days: int,
|
|
corr_threshold: float,
|
|
train_size: int = 80,
|
|
) -> dict:
|
|
"""Run backtest with online learning."""
|
|
|
|
equity = INITIAL_EQUITY
|
|
equity_curve = [equity]
|
|
trades = []
|
|
n = len(data)
|
|
|
|
if n < train_size + 5:
|
|
return {"equity": equity, "trades": [], "equity_curve": equity_curve}
|
|
|
|
# Initial training
|
|
windows = np.array([d["norm_input"] for d in data[:train_size]])
|
|
targets = np.array([d["norm_target"] for d in data[:train_size]])
|
|
train_model(model, windows, targets, EPOCHS)
|
|
|
|
retrain_counter = 0
|
|
|
|
for i in range(train_size, n):
|
|
d = data[i]
|
|
|
|
# Predict shape
|
|
model.eval()
|
|
with torch.no_grad():
|
|
inp = torch.tensor(d["norm_input"], dtype=torch.float32).unsqueeze(0)
|
|
pred = model(inp, stochastic=False).squeeze(0).numpy()
|
|
|
|
# Check confirmation after K days
|
|
signal = check_shape_confirmation(
|
|
pred, d["future_prices"], d["mu"], d["std"],
|
|
confirm_days, corr_threshold,
|
|
)
|
|
|
|
if signal is not None:
|
|
# Position sizing: risk 2% of equity
|
|
stop_dist = signal["stop_distance"]
|
|
risk_amount = equity * RISK_PER_TRADE
|
|
position_size = risk_amount / stop_dist # number of units
|
|
position_value = position_size * signal["entry_price"]
|
|
|
|
# Cap at 100% of equity (no leverage)
|
|
if position_value > equity:
|
|
position_size = equity / signal["entry_price"]
|
|
position_value = equity
|
|
|
|
# Actual exit price (hold_days later)
|
|
exit_idx = signal["confirm_day"] + signal["hold_days"] - 1
|
|
if exit_idx < len(d["future_prices"]):
|
|
exit_price = d["future_prices"][exit_idx]
|
|
else:
|
|
exit_price = d["future_prices"][-1]
|
|
|
|
# Check stop-loss hit during holding period
|
|
hold_prices = d["future_prices"][signal["confirm_day"]:exit_idx + 1]
|
|
stopped = False
|
|
stop_price = signal["entry_price"] - signal["direction"] * stop_dist
|
|
|
|
for hp in hold_prices:
|
|
if signal["direction"] == 1 and hp <= stop_price:
|
|
exit_price = stop_price
|
|
stopped = True
|
|
break
|
|
elif signal["direction"] == -1 and hp >= stop_price:
|
|
exit_price = stop_price
|
|
stopped = True
|
|
break
|
|
|
|
# PnL
|
|
price_change = (exit_price - signal["entry_price"]) * signal["direction"]
|
|
pnl_gross = position_size * price_change
|
|
commission_cost = position_value * COMMISSION * 2 # entry + exit
|
|
pnl_net = pnl_gross - commission_cost
|
|
|
|
equity += pnl_net
|
|
|
|
trades.append({
|
|
"idx": i,
|
|
"direction": "LONG" if signal["direction"] == 1 else "SHORT",
|
|
"entry": signal["entry_price"],
|
|
"exit": exit_price,
|
|
"pnl_pct": pnl_net / (position_value) * 100 if position_value > 0 else 0,
|
|
"pnl_abs": pnl_net,
|
|
"equity": equity,
|
|
"correlation": signal["correlation"],
|
|
"stopped": stopped,
|
|
})
|
|
|
|
equity_curve.append(equity)
|
|
|
|
# Online fine-tune every 10 windows
|
|
retrain_counter += 1
|
|
if retrain_counter >= 10:
|
|
windows = np.array([d["norm_input"] for d in data[:i + 1]])
|
|
targets = np.array([d["norm_target"] for d in data[:i + 1]])
|
|
train_model(model, windows, targets, FINETUNE_EPOCHS)
|
|
retrain_counter = 0
|
|
|
|
return {
|
|
"equity": equity,
|
|
"trades": trades,
|
|
"equity_curve": equity_curve,
|
|
}
|
|
|
|
|
|
# -- Analysis ----------------------------------------------------------------
|
|
|
|
def analyze_trades(trades: list[dict]) -> dict:
|
|
if not trades:
|
|
return {"n_trades": 0}
|
|
|
|
pnls = [t["pnl_pct"] for t in trades]
|
|
wins = [p for p in pnls if p > 0]
|
|
losses = [p for p in pnls if p <= 0]
|
|
stopped = sum(1 for t in trades if t["stopped"])
|
|
|
|
win_rate = len(wins) / len(pnls) if pnls else 0
|
|
avg_win = np.mean(wins) if wins else 0
|
|
avg_loss = np.mean(losses) if losses else 0
|
|
profit_factor = abs(sum(wins) / sum(losses)) if losses and sum(losses) != 0 else float("inf")
|
|
|
|
# Max drawdown from equity curve
|
|
equities = [t["equity"] for t in trades]
|
|
if equities:
|
|
peak = equities[0]
|
|
max_dd = 0
|
|
for e in equities:
|
|
peak = max(peak, e)
|
|
dd = (e - peak) / peak
|
|
max_dd = min(max_dd, dd)
|
|
else:
|
|
max_dd = 0
|
|
|
|
return {
|
|
"n_trades": len(trades),
|
|
"win_rate": win_rate,
|
|
"avg_win": avg_win,
|
|
"avg_loss": avg_loss,
|
|
"profit_factor": profit_factor,
|
|
"total_pnl": sum(pnls),
|
|
"max_drawdown": max_dd,
|
|
"stopped_out": stopped,
|
|
"long_trades": sum(1 for t in trades if t["direction"] == "LONG"),
|
|
"short_trades": sum(1 for t in trades if t["direction"] == "SHORT"),
|
|
}
|
|
|
|
|
|
# -- Main --------------------------------------------------------------------
|
|
|
|
def main():
|
|
print("=" * 75)
|
|
print("SHAPE CONFIRMATION BACKTEST (with money management)")
|
|
print("=" * 75)
|
|
print(f" Initial equity: ${INITIAL_EQUITY:,.0f}")
|
|
print(f" Risk per trade: {RISK_PER_TRADE:.0%}")
|
|
print(f" Commission: {COMMISSION:.1%} per side")
|
|
print(f" Stop-loss: {STOP_MULT}x predicted range")
|
|
|
|
all_results = []
|
|
|
|
for asset in ASSETS:
|
|
import time as _time
|
|
_time.sleep(2) # avoid yfinance rate limit
|
|
try:
|
|
prices, dates = fetch_asset(asset)
|
|
except Exception as e:
|
|
print(f"\n {asset}: FETCH ERROR ({e}), skipping")
|
|
continue
|
|
data = prepare_sequential_data(prices)
|
|
print(f"\n{'=' * 75}")
|
|
print(f" {asset}: {len(data)} decision points "
|
|
f"({dates[WINDOW_SIZE]} to {dates[-1]})")
|
|
print(f"{'=' * 75}")
|
|
|
|
for K in CONFIRM_DAYS:
|
|
for thresh in CORR_THRESHOLDS:
|
|
model = create_model()
|
|
result = backtest_strategy(data, model, K, thresh)
|
|
stats = analyze_trades(result["trades"])
|
|
|
|
final_eq = result["equity"]
|
|
total_ret = (final_eq / INITIAL_EQUITY - 1) * 100
|
|
|
|
config = f"K={K} corr>{thresh}"
|
|
|
|
if stats["n_trades"] == 0:
|
|
print(f" {config:<16s}: NO TRADES")
|
|
all_results.append({
|
|
"asset": asset, "K": K, "thresh": thresh,
|
|
"n_trades": 0, "total_return": 0,
|
|
})
|
|
continue
|
|
|
|
print(f" {config:<16s}: "
|
|
f"${final_eq:>9,.0f} ({total_ret:>+6.1f}%) "
|
|
f"{stats['n_trades']:>3d} trades "
|
|
f"WR={stats['win_rate']:.0%} "
|
|
f"PF={stats['profit_factor']:.2f} "
|
|
f"DD={stats['max_drawdown']:.1%} "
|
|
f"stops={stats['stopped_out']}")
|
|
|
|
all_results.append({
|
|
"asset": asset, "K": K, "thresh": thresh,
|
|
"total_return": total_ret, **stats,
|
|
})
|
|
|
|
# ── Final Summary ──
|
|
print(f"\n\n{'=' * 75}")
|
|
print("FINAL SUMMARY")
|
|
print(f"{'=' * 75}")
|
|
|
|
# Best per asset
|
|
for asset in ASSETS:
|
|
ar = [r for r in all_results if r["asset"] == asset and r["n_trades"] > 5]
|
|
if not ar:
|
|
print(f"\n {asset}: insufficient trades across all configs")
|
|
continue
|
|
|
|
best = max(ar, key=lambda r: r["total_return"])
|
|
worst = min(ar, key=lambda r: r["total_return"])
|
|
|
|
print(f"\n {asset}:")
|
|
print(f" Best: K={best['K']} corr>{best['thresh']}: "
|
|
f"{best['total_return']:+.1f}% "
|
|
f"({best['n_trades']} trades, WR={best['win_rate']:.0%})")
|
|
print(f" Worst: K={worst['K']} corr>{worst['thresh']}: "
|
|
f"{worst['total_return']:+.1f}% "
|
|
f"({worst['n_trades']} trades, WR={worst['win_rate']:.0%})")
|
|
|
|
# Buy-and-hold comparison
|
|
print(f"\n BUY-AND-HOLD comparison:")
|
|
for asset in ASSETS:
|
|
try:
|
|
prices, _ = fetch_asset(asset)
|
|
except Exception:
|
|
continue
|
|
n_data = len(prepare_sequential_data(prices))
|
|
train_start = min(80, n_data)
|
|
if train_start < len(prices) - SHIFT:
|
|
bh_start = prices[WINDOW_SIZE + train_start * SHIFT]
|
|
bh_end = prices[-1]
|
|
bh_ret = (bh_end / bh_start - 1) * 100
|
|
print(f" {asset}: {bh_ret:+.1f}%")
|
|
|
|
# Overall verdict
|
|
profitable = [r for r in all_results if r["n_trades"] > 5 and r["total_return"] > 0]
|
|
total_configs = [r for r in all_results if r["n_trades"] > 5]
|
|
|
|
print(f"\n Profitable configs: {len(profitable)}/{len(total_configs)}")
|
|
|
|
if not profitable:
|
|
print(" VERDICT: Shape confirmation does NOT produce profitable trades.")
|
|
print(" The predicted shape is too smooth/lagged to capture real moves.")
|
|
else:
|
|
avg_ret = np.mean([r["total_return"] for r in profitable])
|
|
print(f" Avg profitable return: {avg_ret:+.1f}%")
|
|
|
|
print(f"\n{'=' * 75}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|