diff --git a/improvements.py b/improvements.py index 89c659d..6f52743 100644 --- a/improvements.py +++ b/improvements.py @@ -28,7 +28,8 @@ import numpy as np import torch import torch.nn as nn -from data_v2 import fetch_asset +import yfinance as yf + from models import EnhancedRemizovNet warnings.filterwarnings("ignore") @@ -58,12 +59,44 @@ ASSET_CONFIGS = { } +# -- Data fetch -------------------------------------------------------------- + +def fetch_asset(ticker, period="max"): + """Fetch daily close prices and dates.""" + hist = yf.Ticker(ticker).history(period=period) + prices = hist["Close"].dropna() + dates = [d.date() for d in prices.index] + return prices.values.astype(np.float64), dates + + +def fetch_asset_with_volume(ticker, period="max"): + """Fetch daily close prices, volumes, and dates.""" + hist = yf.Ticker(ticker).history(period=period) + close = hist["Close"].dropna() + vol = hist["Volume"].reindex(close.index).fillna(0) + dates = [d.date() for d in close.index] + return close.values.astype(np.float64), vol.values.astype(np.float64), dates + + # -- Model helpers ----------------------------------------------------------- -def create_model(grid_size=WINDOW_SIZE): +# Architecture configs for ensemble diversity +ARCH_CONFIGS = [ + {"use_sde": True, "use_ssm": False, "use_fno": False}, # baseline SDE + {"use_sde": True, "use_ssm": True, "use_fno": False}, # SSM + SDE + {"use_sde": True, "use_ssm": False, "use_fno": True}, # FNO + SDE + {"use_sde": True, "use_ssm": True, "use_fno": True}, # all three +] + + +def create_model(grid_size=WINDOW_SIZE, arch_idx=None): + if arch_idx is not None and 0 <= arch_idx < len(ARCH_CONFIGS): + cfg = ARCH_CONFIGS[arch_idx] + else: + cfg = {"use_sde": True, "use_ssm": False, "use_fno": False} return EnhancedRemizovNet( grid_size=grid_size, n_steps=N_STEPS, total_time=TOTAL_TIME, - dx=1.0 / grid_size, use_sde=True, + dx=1.0 / grid_size, **cfg, ) @@ -141,20 +174,29 @@ def run_backtest( ) -> dict: """Run backtest with configurable improvements. - improvements dict keys: + improvements dict keys (original): "adaptive_stop": bool — use ATR-based stop instead of pred range "kelly": bool — Kelly criterion position sizing "trailing_stop": bool — trailing stop-loss "vol_filter": bool — skip trades in bearish regime (MA20 < MA50) "corr_override": float — override correlation threshold "leverage": float — max leverage multiplier (1.0 = no leverage) - "ensemble_preds": list — pre-computed ensemble predictions (if using ensemble) + "ensemble_preds": list — pre-computed ensemble predictions + + New improvement keys (v2): + "adaptive_corr": bool — dynamic corr threshold based on rolling WR + "partial_exit": bool — close 50% at 1.5x risk, trail remainder + "regime_adaptive": bool — adjust K and stop_mult based on ATR/ATR_MA + "volume_filter": bool — enter only if volume > MA20(volume) + "volumes": np.ndarray — volume data aligned with prices (for volume_filter) """ if improvements is None: improvements = {} - K = cfg["K"] - corr_thresh = improvements.get("corr_override", cfg["corr_thresh"]) + K_base = cfg["K"] + K = K_base + corr_thresh_base = improvements.get("corr_override", cfg["corr_thresh"]) + corr_thresh = corr_thresh_base train_size = 80 n = len(data) @@ -194,6 +236,31 @@ def run_backtest( pred = predict(model, d["norm_input"]) pred_new = pred[-SHIFT:] + + # Adaptive correlation threshold (1) + if improvements.get("adaptive_corr") and len(trades) >= 10: + recent = trades[-20:] + rolling_wr = sum(1 for t in recent if t["win"]) / len(recent) + if rolling_wr > 0.55: + corr_thresh = max(corr_thresh_base - 0.1, 0.3) + elif rolling_wr < 0.40: + corr_thresh = min(corr_thresh_base + 0.1, 0.95) + else: + corr_thresh = corr_thresh_base + + # Regime-adaptive params (4) + if improvements.get("regime_adaptive"): + pidx = d["price_idx"] + atr_now = compute_atr(prices, pidx, period=14) + atr_ma = compute_atr(prices, pidx, period=50) + vol_ratio = atr_now / atr_ma if atr_ma > 0 else 1.0 + if vol_ratio > 1.5: # high vol regime + K = min(K_base + 1, SHIFT - 2) + elif vol_ratio < 0.7: # low vol regime + K = max(K_base - 1, 2) # min 2 for correlation + else: + K = K_base + pred_confirm = pred_new[:K] if len(pred_confirm) < 2: @@ -224,6 +291,17 @@ def run_backtest( equity_curve.append(equity) continue + # Volume filter (5) + volumes = improvements.get("volumes") + if improvements.get("volume_filter") and volumes is not None: + pidx = d["price_idx"] + if pidx >= 20: + vol_now = volumes[pidx - 1] + vol_ma20 = volumes[pidx - 20:pidx].mean() + if vol_now < vol_ma20: + equity_curve.append(equity) + continue + # Direction entry_price = d["future_prices"][K - 1] pred_direction = pred_new[-1] - pred_new[K - 1] @@ -235,14 +313,25 @@ def run_backtest( pred_range = np.max(np.abs(pred_new[K:] - pred_new[K - 1])) # Stop-loss calculation + stop_mult = STOP_MULT + if improvements.get("regime_adaptive"): + pidx = d["price_idx"] + atr_now = compute_atr(prices, pidx, period=14) + atr_ma = compute_atr(prices, pidx, period=50) + vol_ratio = atr_now / atr_ma if atr_ma > 0 else 1.0 + if vol_ratio > 1.5: + stop_mult = STOP_MULT * 1.5 + elif vol_ratio < 0.7: + stop_mult = STOP_MULT * 0.8 + if improvements.get("adaptive_stop"): # (A) ATR-based stop pidx = d["price_idx"] atr = compute_atr(prices, pidx) - stop_dist = max(atr * 2.0, entry_price * 0.005) + stop_dist = max(atr * 2.0 * (stop_mult / STOP_MULT), entry_price * 0.005) else: # Baseline: prediction range based - stop_dist = max(pred_range * d["std"] * STOP_MULT, entry_price * 0.005) + stop_dist = max(pred_range * d["std"] * stop_mult, entry_price * 0.005) # Position sizing if improvements.get("kelly"): @@ -277,11 +366,26 @@ def run_backtest( exit_price = d["future_prices"][-1] stop_price = entry_price - direction * stop_dist stopped = False + partial_exit_pnl = 0.0 # extra PnL from partial exit + + use_partial = improvements.get("partial_exit", False) + partial_done = False + partial_target = entry_price + direction * stop_dist * 1.5 if improvements.get("trailing_stop"): # Trailing stop: move stop in favorable direction + remaining_size = pos_size best_price = entry_price for hp in d["future_prices"][K:]: + # Partial exit (2): close 50% at 1.5x risk + if use_partial and not partial_done: + if (direction == 1 and hp >= partial_target) or \ + (direction == -1 and hp <= partial_target): + half = remaining_size * 0.5 + partial_exit_pnl = half * (partial_target - entry_price) * direction + remaining_size -= half + partial_done = True + if direction == 1: best_price = max(best_price, hp) trailing_stop = best_price - stop_dist @@ -298,7 +402,16 @@ def run_backtest( break else: # Fixed stop + remaining_size = pos_size for hp in d["future_prices"][K:]: + if use_partial and not partial_done: + if (direction == 1 and hp >= partial_target) or \ + (direction == -1 and hp <= partial_target): + half = remaining_size * 0.5 + partial_exit_pnl = half * (partial_target - entry_price) * direction + remaining_size -= half + partial_done = True + if direction == 1 and hp <= stop_price: exit_price = stop_price stopped = True @@ -308,7 +421,11 @@ def run_backtest( stopped = True break - pnl_gross = pos_size * (exit_price - entry_price) * direction + if use_partial and partial_done: + remaining_size = pos_size * 0.5 + pnl_gross = partial_exit_pnl + remaining_size * (exit_price - entry_price) * direction + else: + pnl_gross = pos_size * (exit_price - entry_price) * direction commission_cost = pos_value * COMMISSION * 2 pnl_net = pnl_gross - commission_cost equity += pnl_net @@ -566,9 +683,58 @@ def compute_ensemble_parallel(data, n_models=3, train_size=80): return ensemble +# -- Architecture ensemble -------------------------------------------------- + +def _worker_arch_ensemble_single(args): + """Train one architecture variant and return predictions.""" + arch_idx, data, grid_size, train_size = args + + torch.set_num_threads(1) + torch.manual_seed(42) + np.random.seed(42) + + model = create_model(grid_size=grid_size, arch_idx=arch_idx) + 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) + + n = len(data) + preds = {} + retrain_ctr = 0 + for i in range(train_size, n): + preds[i] = predict(model, data[i]["norm_input"]) + retrain_ctr += 1 + if retrain_ctr >= 10: + ws = np.array([dd["norm_input"] for dd in data[:i + 1]]) + ts = np.array([dd["norm_target"] for dd in data[:i + 1]]) + train_model(model, ws, ts, FINETUNE_EPOCHS) + retrain_ctr = 0 + + return preds + + +def compute_arch_ensemble_parallel(data, train_size=80): + """Train 4 architecturally diverse models in parallel, average predictions.""" + n_archs = len(ARCH_CONFIGS) + args = [(idx, data, WINDOW_SIZE, train_size) for idx in range(n_archs)] + + with ProcessPoolExecutor(max_workers=min(n_archs, N_WORKERS)) as pool: + all_preds = list(pool.map(_worker_arch_ensemble_single, args)) + + n = len(data) + ensemble = {} + for i in range(n): + member_preds = [p[i] for p in all_preds if i in p] + if member_preds: + ensemble[i] = np.mean(member_preds, axis=0) + else: + ensemble[i] = None + return ensemble + + # -- Main: Parallel A/B Testing --------------------------------------------- -def run_asset_tests(asset, cfg, prices, dates): +def run_asset_tests(asset, cfg, prices, dates, volumes=None): """Run all tests for one asset. Returns list of metrics.""" data = prepare_data(prices) n = len(data) @@ -589,22 +755,20 @@ def run_asset_tests(asset, cfg, prices, dates): sd = base_model.state_dict() print("done") - # Define all tests + # Baseline = ATR + Trailing (proven best from previous A/B) + baseline_impr = {"adaptive_stop": True, "trailing_stop": True} + + # Define all tests — each new improvement ON TOP of baseline tests = [ - ("BASELINE", {}), - ("A: ATR stop", {"adaptive_stop": True}), - ("A2: Trailing stop", {"trailing_stop": True}), - ("B: Kelly sizing", {"kelly": True}), - ("E: Vol filter (MA20>50)", {"vol_filter": True}), - ("G: 2x leverage", {"leverage": 2.0}), + ("BASELINE (ATR+Trail)", baseline_impr), + ("1: Adaptive corr", {**baseline_impr, "adaptive_corr": True}), + ("2: Partial exit", {**baseline_impr, "partial_exit": True}), + ("4: Regime adaptive", {**baseline_impr, "regime_adaptive": True}), + ("5: Volume filter", {**baseline_impr, "volume_filter": True, + "volumes": volumes}), ] - # Add F tests (higher corr thresholds) - for thresh in [0.7, 0.8, 0.9]: - if thresh > cfg["corr_thresh"]: - tests.append((f"F: corr>{thresh}", {"corr_override": thresh})) - - # Run all tests in parallel + # Run parallel tests print(f" Running {len(tests)} tests in parallel ({N_WORKERS} workers)...", end=" ", flush=True) @@ -618,34 +782,46 @@ def run_asset_tests(asset, cfg, prices, dates): print("done") - # Ensemble (parallel model training) - print(f" Running D: Ensemble (3 models, parallel)...", end=" ", flush=True) - ens_preds = compute_ensemble_parallel(data, n_models=3) - r = run_backtest(prices, dates, data, cfg, {"ensemble_preds": ens_preds}) - m = calc_metrics(r["trades"], "D: Ensemble x3") + # Architecture ensemble (3: parallel model training) + print(f" Running 3: Arch ensemble (4 archs, parallel)...", end=" ", flush=True) + arch_preds = compute_arch_ensemble_parallel(data) + r = run_backtest(prices, dates, data, cfg, + {**baseline_impr, "ensemble_preds": arch_preds}) + m = calc_metrics(r["trades"], "3: Arch ensemble x4") results.append(m) print(f"done ({m['n_trades']} trades)") # Print print_comparison(results, asset) - valid = [r for r in results if r["n_trades"] >= 5] + baseline = results[0] + valid = [r for r in results[1:] if r["n_trades"] >= 5] if valid: - best = max(valid, key=lambda r: r["sharpe"]) - print(f"\n BEST for {asset}: {best['label']} " - f"(Sharpe={best['sharpe']}, Return={best['total_return']:+.1f}%)") + # Show improvements vs baseline + print(f"\n vs BASELINE (Sharpe={baseline['sharpe']}, " + f"Ret={baseline['total_return']:+.1f}%):") + for r in valid: + s_diff = r["sharpe"] - baseline["sharpe"] + r_diff = r["total_return"] - baseline["total_return"] + verdict = "BETTER" if r["sharpe"] > baseline["sharpe"] else "WORSE" + print(f" {r['label']:<25s} Sharpe {s_diff:+.2f}, " + f"Ret {r_diff:+.1f}% [{verdict}]") return results -def run_asset_combos(asset, cfg, prices, dates): - """Run combination tests for one asset. Returns list of metrics.""" +def run_asset_combos(asset, cfg, prices, dates, volumes=None, passed_keys=None): + """Run combination tests for one asset. Only combines improvements that passed.""" data = prepare_data(prices) print(f"\n{'=' * 100}") - print(f" {asset}: COMBINATIONS") + print(f" {asset}: COMBINATIONS (v2)") print(f"{'=' * 100}") + if not passed_keys: + print(" No improvements passed — skipping combos") + return [] + torch.manual_seed(42) np.random.seed(42) base_model = create_model() @@ -655,17 +831,36 @@ def run_asset_combos(asset, cfg, prices, dates): train_model(base_model, windows, targets, EPOCHS) sd = base_model.state_dict() - combos = [ - ("BASELINE", {}), - ("ATR + Kelly", {"adaptive_stop": True, "kelly": True}), - ("ATR + Trailing", {"adaptive_stop": True, "trailing_stop": True}), - ("ATR + Vol filter", {"adaptive_stop": True, "vol_filter": True}), - ("Kelly + Vol filter", {"kelly": True, "vol_filter": True}), - ("ATR + Kelly + Vol", {"adaptive_stop": True, "kelly": True, "vol_filter": True}), - ("ATR + Kelly + Trail", {"adaptive_stop": True, "kelly": True, "trailing_stop": True}), - ("Trail + Vol filter", {"trailing_stop": True, "vol_filter": True}), - ("ATR+Kelly+Vol+2x", {"adaptive_stop": True, "kelly": True, "vol_filter": True, "leverage": 2.0}), - ] + # Baseline = ATR + Trailing + base = {"adaptive_stop": True, "trailing_stop": True} + + # Map improvement names to dict keys + key_map = { + "adaptive_corr": {"adaptive_corr": True}, + "partial_exit": {"partial_exit": True}, + "regime_adaptive": {"regime_adaptive": True}, + "volume_filter": {"volume_filter": True, "volumes": volumes}, + } + + # Generate all pairs from passed keys + combos = [("BASELINE (ATR+Trail)", base)] + passed_list = [k for k in passed_keys if k in key_map] # exclude arch_ensemble + + from itertools import combinations as iter_combos + # Pairs + for a, b in iter_combos(passed_list, 2): + label = f"{a} + {b}" + impr = {**base, **key_map[a], **key_map[b]} + combos.append((label, impr)) + + # Triples (if 3+ passed) + if len(passed_list) >= 3: + for combo in iter_combos(passed_list, 3): + label = " + ".join(combo) + impr = dict(base) + for k in combo: + impr.update(key_map[k]) + combos.append((label, impr)) print(f" Running {len(combos)} combos in parallel...", end=" ", flush=True) worker_args = [ @@ -691,33 +886,72 @@ def main(): t0 = time.time() print("=" * 100) - print(f"IMPROVEMENT A/B TESTING (parallel, {N_WORKERS} workers)") + print(f"IMPROVEMENT A/B TESTING v2 (parallel, {N_WORKERS} workers)") print("=" * 100) + print(" Baseline: ATR + Trailing stop") + print(" New improvements: adaptive_corr, partial_exit, arch_ensemble,") + print(" regime_adaptive, volume_filter") + print() all_metrics = {} + all_data = {} # cache prices/volumes/dates per asset # Phase 1: Individual improvements for asset, cfg in ASSET_CONFIGS.items(): time.sleep(2) try: - prices, dates = fetch_asset(asset) + prices, volumes, dates = fetch_asset_with_volume(asset) except Exception as e: print(f"\n {asset}: FETCH ERROR ({e})") continue - all_metrics[asset] = run_asset_tests(asset, cfg, prices, dates) + all_data[asset] = (prices, volumes, dates) + all_metrics[asset] = run_asset_tests(asset, cfg, prices, dates, volumes) + + # Phase 2: Determine which improvements passed (Sharpe > baseline on >=2 assets) + improvement_labels = { + "1: Adaptive corr": "adaptive_corr", + "2: Partial exit": "partial_exit", + "3: Arch ensemble x4": "arch_ensemble", + "4: Regime adaptive": "regime_adaptive", + "5: Volume filter": "volume_filter", + } + + pass_counts = {key: 0 for key in improvement_labels.values()} + for asset, results in all_metrics.items(): + if not results: + continue + baseline_sharpe = results[0]["sharpe"] + for r in results[1:]: + for label, key in improvement_labels.items(): + if r["label"] == label and r["sharpe"] > baseline_sharpe: + pass_counts[key] += 1 - # Phase 2: Combinations print(f"\n\n{'=' * 100}") - print("PHASE 2: COMBINATIONS") + print("PHASE 2: FILTERING — which improvements passed (>= 2 assets)?") print(f"{'=' * 100}") - for asset, cfg in ASSET_CONFIGS.items(): - time.sleep(2) - try: - prices, dates = fetch_asset(asset) - except Exception as e: - continue - run_asset_combos(asset, cfg, prices, dates) + passed_keys = [] + for key, count in pass_counts.items(): + verdict = "PASS" if count >= 2 else "FAIL" + print(f" {key:<20s}: {count}/4 assets [{verdict}]") + if count >= 2: + passed_keys.append(key) + + # Phase 3: Combinations (only passed improvements, excluding arch_ensemble) + combo_keys = [k for k in passed_keys if k != "arch_ensemble"] + + if combo_keys: + print(f"\n\n{'=' * 100}") + print(f"PHASE 3: COMBINATIONS ({len(combo_keys)} passed improvements)") + print(f"{'=' * 100}") + + for asset, cfg in ASSET_CONFIGS.items(): + if asset not in all_data: + continue + prices, volumes, dates = all_data[asset] + run_asset_combos(asset, cfg, prices, dates, volumes, combo_keys) + else: + print("\n No improvements passed — skipping combinations") # Final summary elapsed = time.time() - t0 @@ -730,7 +964,7 @@ def main(): continue results = all_metrics[asset] baseline = results[0] - valid = [r for r in results if r["n_trades"] >= 5 and r["label"] != "BASELINE"] + valid = [r for r in results[1:] if r["n_trades"] >= 5] if not valid: print(f"\n {asset}: no valid improvements") @@ -738,25 +972,27 @@ def main(): best_sharpe = max(valid, key=lambda r: r["sharpe"]) best_return = max(valid, key=lambda r: r["total_return"]) - best_wr = max(valid, key=lambda r: r["win_rate"]) print(f"\n {asset} (baseline: Sharpe={baseline['sharpe']}, " - f"Ret={baseline['total_return']:+.1f}%, WR={baseline['win_rate']:.0f}%):") + f"Ret={baseline['total_return']:+.1f}%):") print(f" Best Sharpe: {best_sharpe['label']} → {best_sharpe['sharpe']} " f"(vs {baseline['sharpe']})") - print(f" Best Return: {best_return['label']} → {best_return['total_return']:+.1f}% " + print(f" Best Return: {best_return['label']} → " + f"{best_return['total_return']:+.1f}% " f"(vs {baseline['total_return']:+.1f}%)") - print(f" Best WR: {best_wr['label']} → {best_wr['win_rate']:.0f}% " - f"(vs {baseline['win_rate']:.0f}%)") + + print(f"\n Passed improvements: {passed_keys if passed_keys else 'none'}") # Save log os.makedirs("logs", exist_ok=True) ts = datetime.now().strftime("%Y%m%d_%H%M%S") - log_path = f"logs/improvements_{ts}.json" + log_path = f"logs/improvements_v2_{ts}.json" with open(log_path, "w") as f: json.dump({ "timestamp": datetime.now().isoformat(), "elapsed_seconds": elapsed, + "passed_improvements": passed_keys, + "pass_counts": pass_counts, "results": { asset: metrics for asset, metrics in all_metrics.items()