feat: exp27-29 — скан новых пар, volume тест, timeframe sweep

exp27: 25 пар из топ-50 → NEAR/TIA/PEPE с edge, но реалистичный
  бэктест показал слабее ADA+DOGE (+$122 vs +$289)
exp28: volume/range анализ → нулевой эффект для ADA/DOGE
exp29: 20 пар × 6 TF → 4h единственный рабочий таймфрейм

Вывод: текущий прод (ADA+DOGE, 4h) остаётся оптимальным

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-11 08:07:38 +10:00
co-authored by Claude Opus 4.6
parent 05da57e02f
commit 45835e3f2b
10 changed files with 3993 additions and 0 deletions
@@ -0,0 +1,568 @@
"""Exp27b: Realistic backtest for NEAR, TIA, PEPE.
Same methodology as exp26j:
- Bybit margin 2x, commission 0.1%, interest 0.02%/day
- Trailing stop, cooldown, confidence >= 1.5, shape confirmation
- 30% train / 70% test
- Retrain modes: off, losses_only
- Capital $254
Configs: solo per asset + combined portfolio.
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import json
import numpy as np
import pandas as pd
import torch
import backtrader as bt
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.core.net import EnhancedRemizovNet
from remizov_trader.core.signals import fetch_ohlcv_ccxt
from common.metrics import save_results
TOTAL_CAPITAL = 254.0
SHIFT = 7
MIN_CONFIDENCE = 1.5
TRAIN_RATIO = 0.3
TF_HOURS = {"4h": 4}
INTEREST_RATE_DAILY = 0.0002
COMMISSION_PCT = 0.001
MARKET_ORDER_BUFFER = 0.02
# CVR for altcoins (conservative estimate)
DEFAULT_CVR = 0.85
DEFAULT_SPOT_IM = 0.05
# Best params from exp27 scan
ASSETS_META = {
"NEAR": {"symbol": "NEAR/USDC", "ticker": "NEAR-USD", "ws": 64, "K": 2},
"TIA": {"symbol": "TIA/USDC", "ticker": "TIA-USD", "ws": 64, "K": 2},
"PEPE": {"symbol": "PEPE/USDC", "ticker": "PEPE-USD", "ws": 64, "K": 3},
}
CONFIGS = [
{"name": "near_only",
"assets": [
{"ticker": "NEAR-USD", "tf": "4h", "ws": 64, "K": 2, "leverage": 2, "weight": 1.00},
]},
{"name": "tia_only",
"assets": [
{"ticker": "TIA-USD", "tf": "4h", "ws": 64, "K": 2, "leverage": 2, "weight": 1.00},
]},
{"name": "pepe_only",
"assets": [
{"ticker": "PEPE-USD", "tf": "4h", "ws": 64, "K": 3, "leverage": 2, "weight": 1.00},
]},
{"name": "top3_equal",
"assets": [
{"ticker": "NEAR-USD", "tf": "4h", "ws": 64, "K": 2, "leverage": 2, "weight": 0.333},
{"ticker": "TIA-USD", "tf": "4h", "ws": 64, "K": 2, "leverage": 2, "weight": 0.333},
{"ticker": "PEPE-USD", "tf": "4h", "ws": 64, "K": 3, "leverage": 2, "weight": 0.334},
]},
{"name": "all5_equal",
"assets": [
{"ticker": "NEAR-USD", "tf": "4h", "ws": 64, "K": 2, "leverage": 2, "weight": 0.20},
{"ticker": "TIA-USD", "tf": "4h", "ws": 64, "K": 2, "leverage": 2, "weight": 0.20},
{"ticker": "PEPE-USD", "tf": "4h", "ws": 64, "K": 3, "leverage": 2, "weight": 0.20},
{"ticker": "ADA-USD", "tf": "4h", "ws": 64, "K": 3, "leverage": 2, "weight": 0.20},
{"ticker": "DOGE-USD", "tf": "4h", "ws": 48, "K": 2, "leverage": 2, "weight": 0.20},
]},
]
# ── Backtest engine (same as exp26j) ──────────────────────
from dataclasses import dataclass
@dataclass
class Pos:
ticker: str
direction: int
entry_price: float
entry_bar: int
stop_price: float
stop_dist: float
best_price: float
pos_size: float
pos_value: float
margin_locked: float
borrowed: float
haircut: float
spot_im: float
@dataclass
class State:
wins: int = 0
trades_count: int = 0
consecutive_losses: int = 0
def _calc_capital(pos_value, leverage, ticker):
margin = pos_value / leverage
borrowed = pos_value - margin
cvr = DEFAULT_CVR
haircut = (1.0 - cvr) * pos_value
spot_im = borrowed * DEFAULT_SPOT_IM
buf = pos_value * MARKET_ORDER_BUFFER
return {"margin_needed": margin, "borrowed": borrowed,
"haircut": haircut, "spot_im": spot_im,
"total_frozen": margin + haircut + spot_im + buf}
class RemizovStrategy(bt.Strategy):
params = (
('asset_meta', {}),
('min_confidence', MIN_CONFIDENCE),
('retrain_mode', 'losses_only'),
)
def __init__(self):
self.free_usdc = TOTAL_CAPITAL
self.open_pos = {}
self.last_stop_bar = {}
self.states = {}
self.trades = []
self.per_asset = {}
self.skip = {"margin": 0, "cooldown": 0, "short": 0,
"low_conf": 0, "retrain": 0, "no_shape": 0}
self.peak_eq = TOTAL_CAPITAL
self.max_dd = 0.0
self.total_interest = 0.0
self.total_commission = 0.0
self._prev_len = {}
self.equity_curve = []
for d in self.datas:
t = d._name
self._prev_len[t] = 0
self.states[t] = State()
self.per_asset[t] = []
def prenext(self):
self.next()
def next(self):
for d in self.datas:
ticker = d._name
cur_len = len(d)
if cur_len == self._prev_len[ticker]:
continue
self._prev_len[ticker] = cur_len
bar = cur_len - 1
meta = self.p.asset_meta[ticker]
if bar < meta["test_start"]:
continue
price = float(d.close[0])
prices = meta["prices"]
if ticker in self.open_pos:
self._check_stop(ticker, bar, price, meta)
if bar in meta["signal_bars"]:
self._maybe_retrain(ticker, bar, meta)
if ticker not in self.open_pos:
self._check_signal(ticker, bar, price, meta)
eq = self.free_usdc + sum(p.margin_locked for p in self.open_pos.values())
self.equity_curve.append(eq)
self.peak_eq = max(self.peak_eq, eq)
dd = (self.peak_eq - eq) / self.peak_eq if self.peak_eq > 0 else 0
self.max_dd = max(self.max_dd, dd)
def _check_stop(self, ticker, bar, price, meta):
pos = self.open_pos[ticker]
pos.best_price, pos.stop_price = risk.update_trailing_stop(
price, pos.best_price, pos.stop_price,
pos.stop_dist, pos.direction)
if not risk.is_stopped(price, pos.stop_price, pos.direction):
return
bars_held = bar - pos.entry_bar
bar_h = TF_HOURS.get(meta["tf"], 4)
pnl_gross = pos.pos_size * (price - pos.entry_price) * pos.direction
commission = pos.pos_value * COMMISSION_PCT * 2
interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_h / 24
self.total_interest += interest
self.total_commission += commission
pnl = pnl_gross - commission - interest
self.free_usdc += pos.margin_locked + pnl
del self.open_pos[ticker]
self.last_stop_bar[ticker] = bar
trade = {"ticker": ticker, "pnl_net": pnl, "pnl_gross": pnl_gross,
"commission": commission, "interest": interest,
"bars_held": bars_held, "equity_at_entry": pos.margin_locked}
self.trades.append(trade)
self.per_asset[ticker].append(trade)
st = self.states[ticker]
st.trades_count += 1
if pnl > 0:
st.wins += 1
st.consecutive_losses = 0
else:
st.consecutive_losses += 1
def _maybe_retrain(self, ticker, bar, meta):
if self.p.retrain_mode == "off":
return
st = self.states[ticker]
if self.p.retrain_mode == "losses_only":
if st.consecutive_losses >= 3:
data = signals.prepare_windows(meta["prices"][:bar + 1], meta["ws"], SHIFT)
if len(data) >= 20:
recent = data[-200:]
w = np.array([d["norm_input"] for d in recent])
t = np.array([d["norm_target"] for d in recent])
model_mod.train(meta["model"], w, t, epochs=20, lr=0.003 * 0.3)
st.consecutive_losses = 0
self.skip["retrain"] += 1
def _check_signal(self, ticker, bar, price, meta):
prices = meta["prices"]
ws, K = meta["ws"], meta["K"]
if bar < ws + K:
return
if ticker in self.last_stop_bar:
if bar - self.last_stop_bar[ticker] < SHIFT:
self.skip["cooldown"] += 1
return
w = prices[bar - ws - K: bar - K].copy()
confirm = prices[bar - K: bar].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
return
pred = model_mod.predict(meta["model"], (w - mu) / std)
pred_new = pred[-SHIFT:]
_, stop_mult = risk.regime_adaptive_params(prices, bar, K)
corr_thresh = risk.adaptive_corr_threshold(
0.5, self.states[ticker].wins, self.states[ticker].trades_count)
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, corr_thresh)
if not confirmed:
self.skip["no_shape"] += 1
return
atr = risk.compute_atr(prices, bar)
if atr > 0:
pred_denorm = pred_new * std + mu
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
conf = abs(corr) * (amp / atr)
if conf < self.p.min_confidence:
self.skip["low_conf"] += 1
return
direction = signals.get_direction(pred_new, K)
if direction is None:
return
if direction == -1:
self.skip["short"] += 1
return
leverage = meta["leverage"]
eq = self.free_usdc + sum(p.margin_locked for p in self.open_pos.values())
if eq <= 0:
return
pos_value = eq * meta["weight"] * leverage
if pos_value < 5.0:
return
req = _calc_capital(pos_value, leverage, ticker)
avail = self.free_usdc - sum(
p.haircut + p.spot_im for p in self.open_pos.values())
if avail < req["total_frozen"]:
cvr = DEFAULT_CVR
im = DEFAULT_SPOT_IM
freeze = 1 / leverage + (1 - cvr) + (1 - 1 / leverage) * im + MARKET_ORDER_BUFFER
max_pv = avail / freeze
if max_pv < 5.0:
self.skip["margin"] += 1
return
pos_value = max_pv
req = _calc_capital(pos_value, leverage, ticker)
stop_dist = max(atr * stop_mult * 0.5, price * 0.005)
self.free_usdc -= req["margin_needed"]
self.open_pos[ticker] = Pos(
ticker=ticker, direction=direction,
entry_price=price, entry_bar=bar,
stop_price=price - direction * stop_dist,
stop_dist=stop_dist, best_price=price,
pos_size=pos_value / price, pos_value=pos_value,
margin_locked=req["margin_needed"],
borrowed=req["borrowed"],
haircut=req["haircut"], spot_im=req["spot_im"],
)
def stop(self):
for ticker, pos in list(self.open_pos.items()):
meta = self.p.asset_meta[ticker]
prices = meta["prices"]
last_bar = meta["last_test_bar"]
last_price = float(prices[last_bar])
bar_h = TF_HOURS.get(meta["tf"], 4)
bars_held = last_bar - pos.entry_bar
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
commission = pos.pos_value * COMMISSION_PCT * 2
interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_h / 24
pnl = pnl_gross - commission - interest
self.free_usdc += pos.margin_locked + pnl
trade = {"ticker": ticker, "pnl_net": pnl, "pnl_gross": pnl_gross,
"commission": commission, "interest": interest,
"bars_held": bars_held, "equity_at_entry": pos.margin_locked}
self.trades.append(trade)
self.per_asset[ticker].append(trade)
# ── Data fetching ─────────────────────────────────────────
def _fetch_asset(symbol, ticker, tf="4h"):
"""Fetch OHLCV from Bybit."""
ohlcv, dates = fetch_ohlcv_ccxt(symbol, tf, "max")
if ohlcv is None or len(ohlcv) < 500:
return None
prices = ohlcv[:, 3]
dates_np = np.array([str(d) for d in dates])
return {"prices": prices, "ohlcv": ohlcv, "dates": dates_np}
# ── Run config ────────────────────────────────────────────
def _run_config(config, dataset, retrain_mode):
assets = config["assets"]
name = config["name"]
prepared = {}
for a in assets:
ticker = a["ticker"]
if ticker not in dataset:
continue
prices = dataset[ticker]["prices"]
dates = dataset[ticker]["dates"]
ohlcv = dataset[ticker].get("ohlcv")
data = signals.prepare_windows(prices, a["ws"], SHIFT)
n_train = max(int(len(data) * TRAIN_RATIO), 20)
test_data = data[n_train:]
if ohlcv is not None and len(ohlcv) == len(prices):
df = pd.DataFrame({
'open': ohlcv[:, 0], 'high': ohlcv[:, 1],
'low': ohlcv[:, 2], 'close': ohlcv[:, 3],
'volume': 0.0, 'openinterest': 0.0,
}, index=pd.to_datetime(dates))
else:
df = pd.DataFrame({
'open': prices, 'high': prices, 'low': prices, 'close': prices,
'volume': 0.0, 'openinterest': 0.0,
}, index=pd.to_datetime(dates))
prepared[ticker] = {
"prices": prices, "dates": dates, "df": df,
"tf": a["tf"], "ws": a["ws"], "K": a["K"],
"leverage": a["leverage"], "weight": a["weight"],
"train_data": data[:n_train], "test_start": test_data[0]["price_idx"],
"last_test_bar": test_data[-1]["price_idx"],
"signal_bars": {d["price_idx"] for d in test_data},
}
# Train models
asset_meta = {}
for ticker, p in prepared.items():
torch.manual_seed(42)
np.random.seed(42)
mdl = EnhancedRemizovNet(grid_size=p["ws"], n_steps=20, total_time=0.5,
dx=1.0 / p["ws"], use_sde=True)
model_mod.train(mdl,
np.array([d["norm_input"] for d in p["train_data"]]),
np.array([d["norm_target"] for d in p["train_data"]]),
200, 0.003)
asset_meta[ticker] = {
"model": mdl, "prices": p["prices"], "dates": p["dates"],
"tf": p["tf"], "ws": p["ws"], "K": p["K"],
"leverage": p["leverage"], "weight": p["weight"],
"test_start": p["test_start"], "last_test_bar": p["last_test_bar"],
"signal_bars": p["signal_bars"],
}
# Align data feeds to common date range for portfolio configs
# Find common start/end dates
all_dfs = {t: p["df"] for t, p in prepared.items()}
if len(all_dfs) > 1:
common_start = max(df.index[0] for df in all_dfs.values())
common_end = min(df.index[-1] for df in all_dfs.values())
for t in all_dfs:
all_dfs[t] = all_dfs[t].loc[common_start:common_end]
cerebro = bt.Cerebro()
cerebro.broker.setcash(1_000_000)
cerebro.broker.setcommission(commission=0)
for ticker in [a["ticker"] for a in assets]:
if ticker not in prepared:
continue
df = all_dfs.get(ticker, prepared[ticker]["df"])
bt_data = bt.feeds.PandasData(dataname=df)
cerebro.adddata(bt_data, name=ticker)
cerebro.addstrategy(RemizovStrategy, asset_meta=asset_meta,
retrain_mode=retrain_mode)
results = cerebro.run()
strat = results[0]
final_eq = strat.free_usdc
total_pnl = final_eq - TOTAL_CAPITAL
n = len(strat.trades)
wins = sum(1 for t in strat.trades if t["pnl_net"] > 0)
if n >= 2:
rets = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in strat.trades if t["equity_at_entry"] > 0])
if len(rets) >= 2 and np.std(rets) > 0:
all_dates = []
for m in asset_meta.values():
all_dates.extend(m["dates"].tolist())
from datetime import date as dt
first = dt.fromisoformat(str(min(all_dates))[:10])
last = dt.fromisoformat(str(max(all_dates))[:10])
years = max((last - first).days / 365.25, 0.1)
tpy = n / years
sharpe = float(np.mean(rets) / np.std(rets) * np.sqrt(tpy))
else:
sharpe = 0
else:
sharpe = 0
per_asset = {}
for a in assets:
ticker = a["ticker"]
tds = strat.per_asset.get(ticker, [])
if tds:
pnl = sum(t["pnl_net"] for t in tds)
w = sum(1 for t in tds if t["pnl_net"] > 0)
gross = sum(t.get("pnl_gross", 0) for t in tds)
comm = sum(t.get("commission", 0) for t in tds)
intr = sum(t.get("interest", 0) for t in tds)
per_asset[ticker] = {
"pnl_net": round(pnl, 2), "pnl_gross": round(gross, 2),
"commission": round(comm, 2), "interest": round(intr, 2),
"trades": len(tds), "wins": w,
"wr": round(w / len(tds) * 100, 1),
}
return {
"name": f"{name}|{retrain_mode}",
"total_pnl": round(total_pnl, 2),
"final_eq": round(final_eq, 2),
"return_pct": round(total_pnl / TOTAL_CAPITAL * 100, 1),
"sharpe": round(sharpe, 2),
"max_dd": round(strat.max_dd * 100, 1),
"trades": n,
"wins": wins,
"wr": round(wins / n * 100, 1) if n else 0,
"total_commission": round(strat.total_commission, 2),
"total_interest": round(strat.total_interest, 2),
"retrains": strat.skip["retrain"],
"skipped": strat.skip,
"per_asset": per_asset,
}
def main():
results_dir = Path(__file__).parent / "results"
print("=" * 80)
print("EXP27b: REALISTIC BACKTEST — NEAR, TIA, PEPE (+ADA/DOGE combo)")
print("=" * 80)
print(f"Capital: ${TOTAL_CAPITAL} | Leverage: 2x | Bybit margin model")
print(f"Commission: {COMMISSION_PCT*100:.1f}% | Interest: {INTEREST_RATE_DAILY*100:.2f}%/day")
# Fetch all needed data
print("\nFetching data...")
dataset = {}
# New pairs
for name, meta in ASSETS_META.items():
print(f" {meta['ticker']}...", end=" ", flush=True)
d = _fetch_asset(meta["symbol"], meta["ticker"])
if d:
dataset[meta["ticker"]] = d
print(f"{len(d['prices'])} bars")
else:
print("FAILED")
# Also fetch ADA and DOGE for all5 config
from common.dataset import load_or_fetch
old_dataset = load_or_fetch("default")
for t in ["ADA-USD", "DOGE-USD"]:
if t in old_dataset:
dataset[t] = old_dataset[t]
print(f" {t}... {len(old_dataset[t]['prices'])} bars (cached)")
all_results = []
for config in CONFIGS:
for retrain_mode in ["off", "losses_only"]:
# Check all assets available
missing = [a["ticker"] for a in config["assets"] if a["ticker"] not in dataset]
if missing:
print(f"\n [{config['name']}|{retrain_mode}] SKIP: missing {missing}")
continue
label = f"{config['name']}|{retrain_mode}"
assets_str = "+".join(a["ticker"].split("-")[0] for a in config["assets"])
print(f"\n [{label}] {assets_str}...", end=" ", flush=True)
r = _run_config(config, dataset, retrain_mode)
all_results.append(r)
print(f"PnL=${r['total_pnl']:+.0f} ({r['return_pct']:+.1f}%) "
f"Sharpe={r['sharpe']:.2f} DD={r['max_dd']:.1f}% "
f"Trades={r['trades']} WR={r['wr']:.1f}%")
for ticker, pa in r["per_asset"].items():
print(f" {ticker:10s} PnL=${pa['pnl_net']:+.1f} "
f"(comm=${pa['commission']:.1f}) "
f"trades={pa['trades']} WR={pa['wr']:.1f}%")
print(f"\n{'═' * 80}")
print("SUMMARY")
print(f"{'═' * 80}")
print(f" {'Config':<28s} {'PnL$':>6s} {'Ret%':>6s} {'Shrp':>5s} "
f"{'DD%':>5s} {'Trds':>5s} {'WR%':>5s} {'Comm$':>6s}")
print(f" {'-' * 70}")
for r in all_results:
print(f" {r['name']:<28s} ${r['total_pnl']:>+5.0f} "
f"{r['return_pct']:>+5.1f}% {r['sharpe']:>5.2f} "
f"{r['max_dd']:>4.1f}% {r['trades']:>5d} {r['wr']:>4.1f}% "
f"${r['total_commission']:>5.1f}")
best = max(all_results, key=lambda r: r["sharpe"])
print(f"\n BEST: {best['name']} — PnL=${best['total_pnl']:+.0f} "
f"({best['return_pct']:+.1f}%) Sharpe={best['sharpe']:.2f}")
path = save_results({"results": all_results}, results_dir, "exp27b_realistic")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()
@@ -0,0 +1,259 @@
{
"results": [
{
"ticker": "AVAX-USD",
"status": "no_edge"
},
{
"ticker": "LINK-USD",
"status": "no_edge"
},
{
"ticker": "MATIC-USD",
"status": "insufficient_data",
"bars": 0
},
{
"ticker": "UNI-USD",
"status": "no_edge"
},
{
"ticker": "ATOM-USD",
"ws": 64,
"K": 3,
"bars": 3358,
"amplitude": {
"r": 0.2102,
"p": 0.0001,
"n": 329
},
"conf_pnl": {
"mean_pnl": 0.8509,
"n": 40,
"wr": 42.5
},
"bootstrap": {
"p_positive": 94.9,
"ci_lo": -0.1731,
"ci_hi": 1.9441,
"n": 40,
"mean": 0.8509
},
"walk_forward": {
"folds": [
0.1695,
-0.8165
],
"positive": 1,
"total": 2,
"stable": false
},
"score": 0.8075,
"status": "tested"
},
{
"ticker": "FIL-USD",
"status": "no_edge"
},
{
"ticker": "LTC-USD",
"ws": 64,
"K": 2,
"bars": 6000,
"amplitude": {
"r": 0.2337,
"p": 0.0,
"n": 593
},
"conf_pnl": {
"mean_pnl": 0.524,
"n": 94,
"wr": 40.4
},
"bootstrap": {
"p_positive": 91.1,
"ci_lo": -0.1828,
"ci_hi": 1.2812,
"n": 94,
"mean": 0.524
},
"walk_forward": {
"folds": [
0.8348,
0.4131
],
"positive": 2,
"total": 2,
"stable": true
},
"score": 0.4774,
"status": "tested"
},
{
"ticker": "NEAR-USD",
"ws": 64,
"K": 2,
"bars": 3394,
"amplitude": {
"r": 0.1537,
"p": 0.0049,
"n": 333
},
"conf_pnl": {
"mean_pnl": 1.3441,
"n": 59,
"wr": 49.2
},
"bootstrap": {
"p_positive": 97.8,
"ci_lo": 0.0212,
"ci_hi": 3.2827,
"n": 59,
"mean": 1.3441
},
"walk_forward": {
"folds": [
0.3418,
1.065
],
"positive": 2,
"total": 2,
"stable": true
},
"score": 1.3145,
"status": "tested"
},
{
"ticker": "APT-USD",
"status": "no_edge"
},
{
"ticker": "OP-USD",
"status": "no_edge"
},
{
"ticker": "ARB-USD",
"status": "no_edge"
},
{
"ticker": "SUI-USD",
"status": "no_edge"
},
{
"ticker": "PEPE-USD",
"ws": 64,
"K": 3,
"bars": 3442,
"amplitude": {
"r": 0.2672,
"p": 0.0,
"n": 338
},
"conf_pnl": {
"mean_pnl": 0.9907,
"n": 50,
"wr": 40.0
},
"bootstrap": {
"p_positive": 95.9,
"ci_lo": -0.1486,
"ci_hi": 2.1937,
"n": 50,
"mean": 0.9907
},
"walk_forward": {
"folds": [
0.257,
0.3079
],
"positive": 2,
"total": 2,
"stable": true
},
"score": 0.9501,
"status": "tested"
},
{
"ticker": "SHIB-USD",
"status": "no_edge"
},
{
"ticker": "WIF-USD",
"status": "no_edge"
},
{
"ticker": "FET-USD",
"status": "no_edge"
},
{
"ticker": "RENDER-USD",
"status": "insufficient_data",
"bars": 1601
},
{
"ticker": "INJ-USD",
"status": "no_edge"
},
{
"ticker": "SEI-USD",
"status": "no_edge"
},
{
"ticker": "TIA-USD",
"ws": 64,
"K": 2,
"bars": 3352,
"amplitude": {
"r": 0.544,
"p": 0.0,
"n": 329
},
"conf_pnl": {
"mean_pnl": 1.0743,
"n": 57,
"wr": 36.8
},
"bootstrap": {
"p_positive": 95.3,
"ci_lo": -0.1308,
"ci_hi": 2.4066,
"n": 57,
"mean": 1.0743
},
"walk_forward": {
"folds": [
1.7949,
0.8137
],
"positive": 2,
"total": 2,
"stable": true
},
"score": 1.0238,
"status": "tested"
},
{
"ticker": "STX-USD",
"status": "insufficient_data",
"bars": 1474
},
{
"ticker": "IMX-USD",
"status": "insufficient_data",
"bars": 0
},
{
"ticker": "SAND-USD",
"status": "no_edge"
},
{
"ticker": "MANA-USD",
"status": "no_edge"
},
{
"ticker": "CRV-USD",
"status": "insufficient_data",
"bars": 1601
}
]
}
@@ -0,0 +1,442 @@
{
"results": [
{
"name": "near_only|off",
"total_pnl": 115.17,
"final_eq": 369.17,
"return_pct": 45.3,
"sharpe": 0.67,
"max_dd": 28.8,
"trades": 42,
"wins": 18,
"wr": 42.9,
"total_commission": 43.13,
"total_interest": 1.5,
"retrains": 0,
"skipped": {
"margin": 0,
"cooldown": 42,
"short": 38,
"low_conf": 70,
"retrain": 0,
"no_shape": 133
},
"per_asset": {
"NEAR-USD": {
"pnl_net": 115.17,
"pnl_gross": 159.8,
"commission": 43.13,
"interest": 1.5,
"trades": 42,
"wins": 18,
"wr": 42.9
}
}
},
{
"name": "near_only|losses_only",
"total_pnl": 121.76,
"final_eq": 375.76,
"return_pct": 47.9,
"sharpe": 0.7,
"max_dd": 27.5,
"trades": 43,
"wins": 19,
"wr": 44.2,
"total_commission": 44.71,
"total_interest": 1.54,
"retrains": 3,
"skipped": {
"margin": 0,
"cooldown": 43,
"short": 42,
"low_conf": 64,
"retrain": 3,
"no_shape": 133
},
"per_asset": {
"NEAR-USD": {
"pnl_net": 121.76,
"pnl_gross": 168.0,
"commission": 44.71,
"interest": 1.54,
"trades": 43,
"wins": 19,
"wr": 44.2
}
}
},
{
"name": "tia_only|off",
"total_pnl": 30.51,
"final_eq": 284.51,
"return_pct": 12.0,
"sharpe": 0.39,
"max_dd": 19.6,
"trades": 41,
"wins": 15,
"wr": 36.6,
"total_commission": 33.15,
"total_interest": 1.26,
"retrains": 0,
"skipped": {
"margin": 0,
"cooldown": 41,
"short": 26,
"low_conf": 69,
"retrain": 0,
"no_shape": 144
},
"per_asset": {
"TIA-USD": {
"pnl_net": 30.51,
"pnl_gross": 64.92,
"commission": 33.15,
"interest": 1.26,
"trades": 41,
"wins": 15,
"wr": 36.6
}
}
},
{
"name": "tia_only|losses_only",
"total_pnl": 118.52,
"final_eq": 372.52,
"return_pct": 46.7,
"sharpe": 0.73,
"max_dd": 19.6,
"trades": 42,
"wins": 14,
"wr": 33.3,
"total_commission": 37.25,
"total_interest": 1.47,
"retrains": 4,
"skipped": {
"margin": 0,
"cooldown": 42,
"short": 27,
"low_conf": 63,
"retrain": 4,
"no_shape": 146
},
"per_asset": {
"TIA-USD": {
"pnl_net": 118.52,
"pnl_gross": 157.23,
"commission": 37.25,
"interest": 1.47,
"trades": 42,
"wins": 14,
"wr": 33.3
}
}
},
{
"name": "pepe_only|off",
"total_pnl": 10.96,
"final_eq": 264.96,
"return_pct": 4.3,
"sharpe": 0.23,
"max_dd": 17.7,
"trades": 40,
"wins": 14,
"wr": 35.0,
"total_commission": 30.3,
"total_interest": 1.01,
"retrains": 0,
"skipped": {
"margin": 0,
"cooldown": 39,
"short": 23,
"low_conf": 43,
"retrain": 0,
"no_shape": 186
},
"per_asset": {
"PEPE-USD": {
"pnl_net": 10.96,
"pnl_gross": 42.27,
"commission": 30.3,
"interest": 1.01,
"trades": 40,
"wins": 14,
"wr": 35.0
}
}
},
{
"name": "pepe_only|losses_only",
"total_pnl": 6.98,
"final_eq": 260.98,
"return_pct": 2.7,
"sharpe": 0.19,
"max_dd": 17.7,
"trades": 42,
"wins": 15,
"wr": 35.7,
"total_commission": 31.4,
"total_interest": 1.02,
"retrains": 7,
"skipped": {
"margin": 0,
"cooldown": 41,
"short": 28,
"low_conf": 38,
"retrain": 7,
"no_shape": 182
},
"per_asset": {
"PEPE-USD": {
"pnl_net": 6.98,
"pnl_gross": 39.41,
"commission": 31.4,
"interest": 1.02,
"trades": 42,
"wins": 15,
"wr": 35.7
}
}
},
{
"name": "top3_equal|off",
"total_pnl": -11.64,
"final_eq": 242.36,
"return_pct": -4.6,
"sharpe": 0.21,
"max_dd": 21.3,
"trades": 120,
"wins": 43,
"wr": 35.8,
"total_commission": 39.69,
"total_interest": 1.54,
"retrains": 0,
"skipped": {
"margin": 0,
"cooldown": 120,
"short": 83,
"low_conf": 184,
"retrain": 0,
"no_shape": 448
},
"per_asset": {
"NEAR-USD": {
"pnl_net": -44.77,
"pnl_gross": -30.2,
"commission": 14.0,
"interest": 0.57,
"trades": 42,
"wins": 13,
"wr": 31.0
},
"TIA-USD": {
"pnl_net": -3.38,
"pnl_gross": 10.33,
"commission": 13.21,
"interest": 0.49,
"trades": 41,
"wins": 15,
"wr": 36.6
},
"PEPE-USD": {
"pnl_net": 36.51,
"pnl_gross": 49.46,
"commission": 12.48,
"interest": 0.48,
"trades": 37,
"wins": 15,
"wr": 40.5
}
}
},
{
"name": "top3_equal|losses_only",
"total_pnl": 6.43,
"final_eq": 260.43,
"return_pct": 2.5,
"sharpe": 0.38,
"max_dd": 21.3,
"trades": 125,
"wins": 43,
"wr": 34.4,
"total_commission": 41.82,
"total_interest": 1.63,
"retrains": 15,
"skipped": {
"margin": 0,
"cooldown": 125,
"short": 97,
"low_conf": 159,
"retrain": 15,
"no_shape": 448
},
"per_asset": {
"NEAR-USD": {
"pnl_net": -49.92,
"pnl_gross": -34.38,
"commission": 14.92,
"interest": 0.61,
"trades": 44,
"wins": 14,
"wr": 31.8
},
"TIA-USD": {
"pnl_net": 31.82,
"pnl_gross": 45.91,
"commission": 13.57,
"interest": 0.52,
"trades": 42,
"wins": 14,
"wr": 33.3
},
"PEPE-USD": {
"pnl_net": 24.53,
"pnl_gross": 38.35,
"commission": 13.32,
"interest": 0.5,
"trades": 39,
"wins": 15,
"wr": 38.5
}
}
},
{
"name": "all5_equal|off",
"total_pnl": -2.09,
"final_eq": 251.91,
"return_pct": -0.8,
"sharpe": 0.05,
"max_dd": 13.3,
"trades": 165,
"wins": 61,
"wr": 37.0,
"total_commission": 34.13,
"total_interest": 1.39,
"retrains": 0,
"skipped": {
"margin": 0,
"cooldown": 164,
"short": 156,
"low_conf": 240,
"retrain": 0,
"no_shape": 645
},
"per_asset": {
"NEAR-USD": {
"pnl_net": -27.3,
"pnl_gross": -18.28,
"commission": 8.66,
"interest": 0.36,
"trades": 42,
"wins": 13,
"wr": 31.0
},
"TIA-USD": {
"pnl_net": 10.99,
"pnl_gross": 19.64,
"commission": 8.33,
"interest": 0.32,
"trades": 41,
"wins": 15,
"wr": 36.6
},
"PEPE-USD": {
"pnl_net": 23.91,
"pnl_gross": 31.89,
"commission": 7.68,
"interest": 0.3,
"trades": 37,
"wins": 15,
"wr": 40.5
},
"ADA-USD": {
"pnl_net": 3.15,
"pnl_gross": 7.15,
"commission": 3.86,
"interest": 0.14,
"trades": 18,
"wins": 8,
"wr": 44.4
},
"DOGE-USD": {
"pnl_net": -12.83,
"pnl_gross": -2.2,
"commission": 5.81,
"interest": 4.83,
"trades": 27,
"wins": 10,
"wr": 37.0
}
}
},
{
"name": "all5_equal|losses_only",
"total_pnl": 7.8,
"final_eq": 261.8,
"return_pct": 3.1,
"sharpe": 0.16,
"max_dd": 13.3,
"trades": 170,
"wins": 61,
"wr": 35.9,
"total_commission": 35.35,
"total_interest": 1.44,
"retrains": 18,
"skipped": {
"margin": 0,
"cooldown": 169,
"short": 172,
"low_conf": 214,
"retrain": 18,
"no_shape": 644
},
"per_asset": {
"NEAR-USD": {
"pnl_net": -29.39,
"pnl_gross": -19.93,
"commission": 9.09,
"interest": 0.37,
"trades": 44,
"wins": 14,
"wr": 31.8
},
"TIA-USD": {
"pnl_net": 33.92,
"pnl_gross": 42.8,
"commission": 8.54,
"interest": 0.34,
"trades": 42,
"wins": 14,
"wr": 33.3
},
"PEPE-USD": {
"pnl_net": 15.76,
"pnl_gross": 24.21,
"commission": 8.15,
"interest": 0.31,
"trades": 39,
"wins": 15,
"wr": 38.5
},
"ADA-USD": {
"pnl_net": 3.63,
"pnl_gross": 7.66,
"commission": 3.89,
"interest": 0.15,
"trades": 18,
"wins": 8,
"wr": 44.4
},
"DOGE-USD": {
"pnl_net": -16.11,
"pnl_gross": -5.2,
"commission": 5.89,
"interest": 5.01,
"trades": 27,
"wins": 10,
"wr": 37.0
}
}
}
]
}
+405
View File
@@ -0,0 +1,405 @@
"""Exp27: Scan top crypto pairs for Remizov formula edge.
Pipeline per asset:
1. Fetch 4h OHLCV from Bybit (need 2000+ bars)
2. Train model (30% train / 70% test)
3. Amplitude correlation test
4. Confidence-filtered PnL test
5. Statistical significance (bootstrap)
6. Walk-forward (3 folds)
Only pairs passing all tests proceed to realistic backtest.
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from scipy import stats
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.core.net import EnhancedRemizovNet
from remizov_trader.core.signals import fetch_ohlcv_ccxt
from common.metrics import save_results
SHIFT = 7
MIN_CONFIDENCE = 1.5
TRAIN_RATIO = 0.3
MIN_BARS = 2000
# Top 50 crypto on Bybit spot/USDC (excluding already tested BTC/ETH/ADA/DOGE/SOL/DOT/XRP)
CANDIDATES = [
"AVAX/USDC", "LINK/USDC", "MATIC/USDC", "UNI/USDC", "ATOM/USDC",
"FIL/USDC", "LTC/USDC", "NEAR/USDC", "APT/USDC", "OP/USDC",
"ARB/USDC", "SUI/USDC", "PEPE/USDC", "SHIB/USDC", "WIF/USDC",
"FET/USDC", "RENDER/USDC", "INJ/USDC", "SEI/USDC", "TIA/USDC",
"STX/USDC", "IMX/USDC", "SAND/USDC", "MANA/USDC", "CRV/USDC",
]
WS_OPTIONS = [48, 64]
K_OPTIONS = [2, 3]
def _ticker(symbol):
return symbol.replace("/", "-").replace("USDC", "USD")
def _train_model(prices, ws):
data = signals.prepare_windows(prices, ws, SHIFT)
n_train = max(int(len(data) * TRAIN_RATIO), 20)
train = data[:n_train]
test = data[n_train:]
torch.manual_seed(42)
np.random.seed(42)
mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
dx=1.0 / ws, use_sde=True)
w = np.array([d["norm_input"] for d in train])
t = np.array([d["norm_target"] for d in train])
model_mod.train(mdl, w, t, 200, 0.003)
return mdl, train, test
def _amplitude_test(mdl, test_data, prices, ws, K):
"""Test amplitude prediction correlation."""
pred_amps, actual_amps = [], []
for d in test_data:
idx = d["price_idx"]
if idx + SHIFT >= len(prices):
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
pred_denorm = pred_new * d["std"] + d["mu"]
pred_amp = float(np.max(pred_denorm) - np.min(pred_denorm))
future = prices[idx:idx + SHIFT]
actual_amp = float(np.max(future) - np.min(future))
pred_amps.append(pred_amp)
actual_amps.append(actual_amp)
if len(pred_amps) < 50:
return {"r": 0, "n": len(pred_amps)}
r, p = stats.pearsonr(pred_amps, actual_amps)
return {"r": round(float(r), 4), "p": round(float(p), 4), "n": len(pred_amps)}
def _conf_pnl_test(mdl, test_data, prices, ws, K):
"""Test confidence-filtered PnL (trailing stop sim)."""
trades = []
for d in test_data:
idx = d["price_idx"]
if idx + SHIFT >= len(prices) or idx < ws + K:
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
# Shape confirmation
confirm = prices[idx - K:idx]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, d["mu"], d["std"], K, 0.5)
if not confirmed:
continue
# Confidence filter
atr = risk.compute_atr(prices, idx)
if atr <= 0:
continue
pred_denorm = pred_new * d["std"] + d["mu"]
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
conf = abs(corr) * (amp / atr)
if conf < MIN_CONFIDENCE:
continue
# Direction (long only)
direction = signals.get_direction(pred_new, K)
if direction != 1:
continue
# Trailing stop PnL
entry = prices[idx]
_, stop_mult = risk.regime_adaptive_params(prices, idx, K)
stop_dist = max(atr * stop_mult * 0.5, entry * 0.005)
stop = entry - stop_dist
best = entry
pnl_pct = 0.0
for j in range(1, SHIFT + 1):
if idx + j >= len(prices):
break
p = prices[idx + j]
if p > best:
best = p
stop = best - stop_dist
if p <= stop:
pnl_pct = (p - entry) / entry * 100
break
else:
pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100
trades.append(pnl_pct)
if not trades:
return {"mean_pnl": 0, "n": 0, "wr": 0}
wins = sum(1 for t in trades if t > 0)
return {
"mean_pnl": round(float(np.mean(trades)), 4),
"n": len(trades),
"wr": round(wins / len(trades) * 100, 1),
}
def _bootstrap_significance(mdl, test_data, prices, ws, K, n_boot=1000):
"""Bootstrap test for PnL significance."""
# Collect trade PnLs
trade_pnls = []
for d in test_data:
idx = d["price_idx"]
if idx + SHIFT >= len(prices) or idx < ws + K:
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
confirm = prices[idx - K:idx]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, d["mu"], d["std"], K, 0.5)
if not confirmed:
continue
atr = risk.compute_atr(prices, idx)
if atr <= 0:
continue
pred_denorm = pred_new * d["std"] + d["mu"]
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
conf = abs(corr) * (amp / atr)
if conf < MIN_CONFIDENCE:
continue
direction = signals.get_direction(pred_new, K)
if direction != 1:
continue
entry = prices[idx]
_, stop_mult = risk.regime_adaptive_params(prices, idx, K)
stop_dist = max(atr * stop_mult * 0.5, entry * 0.005)
stop = entry - stop_dist
best = entry
pnl_pct = 0.0
for j in range(1, SHIFT + 1):
if idx + j >= len(prices):
break
p = prices[idx + j]
if p > best:
best = p
stop = best - stop_dist
if p <= stop:
pnl_pct = (p - entry) / entry * 100
break
else:
pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100
trade_pnls.append(pnl_pct)
if len(trade_pnls) < 10:
return {"p_positive": 0, "ci_lo": 0, "ci_hi": 0, "n": len(trade_pnls)}
arr = np.array(trade_pnls)
means = [float(np.mean(np.random.choice(arr, len(arr), replace=True)))
for _ in range(n_boot)]
means = np.array(means)
p_pos = float(np.mean(means > 0))
ci = np.percentile(means, [2.5, 97.5])
return {
"p_positive": round(p_pos * 100, 1),
"ci_lo": round(float(ci[0]), 4),
"ci_hi": round(float(ci[1]), 4),
"n": len(trade_pnls),
"mean": round(float(np.mean(arr)), 4),
}
def _walk_forward(prices, ws, K, n_folds=3):
"""Walk-forward validation with 3 folds."""
data = signals.prepare_windows(prices, ws, SHIFT)
n = len(data)
chunk = n // (n_folds + 1)
if chunk < 30:
return {"folds": [], "stable": False}
fold_results = []
for i in range(n_folds):
train_end = chunk * (i + 2)
test_start = train_end
test_end = min(train_end + chunk, n)
train_data = data[:train_end]
test_data = data[test_start:test_end]
if len(test_data) < 10:
continue
torch.manual_seed(42)
np.random.seed(42)
mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
dx=1.0 / ws, use_sde=True)
w = np.array([d["norm_input"] for d in train_data])
t = np.array([d["norm_target"] for d in train_data])
model_mod.train(mdl, w, t, 200, 0.003)
r = _conf_pnl_test(mdl, test_data, prices, ws, K)
fold_results.append(r["mean_pnl"])
positive_folds = sum(1 for f in fold_results if f > 0)
return {
"folds": [round(f, 4) for f in fold_results],
"positive": positive_folds,
"total": len(fold_results),
"stable": positive_folds == len(fold_results) and len(fold_results) >= 2,
}
def main():
results_dir = Path(__file__).parent / "results"
results_dir.mkdir(parents=True, exist_ok=True)
print("=" * 80)
print("EXP27: SCAN NEW PAIRS FOR REMIZOV FORMULA EDGE")
print("=" * 80)
print(f"Candidates: {len(CANDIDATES)} pairs")
print(f"Tests: amplitude corr → conf PnL → bootstrap → walk-forward")
print(f"WS options: {WS_OPTIONS}, K options: {K_OPTIONS}")
all_results = []
for symbol in CANDIDATES:
ticker = _ticker(symbol)
print(f"\n{'─' * 60}")
print(f" {ticker} ({symbol})")
print(f"{'─' * 60}")
# Fetch data
try:
ohlcv, dates = fetch_ohlcv_ccxt(symbol, "4h", "max")
except Exception as e:
print(f" SKIP: fetch error: {e}")
all_results.append({"ticker": ticker, "status": "fetch_error", "error": str(e)})
continue
if ohlcv is None or len(ohlcv) < MIN_BARS:
bars = len(ohlcv) if ohlcv is not None else 0
print(f" SKIP: only {bars} bars (need {MIN_BARS})")
all_results.append({"ticker": ticker, "status": "insufficient_data", "bars": bars})
continue
prices = ohlcv[:, 3] # close
print(f" {len(prices)} bars, price ${prices[-1]:.4f}")
best_config = None
best_sharpe_proxy = -999
for ws in WS_OPTIONS:
for K in K_OPTIONS:
label = f"ws={ws} K={K}"
print(f"\n [{label}]", end=" ", flush=True)
mdl, train, test = _train_model(prices, ws)
# Test 1: Amplitude correlation
amp = _amplitude_test(mdl, test, prices, ws, K)
print(f"amp_r={amp['r']:.3f}", end=" ", flush=True)
if amp["r"] < 0.05:
print("← LOW, skip")
continue
# Test 2: Conf-filtered PnL
pnl = _conf_pnl_test(mdl, test, prices, ws, K)
print(f"PnL={pnl['mean_pnl']:+.3f}% N={pnl['n']}", end=" ", flush=True)
if pnl["n"] < 10 or pnl["mean_pnl"] <= 0:
print("← NO EDGE, skip")
continue
# Test 3: Bootstrap significance
boot = _bootstrap_significance(mdl, test, prices, ws, K)
print(f"P={boot['p_positive']:.0f}%", end=" ", flush=True)
if boot["p_positive"] < 90:
print("← NOT SIGNIFICANT, skip")
continue
# Test 4: Walk-forward
wf = _walk_forward(prices, ws, K)
print(f"WF={wf['positive']}/{wf['total']}", end=" ", flush=True)
# Score
score = pnl["mean_pnl"] * boot["p_positive"] / 100
print(f"score={score:.3f}")
result = {
"ticker": ticker, "ws": ws, "K": K,
"bars": len(prices),
"amplitude": amp,
"conf_pnl": pnl,
"bootstrap": boot,
"walk_forward": wf,
"score": round(score, 4),
"status": "tested",
}
if score > best_sharpe_proxy:
best_sharpe_proxy = score
best_config = result
if best_config:
all_results.append(best_config)
elif not any(r["ticker"] == ticker for r in all_results):
all_results.append({"ticker": ticker, "status": "no_edge"})
# Summary
tested = [r for r in all_results if r.get("status") == "tested"]
tested.sort(key=lambda r: r["score"], reverse=True)
print(f"\n{'═' * 80}")
print("RESULTS — PAIRS WITH EDGE")
print(f"{'═' * 80}")
if tested:
print(f" {'Ticker':<12s} {'ws':>3s} {'K':>2s} {'amp_r':>6s} "
f"{'PnL%':>7s} {'N':>4s} {'P%':>5s} {'WF':>5s} {'Score':>6s}")
print(f" {'-' * 55}")
for r in tested:
wf = r["walk_forward"]
print(f" {r['ticker']:<12s} {r['ws']:>3d} {r['K']:>2d} "
f"{r['amplitude']['r']:>6.3f} "
f"{r['conf_pnl']['mean_pnl']:>+6.3f}% "
f"{r['conf_pnl']['n']:>4d} "
f"{r['bootstrap']['p_positive']:>4.0f}% "
f"{wf['positive']}/{wf['total']} "
f"{r['score']:>6.3f}")
else:
print(" No pairs found with edge.")
failed = [r for r in all_results if r.get("status") != "tested"]
if failed:
print(f"\n Skipped: {len(failed)} pairs")
for r in failed:
print(f" {r['ticker']}: {r.get('status', 'unknown')}")
path = save_results({"results": all_results}, results_dir, "exp27_scan")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()
@@ -0,0 +1,76 @@
{
"ADA-USD": {
"test1_amplitude": {
"r_pred_amp_vs_actual_amp": 0.3862,
"p_amp": 0.0,
"n": 593,
"Q1_actual_amp": 0.019505,
"Q1_n": 149,
"Q2_actual_amp": 0.023589,
"Q2_n": 148,
"Q3_actual_amp": 0.028524,
"Q3_n": 148,
"Q4_actual_amp": 0.052077,
"Q4_n": 148,
"Q4_Q1_ratio": 2.67
},
"test2_activity_filter": {
"total_trades": 76,
"total_mean_pnl": 0.3256
},
"test3_vw_input": {
"standard_r": 0.3862,
"volume_weighted_r": 0.3824,
"delta_r": -0.0038,
"n_std": 593,
"n_vw": 593
},
"test4_range_boost": {
"standard_n": 76,
"standard_pnl": 0.3256,
"standard_wr": 36.8,
"boosted_n": 69,
"boosted_pnl": 0.2305,
"boosted_wr": 37.7,
"delta_pnl": -0.0951,
"delta_n": -7
}
},
"DOGE-USD": {
"test1_amplitude": {
"r_pred_amp_vs_actual_amp": 0.3852,
"p_amp": 0.0,
"n": 595,
"Q1_actual_amp": 0.006716,
"Q1_n": 149,
"Q2_actual_amp": 0.0087,
"Q2_n": 149,
"Q3_actual_amp": 0.009414,
"Q3_n": 148,
"Q4_actual_amp": 0.015862,
"Q4_n": 149,
"Q4_Q1_ratio": 2.362
},
"test2_activity_filter": {
"total_trades": 114,
"total_mean_pnl": 0.6492
},
"test3_vw_input": {
"standard_r": 0.3852,
"volume_weighted_r": 0.3805,
"delta_r": -0.0047,
"n_std": 595,
"n_vw": 595
},
"test4_range_boost": {
"standard_n": 114,
"standard_pnl": 0.6492,
"standard_wr": 41.2,
"boosted_n": 111,
"boosted_pnl": 0.7013,
"boosted_wr": 42.3,
"delta_pnl": 0.0521,
"delta_n": -3
}
}
}
+437
View File
@@ -0,0 +1,437 @@
"""Exp28: Volume analysis for Remizov formula.
Tests:
1. Does predicted amplitude correlate with future volume?
2. Does volume filter improve signal quality?
3. Does feeding volume-weighted prices improve amplitude prediction?
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from scipy import stats
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.core.net import EnhancedRemizovNet
from common.dataset import load_or_fetch
from common.metrics import save_results
SHIFT = 7
MIN_CONFIDENCE = 1.5
TRAIN_RATIO = 0.3
ASSETS = {
"ADA-USD": {"ws": 64, "K": 3},
"DOGE-USD": {"ws": 48, "K": 2},
}
def _train(prices, ws):
data = signals.prepare_windows(prices, ws, SHIFT)
n_train = max(int(len(data) * TRAIN_RATIO), 20)
torch.manual_seed(42)
np.random.seed(42)
mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
dx=1.0 / ws, use_sde=True)
w = np.array([d["norm_input"] for d in data[:n_train]])
t = np.array([d["norm_target"] for d in data[:n_train]])
model_mod.train(mdl, w, t, 200, 0.003)
return mdl, data[:n_train], data[n_train:]
def test1_amplitude_volume_correlation(mdl, test_data, prices, ohlcv, ws, K):
"""Does predicted amplitude correlate with future volume?"""
# ohlcv columns: [open, high, low, close] — but we need volume
# Volume is in the 5th column if available, otherwise skip
pred_amps = []
actual_vols = []
actual_amps = []
for d in test_data:
idx = d["price_idx"]
if idx + SHIFT >= len(prices):
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
pred_denorm = pred_new * d["std"] + d["mu"]
pred_amp = float(np.max(pred_denorm) - np.min(pred_denorm))
future = prices[idx:idx + SHIFT]
actual_amp = float(np.max(future) - np.min(future))
pred_amps.append(pred_amp)
actual_amps.append(actual_amp)
if len(pred_amps) < 50:
return {"status": "insufficient_data"}
# Quartile analysis
pred_arr = np.array(pred_amps)
actual_arr = np.array(actual_amps)
q25, q50, q75 = np.percentile(pred_arr, [25, 50, 75])
quartiles = {
"Q1": pred_arr <= q25,
"Q2": (pred_arr > q25) & (pred_arr <= q50),
"Q3": (pred_arr > q50) & (pred_arr <= q75),
"Q4": pred_arr > q75,
}
r_amp, p_amp = stats.pearsonr(pred_amps, actual_amps)
result = {
"r_pred_amp_vs_actual_amp": round(float(r_amp), 4),
"p_amp": round(float(p_amp), 6),
"n": len(pred_amps),
}
for qname, mask in quartiles.items():
result[f"{qname}_actual_amp"] = round(float(np.mean(actual_arr[mask])), 6)
result[f"{qname}_n"] = int(np.sum(mask))
result["Q4_Q1_ratio"] = round(
result["Q4_actual_amp"] / result["Q1_actual_amp"]
if result["Q1_actual_amp"] > 0 else 0, 3)
return result
def test2_volume_filter(mdl, test_data, prices, ohlcv, ws, K):
"""Does filtering by volume improve signal PnL?"""
# We don't have volume in our dataset — let's use price range as proxy
# Actually check if ohlcv has volume info
# ohlcv shape is (N, 4): O, H, L, C — no volume column in our dataset
# Use intrabar range (H-L) as activity proxy
trades_low_range = []
trades_high_range = []
all_trades = []
for d in test_data:
idx = d["price_idx"]
if idx + SHIFT >= len(prices) or idx < ws + K:
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
confirm = prices[idx - K:idx]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, d["mu"], d["std"], K, 0.5)
if not confirmed:
continue
atr = risk.compute_atr(prices, idx)
if atr <= 0:
continue
pred_denorm = pred_new * d["std"] + d["mu"]
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
conf = abs(corr) * (amp / atr)
if conf < MIN_CONFIDENCE:
continue
direction = signals.get_direction(pred_new, K)
if direction != 1:
continue
# Trailing stop PnL
entry = prices[idx]
_, stop_mult = risk.regime_adaptive_params(prices, idx, K)
stop_dist = max(atr * stop_mult * 0.5, entry * 0.005)
stop = entry - stop_dist
best = entry
pnl_pct = 0.0
for j in range(1, SHIFT + 1):
if idx + j >= len(prices):
break
p = prices[idx + j]
if p > best:
best = p
stop = best - stop_dist
if p <= stop:
pnl_pct = (p - entry) / entry * 100
break
else:
pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100
# Compute recent intrabar range as volume proxy
if ohlcv is not None and idx >= 20:
recent_ranges = ohlcv[idx-20:idx, 1] - ohlcv[idx-20:idx, 2] # H - L
current_range = ohlcv[idx, 1] - ohlcv[idx, 2]
median_range = np.median(recent_ranges)
is_high_activity = current_range > median_range
else:
is_high_activity = None
trade = {"pnl": pnl_pct, "high_activity": is_high_activity}
all_trades.append(trade)
if is_high_activity is True:
trades_high_range.append(pnl_pct)
elif is_high_activity is False:
trades_low_range.append(pnl_pct)
result = {
"total_trades": len(all_trades),
"total_mean_pnl": round(float(np.mean([t["pnl"] for t in all_trades])), 4) if all_trades else 0,
}
if trades_high_range:
result["high_activity_n"] = len(trades_high_range)
result["high_activity_pnl"] = round(float(np.mean(trades_high_range)), 4)
result["high_activity_wr"] = round(sum(1 for t in trades_high_range if t > 0) / len(trades_high_range) * 100, 1)
if trades_low_range:
result["low_activity_n"] = len(trades_low_range)
result["low_activity_pnl"] = round(float(np.mean(trades_low_range)), 4)
result["low_activity_wr"] = round(sum(1 for t in trades_low_range if t > 0) / len(trades_low_range) * 100, 1)
if trades_high_range and trades_low_range:
result["delta_pnl"] = round(result["high_activity_pnl"] - result["low_activity_pnl"], 4)
return result
def test3_volume_weighted_input(prices, ohlcv, ws, K):
"""Does volume-weighting the input improve amplitude prediction?
Compare:
A) Standard model (close prices)
B) Model trained on VWAP-like input: close * (range / median_range)
"""
if ohlcv is None:
return {"status": "no_ohlcv"}
# Create volume-weighted prices: emphasize bars with high range
ranges = ohlcv[:, 1] - ohlcv[:, 2] # H - L
# Rolling median range (20 bars)
vw_prices = prices.copy()
for i in range(20, len(prices)):
med_range = np.median(ranges[i-20:i])
if med_range > 0:
weight = ranges[i] / med_range
# Amplify deviations from local mean
local_mean = np.mean(prices[max(0, i-10):i+1])
vw_prices[i] = local_mean + (prices[i] - local_mean) * (1 + 0.5 * (weight - 1))
# Train and test standard model
mdl_std, train_std, test_std = _train(prices, ws)
amp_std = test1_amplitude_volume_correlation(mdl_std, test_std, prices, ohlcv, ws, K)
# Train and test volume-weighted model
mdl_vw, train_vw, test_vw = _train(vw_prices, ws)
# But test on actual prices amplitude
pred_amps_vw = []
actual_amps_vw = []
for d in test_vw:
idx = d["price_idx"]
if idx + SHIFT >= len(prices):
continue
pred = model_mod.predict(mdl_vw, d["norm_input"])
pred_new = pred[-SHIFT:]
pred_denorm = pred_new * d["std"] + d["mu"]
pred_amp = float(np.max(pred_denorm) - np.min(pred_denorm))
actual_amp = float(np.max(prices[idx:idx+SHIFT]) - np.min(prices[idx:idx+SHIFT]))
pred_amps_vw.append(pred_amp)
actual_amps_vw.append(actual_amp)
if len(pred_amps_vw) >= 50:
r_vw, _ = stats.pearsonr(pred_amps_vw, actual_amps_vw)
else:
r_vw = 0
return {
"standard_r": amp_std.get("r_pred_amp_vs_actual_amp", 0),
"volume_weighted_r": round(float(r_vw), 4),
"delta_r": round(float(r_vw) - amp_std.get("r_pred_amp_vs_actual_amp", 0), 4),
"n_std": amp_std.get("n", 0),
"n_vw": len(pred_amps_vw),
}
def test4_range_as_confidence_boost(mdl, test_data, prices, ohlcv, ws, K):
"""Does adding H-L range to confidence formula improve results?
Compare:
A) Standard: conf = |corr| * (amp / ATR)
B) Range-boosted: conf = |corr| * (amp / ATR) * (range / median_range)
"""
if ohlcv is None:
return {"status": "no_ohlcv"}
trades_standard = []
trades_boosted = []
for d in test_data:
idx = d["price_idx"]
if idx + SHIFT >= len(prices) or idx < ws + K or idx < 20:
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
confirm = prices[idx - K:idx]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, d["mu"], d["std"], K, 0.5)
if not confirmed:
continue
atr = risk.compute_atr(prices, idx)
if atr <= 0:
continue
pred_denorm = pred_new * d["std"] + d["mu"]
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
conf_std = abs(corr) * (amp / atr)
# Range boost
recent_ranges = ohlcv[idx-20:idx, 1] - ohlcv[idx-20:idx, 2]
current_range = ohlcv[idx, 1] - ohlcv[idx, 2]
median_range = np.median(recent_ranges)
range_ratio = current_range / median_range if median_range > 0 else 1.0
conf_boosted = conf_std * range_ratio
direction = signals.get_direction(pred_new, K)
if direction != 1:
continue
# Trailing stop PnL
entry = prices[idx]
_, stop_mult = risk.regime_adaptive_params(prices, idx, K)
stop_dist = max(atr * stop_mult * 0.5, entry * 0.005)
stop = entry - stop_dist
best = entry
pnl_pct = 0.0
for j in range(1, SHIFT + 1):
if idx + j >= len(prices):
break
p = prices[idx + j]
if p > best:
best = p
stop = best - stop_dist
if p <= stop:
pnl_pct = (p - entry) / entry * 100
break
else:
pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100
if conf_std >= MIN_CONFIDENCE:
trades_standard.append(pnl_pct)
if conf_boosted >= MIN_CONFIDENCE:
trades_boosted.append(pnl_pct)
result = {}
if trades_standard:
result["standard_n"] = len(trades_standard)
result["standard_pnl"] = round(float(np.mean(trades_standard)), 4)
result["standard_wr"] = round(sum(1 for t in trades_standard if t > 0) / len(trades_standard) * 100, 1)
if trades_boosted:
result["boosted_n"] = len(trades_boosted)
result["boosted_pnl"] = round(float(np.mean(trades_boosted)), 4)
result["boosted_wr"] = round(sum(1 for t in trades_boosted if t > 0) / len(trades_boosted) * 100, 1)
if trades_standard and trades_boosted:
result["delta_pnl"] = round(result["boosted_pnl"] - result["standard_pnl"], 4)
result["delta_n"] = result["boosted_n"] - result["standard_n"]
return result
def main():
results_dir = Path(__file__).parent / "results"
results_dir.mkdir(parents=True, exist_ok=True)
print("=" * 80)
print("EXP28: VOLUME / RANGE ANALYSIS FOR REMIZOV FORMULA")
print("=" * 80)
dataset = load_or_fetch("default")
all_results = {}
for ticker, params in ASSETS.items():
ws, K = params["ws"], params["K"]
d = dataset[ticker]
prices = d["prices"]
ohlcv = d.get("ohlcv")
print(f"\n{'─' * 60}")
print(f" {ticker} (ws={ws}, K={K}, {len(prices)} bars)")
print(f"{'─' * 60}")
mdl, train, test = _train(prices, ws)
# Test 1: Amplitude → volume correlation
print("\n TEST 1: Predicted amplitude vs actual amplitude")
r1 = test1_amplitude_volume_correlation(mdl, test, prices, ohlcv, ws, K)
print(f" r(pred_amp, actual_amp) = {r1.get('r_pred_amp_vs_actual_amp', 'N/A')}")
print(f" Q4/Q1 actual amp ratio = {r1.get('Q4_Q1_ratio', 'N/A')}x")
for q in ["Q1", "Q2", "Q3", "Q4"]:
print(f" {q}: actual_amp={r1.get(f'{q}_actual_amp', 'N/A'):.6f} (N={r1.get(f'{q}_n', 0)})")
# Test 2: Range-based activity filter
print("\n TEST 2: High vs low intrabar range (activity proxy)")
r2 = test2_volume_filter(mdl, test, prices, ohlcv, ws, K)
print(f" Total: {r2.get('total_trades', 0)} trades, PnL={r2.get('total_mean_pnl', 0):+.4f}%")
if "high_activity_pnl" in r2:
print(f" High range: {r2['high_activity_n']} trades, "
f"PnL={r2['high_activity_pnl']:+.4f}%, WR={r2['high_activity_wr']:.1f}%")
if "low_activity_pnl" in r2:
print(f" Low range: {r2['low_activity_n']} trades, "
f"PnL={r2['low_activity_pnl']:+.4f}%, WR={r2['low_activity_wr']:.1f}%")
if "delta_pnl" in r2:
print(f" Delta: {r2['delta_pnl']:+.4f}pp")
# Test 3: Volume-weighted input
print("\n TEST 3: Volume-weighted input vs standard")
r3 = test3_volume_weighted_input(prices, ohlcv, ws, K)
print(f" Standard r = {r3.get('standard_r', 'N/A')}")
print(f" VW input r = {r3.get('volume_weighted_r', 'N/A')}")
print(f" Delta r = {r3.get('delta_r', 'N/A')}")
# Test 4: Range-boosted confidence
print("\n TEST 4: Range-boosted confidence vs standard")
r4 = test4_range_as_confidence_boost(mdl, test, prices, ohlcv, ws, K)
if "standard_pnl" in r4:
print(f" Standard: N={r4['standard_n']}, PnL={r4['standard_pnl']:+.4f}%, WR={r4['standard_wr']:.1f}%")
if "boosted_pnl" in r4:
print(f" Boosted: N={r4['boosted_n']}, PnL={r4['boosted_pnl']:+.4f}%, WR={r4['boosted_wr']:.1f}%")
if "delta_pnl" in r4:
print(f" Delta PnL: {r4['delta_pnl']:+.4f}pp, Delta N: {r4['delta_n']:+d}")
all_results[ticker] = {
"test1_amplitude": r1,
"test2_activity_filter": r2,
"test3_vw_input": r3,
"test4_range_boost": r4,
}
# Summary
print(f"\n{'═' * 80}")
print("SUMMARY")
print(f"{'═' * 80}")
for ticker, results in all_results.items():
print(f"\n {ticker}:")
r2 = results["test2_activity_filter"]
r3 = results["test3_vw_input"]
r4 = results["test4_range_boost"]
activity_helps = r2.get("delta_pnl", 0) > 0.1
vw_helps = r3.get("delta_r", 0) > 0.01
boost_helps = r4.get("delta_pnl", 0) > 0.1
print(f" Activity filter: {'YES' if activity_helps else 'NO'} (Δ={r2.get('delta_pnl', 0):+.3f}pp)")
print(f" VW input: {'YES' if vw_helps else 'NO'} (Δr={r3.get('delta_r', 0):+.4f})")
print(f" Range-boost conf: {'YES' if boost_helps else 'NO'} (Δ={r4.get('delta_pnl', 0):+.3f}pp)")
path = save_results(all_results, results_dir, "exp28_volume")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()
+194
View File
@@ -0,0 +1,194 @@
"""Exp29b: ADA+DOGE timeframe scan with correct K values.
ADA: ws=64, K=3 (prod)
DOGE: ws=48, K=2 (prod)
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from scipy import stats
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.core.net import EnhancedRemizovNet
from remizov_trader.core.signals import fetch_ohlcv_ccxt
from common.metrics import save_results
SHIFT = 7
MIN_CONFIDENCE = 1.5
TRAIN_RATIO = 0.3
TIMEFRAMES = ["1h", "2h", "4h", "6h", "12h"]
ASSETS = [
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "ws": 64, "K": 3},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "ws": 48, "K": 2},
]
def _run_tests(prices, ws, K):
data = signals.prepare_windows(prices, ws, SHIFT)
n_train = max(int(len(data) * TRAIN_RATIO), 20)
train, test = data[:n_train], data[n_train:]
if len(test) < 20:
return None
torch.manual_seed(42)
np.random.seed(42)
mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
dx=1.0 / ws, use_sde=True)
w = np.array([d["norm_input"] for d in train])
t = np.array([d["norm_target"] for d in train])
model_mod.train(mdl, w, t, 200, 0.003)
# Amplitude correlation
pred_amps, actual_amps = [], []
for d in test:
idx = d["price_idx"]
if idx + SHIFT >= len(prices):
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
pred_denorm = pred_new * d["std"] + d["mu"]
pred_amps.append(float(np.max(pred_denorm) - np.min(pred_denorm)))
future = prices[idx:idx + SHIFT]
actual_amps.append(float(np.max(future) - np.min(future)))
if len(pred_amps) < 20:
return None
r_amp, _ = stats.pearsonr(pred_amps, actual_amps)
# Conf-filtered PnL with trailing stop
trade_pnls = []
for d in test:
idx = d["price_idx"]
if idx + SHIFT >= len(prices) or idx < ws + K:
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
confirm = prices[idx - K:idx]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, d["mu"], d["std"], K, 0.5)
if not confirmed:
continue
atr = risk.compute_atr(prices, idx)
if atr <= 0:
continue
pred_denorm = pred_new * d["std"] + d["mu"]
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
conf = abs(corr) * (amp / atr)
if conf < MIN_CONFIDENCE:
continue
direction = signals.get_direction(pred_new, K)
if direction != 1:
continue
entry = prices[idx]
_, stop_mult = risk.regime_adaptive_params(prices, idx, K)
stop_dist = max(atr * stop_mult * 0.5, entry * 0.005)
stop = entry - stop_dist
best = entry
pnl_pct = 0.0
for j in range(1, SHIFT + 1):
if idx + j >= len(prices):
break
p = prices[idx + j]
if p > best:
best = p
stop = best - stop_dist
if p <= stop:
pnl_pct = (p - entry) / entry * 100
break
else:
pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100
trade_pnls.append(pnl_pct)
n_trades = len(trade_pnls)
if n_trades < 3:
return {
"r_amp": round(float(r_amp), 4),
"mean_pnl": 0, "n_trades": n_trades, "wr": 0,
"p_positive": 0, "ci_lo": 0, "ci_hi": 0,
}
mean_pnl = float(np.mean(trade_pnls))
wr = sum(1 for t in trade_pnls if t > 0) / n_trades * 100
arr = np.array(trade_pnls)
means = np.array([float(np.mean(np.random.choice(arr, len(arr), replace=True)))
for _ in range(2000)])
p_pos = float(np.mean(means > 0)) * 100
ci = np.percentile(means, [2.5, 97.5])
return {
"r_amp": round(float(r_amp), 4),
"mean_pnl": round(mean_pnl, 4),
"n_trades": n_trades,
"wr": round(wr, 1),
"p_positive": round(p_pos, 1),
"ci_lo": round(float(ci[0]), 4),
"ci_hi": round(float(ci[1]), 4),
}
def main():
results_dir = Path(__file__).parent / "results"
results_dir.mkdir(parents=True, exist_ok=True)
print("=" * 80)
print("EXP29b: ADA+DOGE TIMEFRAME SCAN (CORRECT K)")
print("=" * 80)
all_results = []
for asset in ASSETS:
ticker = asset["ticker"]
ws, K = asset["ws"], asset["K"]
print(f"\n {ticker} (ws={ws}, K={K})")
print(f" {'TF':>3s} {'Bars':>6s} {'r_amp':>6s} {'PnL%':>8s} "
f"{'N':>4s} {'WR%':>5s} {'P%':>5s} {'CI':>20s}")
print(f" {'-' * 60}")
for tf in TIMEFRAMES:
try:
ohlcv, dates = fetch_ohlcv_ccxt(asset["symbol"], tf, "max")
except Exception:
print(f" {tf:>3s} fetch error")
continue
if ohlcv is None or len(ohlcv) < 500:
print(f" {tf:>3s} {len(ohlcv) if ohlcv is not None else 0} bars (insufficient)")
continue
prices = ohlcv[:, 3]
r = _run_tests(prices, ws, K)
if r is None:
print(f" {tf:>3s} {len(prices):>5d} bars — insufficient test data")
continue
flag = " ★" if r["mean_pnl"] > 0 and r["p_positive"] >= 90 and r["n_trades"] >= 10 else ""
print(f" {tf:>3s} {len(prices):>6d} {r['r_amp']:>+5.3f} "
f"{r['mean_pnl']:>+7.3f}% {r['n_trades']:>4d} "
f"{r['wr']:>4.1f}% {r['p_positive']:>4.0f}% "
f"[{r['ci_lo']:+.3f}, {r['ci_hi']:+.3f}]{flag}")
all_results.append({"ticker": ticker, "tf": tf, "ws": ws, "K": K,
"bars": len(prices), **r})
path = save_results({"results": all_results}, results_dir, "exp29b_ada_doge_tf")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,144 @@
{
"results": [
{
"ticker": "ADA-USD",
"tf": "1h",
"ws": 64,
"K": 3,
"bars": 24000,
"r_amp": 0.4403,
"mean_pnl": -0.0181,
"n_trades": 378,
"wr": 36.5,
"p_positive": 41.2,
"ci_lo": -0.2047,
"ci_hi": 0.176
},
{
"ticker": "ADA-USD",
"tf": "2h",
"ws": 64,
"K": 3,
"bars": 12000,
"r_amp": 0.4275,
"mean_pnl": -0.2391,
"n_trades": 205,
"wr": 35.1,
"p_positive": 7.6,
"ci_lo": -0.5478,
"ci_hi": 0.0917
},
{
"ticker": "ADA-USD",
"tf": "4h",
"ws": 64,
"K": 3,
"bars": 6000,
"r_amp": 0.4582,
"mean_pnl": 0.4213,
"n_trades": 92,
"wr": 44.6,
"p_positive": 88.2,
"ci_lo": -0.2346,
"ci_hi": 1.1214
},
{
"ticker": "ADA-USD",
"tf": "6h",
"ws": 64,
"K": 3,
"bars": 4000,
"r_amp": 0.4227,
"mean_pnl": -1.0627,
"n_trades": 45,
"wr": 35.6,
"p_positive": 0.7,
"ci_lo": -1.8794,
"ci_hi": -0.266
},
{
"ticker": "ADA-USD",
"tf": "12h",
"ws": 64,
"K": 3,
"bars": 2000,
"r_amp": 0.3045,
"mean_pnl": 1.5386,
"n_trades": 4,
"wr": 25.0,
"p_positive": 66.9,
"ci_lo": -1.824,
"ci_hi": 7.4749
},
{
"ticker": "DOGE-USD",
"tf": "1h",
"ws": 48,
"K": 2,
"bars": 24000,
"r_amp": 0.5124,
"mean_pnl": -0.1219,
"n_trades": 532,
"wr": 38.7,
"p_positive": 6.3,
"ci_lo": -0.2646,
"ci_hi": 0.0325
},
{
"ticker": "DOGE-USD",
"tf": "2h",
"ws": 48,
"K": 2,
"bars": 12000,
"r_amp": 0.5082,
"mean_pnl": 0.0898,
"n_trades": 259,
"wr": 38.2,
"p_positive": 70.3,
"ci_lo": -0.2291,
"ci_hi": 0.4389
},
{
"ticker": "DOGE-USD",
"tf": "4h",
"ws": 48,
"K": 2,
"bars": 6000,
"r_amp": 0.4128,
"mean_pnl": -0.0053,
"n_trades": 127,
"wr": 37.8,
"p_positive": 48.7,
"ci_lo": -0.7118,
"ci_hi": 0.722
},
{
"ticker": "DOGE-USD",
"tf": "6h",
"ws": 48,
"K": 2,
"bars": 4000,
"r_amp": 0.3364,
"mean_pnl": -0.2636,
"n_trades": 69,
"wr": 30.4,
"p_positive": 25.4,
"ci_lo": -1.1116,
"ci_hi": 0.5935
},
{
"ticker": "DOGE-USD",
"tf": "12h",
"ws": 48,
"K": 2,
"bars": 2000,
"r_amp": 0.3403,
"mean_pnl": -3.5186,
"n_trades": 9,
"wr": 11.1,
"p_positive": 0.0,
"ci_lo": -5.0874,
"ci_hi": -2.1504
}
]
}
+255
View File
@@ -0,0 +1,255 @@
"""Exp29: Timeframe scan for Remizov formula.
Tests top crypto pairs across multiple timeframes.
Pipeline per (asset, tf): fetch → train → amplitude corr → conf PnL → bootstrap.
"""
import sys
from pathlib import Path
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from scipy import stats
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.core.net import EnhancedRemizovNet
from remizov_trader.core.signals import fetch_ohlcv_ccxt
from common.metrics import save_results
SHIFT = 7
MIN_CONFIDENCE = 1.5
TRAIN_RATIO = 0.3
MIN_BARS = 1500
TIMEFRAMES = ["1h", "2h", "4h", "6h", "12h", "1d"]
# Include our current pairs + top candidates from exp27
PAIRS = [
"ADA/USDC", "DOGE/USDC", # current prod
"BTC/USDC", "ETH/USDC", "SOL/USDC", # previously tested (for comparison)
"NEAR/USDC", "TIA/USDC", "PEPE/USDC", # exp27 winners
"AVAX/USDC", "LINK/USDC", "LTC/USDC", # large caps
"UNI/USDC", "ATOM/USDC", "OP/USDC",
"ARB/USDC", "SUI/USDC", "APT/USDC",
"FIL/USDC", "SHIB/USDC", "SEI/USDC",
]
# ws=64, K=2 as default (good balance from exp26e/27)
WS = 64
K = 2
def _ticker(symbol):
return symbol.replace("/", "-").replace("USDC", "USD")
def _run_tests(prices, ws, K):
"""Train model and run amplitude + PnL + bootstrap tests."""
data = signals.prepare_windows(prices, ws, SHIFT)
n_train = max(int(len(data) * TRAIN_RATIO), 20)
train, test = data[:n_train], data[n_train:]
if len(test) < 30:
return None
torch.manual_seed(42)
np.random.seed(42)
mdl = EnhancedRemizovNet(grid_size=ws, n_steps=20, total_time=0.5,
dx=1.0 / ws, use_sde=True)
w = np.array([d["norm_input"] for d in train])
t = np.array([d["norm_target"] for d in train])
model_mod.train(mdl, w, t, 200, 0.003)
# Amplitude correlation
pred_amps, actual_amps = [], []
for d in test:
idx = d["price_idx"]
if idx + SHIFT >= len(prices):
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
pred_denorm = pred_new * d["std"] + d["mu"]
pred_amps.append(float(np.max(pred_denorm) - np.min(pred_denorm)))
future = prices[idx:idx + SHIFT]
actual_amps.append(float(np.max(future) - np.min(future)))
if len(pred_amps) < 30:
return None
r_amp, _ = stats.pearsonr(pred_amps, actual_amps)
# Conf-filtered PnL with trailing stop
trade_pnls = []
for d in test:
idx = d["price_idx"]
if idx + SHIFT >= len(prices) or idx < ws + K:
continue
pred = model_mod.predict(mdl, d["norm_input"])
pred_new = pred[-SHIFT:]
confirm = prices[idx - K:idx]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, d["mu"], d["std"], K, 0.5)
if not confirmed:
continue
atr = risk.compute_atr(prices, idx)
if atr <= 0:
continue
pred_denorm = pred_new * d["std"] + d["mu"]
amp = float(np.max(pred_denorm) - np.min(pred_denorm))
conf = abs(corr) * (amp / atr)
if conf < MIN_CONFIDENCE:
continue
direction = signals.get_direction(pred_new, K)
if direction != 1:
continue
entry = prices[idx]
_, stop_mult = risk.regime_adaptive_params(prices, idx, K)
stop_dist = max(atr * stop_mult * 0.5, entry * 0.005)
stop = entry - stop_dist
best = entry
pnl_pct = 0.0
for j in range(1, SHIFT + 1):
if idx + j >= len(prices):
break
p = prices[idx + j]
if p > best:
best = p
stop = best - stop_dist
if p <= stop:
pnl_pct = (p - entry) / entry * 100
break
else:
pnl_pct = (prices[min(idx + SHIFT, len(prices) - 1)] - entry) / entry * 100
trade_pnls.append(pnl_pct)
n_trades = len(trade_pnls)
if n_trades < 5:
return {
"r_amp": round(float(r_amp), 4),
"mean_pnl": 0, "n_trades": n_trades,
"p_positive": 0, "ci_lo": 0, "ci_hi": 0,
}
mean_pnl = float(np.mean(trade_pnls))
wr = sum(1 for t in trade_pnls if t > 0) / n_trades * 100
# Bootstrap
arr = np.array(trade_pnls)
means = np.array([float(np.mean(np.random.choice(arr, len(arr), replace=True)))
for _ in range(1000)])
p_pos = float(np.mean(means > 0)) * 100
ci = np.percentile(means, [2.5, 97.5])
return {
"r_amp": round(float(r_amp), 4),
"mean_pnl": round(mean_pnl, 4),
"n_trades": n_trades,
"wr": round(wr, 1),
"p_positive": round(p_pos, 1),
"ci_lo": round(float(ci[0]), 4),
"ci_hi": round(float(ci[1]), 4),
}
def main():
results_dir = Path(__file__).parent / "results"
results_dir.mkdir(parents=True, exist_ok=True)
print("=" * 80)
print("EXP29: TIMEFRAME SCAN")
print("=" * 80)
print(f"Pairs: {len(PAIRS)} | Timeframes: {TIMEFRAMES}")
print(f"ws={WS}, K={K}, conf>={MIN_CONFIDENCE}")
all_results = []
winners = []
for symbol in PAIRS:
ticker = _ticker(symbol)
print(f"\n{'─' * 50}")
print(f" {ticker}")
for tf in TIMEFRAMES:
print(f" {tf:>3s}: ", end="", flush=True)
try:
ohlcv, dates = fetch_ohlcv_ccxt(symbol, tf, "max")
except Exception as e:
print(f"fetch error")
continue
if ohlcv is None or len(ohlcv) < MIN_BARS:
bars = len(ohlcv) if ohlcv is not None else 0
print(f"{bars} bars (need {MIN_BARS})")
continue
prices = ohlcv[:, 3]
result = _run_tests(prices, WS, K)
if result is None:
print(f"{len(prices)} bars, insufficient test data")
continue
r = result
entry = {
"ticker": ticker, "tf": tf, "bars": len(prices),
**r,
}
all_results.append(entry)
flag = ""
if r["mean_pnl"] > 0 and r["p_positive"] >= 90 and r["n_trades"] >= 10:
flag = " ★"
winners.append(entry)
print(f"{len(prices):>5d} bars r={r['r_amp']:+.3f} "
f"PnL={r['mean_pnl']:+.3f}% N={r['n_trades']:>3d} "
f"P={r['p_positive']:>4.0f}%{flag}")
# Summary
print(f"\n{'═' * 80}")
print(f"WINNERS (PnL>0, P>=90%, N>=10)")
print(f"{'═' * 80}")
if winners:
winners.sort(key=lambda x: x["mean_pnl"] * x["p_positive"] / 100, reverse=True)
print(f" {'Ticker':<12s} {'TF':>3s} {'Bars':>5s} {'r_amp':>6s} "
f"{'PnL%':>7s} {'N':>4s} {'WR%':>5s} {'P%':>5s} {'CI':>15s}")
print(f" {'-' * 65}")
for w in winners:
print(f" {w['ticker']:<12s} {w['tf']:>3s} {w['bars']:>5d} "
f"{w['r_amp']:>+5.3f} {w['mean_pnl']:>+6.3f}% "
f"{w['n_trades']:>4d} {w.get('wr', 0):>4.1f}% "
f"{w['p_positive']:>4.0f}% "
f"[{w['ci_lo']:+.3f}, {w['ci_hi']:+.3f}]")
else:
print(" None found.")
# Compare 4h vs other TFs for our current pairs
print(f"\n{'═' * 80}")
print(f"ADA + DOGE: ALL TIMEFRAMES")
print(f"{'═' * 80}")
for t in ["ADA-USD", "DOGE-USD"]:
entries = [r for r in all_results if r["ticker"] == t]
if entries:
print(f"\n {t}:")
for e in sorted(entries, key=lambda x: TIMEFRAMES.index(x["tf"])):
flag = " ★" if e["mean_pnl"] > 0 and e["p_positive"] >= 90 else ""
print(f" {e['tf']:>3s}: r={e['r_amp']:+.3f} "
f"PnL={e['mean_pnl']:+.3f}% N={e['n_trades']:>3d} "
f"P={e['p_positive']:>4.0f}%{flag}")
path = save_results({"results": all_results, "winners": winners},
results_dir, "exp29_tf_scan")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()