Files
remizov-crypto/retest_isolated.py
anorandClaude Opus 4.6 f66c13df84 feat: полный цикл тестирования RemizovNet + логирование
- 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>
2026-03-08 03:30:48 +10:00

325 lines
11 KiB
Python

"""
Isolated feature tests with time lags.
Phase A: Astrology only (no model, no technical)
Phase B: Technical only (no model, no astrology)
Phase C: Astrology with time lags (1-28 days)
Phase D: Technical with time lags (1-28 days)
Phase E: Best combo (astro lag + tech lag)
All with walk-forward validation, correct price-based labels.
"""
from __future__ import annotations
import time
import warnings
from datetime import date, timedelta
import numpy as np
from scipy import stats
from sklearn.linear_model import LogisticRegression
from sklearn.preprocessing import StandardScaler
from data_v2 import fetch_asset, make_windows
from retest_all import curated_astro_features, extract_technical
warnings.filterwarnings("ignore")
# -- Config ------------------------------------------------------------------
ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"]
WINDOW_SIZE = 64
SHIFT = 7
STRIDE = 7
INITIAL_TRAIN = 80
TEST_CHUNK = 20
RANDOM_STATE = 42
LAGS = [0, 3, 7, 14, 21, 28] # days of lag to test
# -- Astro with lag ----------------------------------------------------------
def extract_astro_lagged(dates: list[date], lag_days: int = 0) -> np.ndarray:
"""Extract astro features for dates shifted back by lag_days.
lag=0: astro features for the decision date itself
lag=7: astro features from 7 days BEFORE the decision date
(hypothesis: planetary positions influence markets with delay)
"""
feats = []
for d in dates:
shifted = d - timedelta(days=lag_days)
feats.append(curated_astro_features(shifted))
return np.array(feats)
# -- Technical with lag ------------------------------------------------------
def extract_technical_lagged(
prices: np.ndarray,
dates: list[date],
win_dates: list[date],
lag_days: int = 0,
) -> np.ndarray:
"""Extract technical indicators from price data lagged by lag_days.
lag=0: technical features at decision point
lag=7: technical features from 7 days earlier
(hypothesis: delayed reaction to technical signals)
"""
# Build date->index mapping
date_to_idx = {d: i for i, d in enumerate(dates)}
n = len(win_dates)
feats = np.zeros((n, 7))
for i, wd in enumerate(win_dates):
# Find the price index for this date - lag
target_date = wd - timedelta(days=lag_days)
# Find nearest available date
idx = date_to_idx.get(target_date)
if idx is None:
# Search nearby dates (markets closed on weekends)
for offset in range(1, 5):
for sign in [-1, 1]:
candidate = target_date + timedelta(days=sign * offset)
idx = date_to_idx.get(candidate)
if idx is not None:
break
if idx is not None:
break
if idx is None or idx < WINDOW_SIZE:
# Fallback: use zeros
continue
# Extract window ending at idx
w = prices[idx - WINDOW_SIZE: idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
w = (w - mu) / std
# Same 7 technical features
d = w[-14:]
g = np.maximum(d, 0).mean()
lo = np.abs(np.minimum(d, 0)).mean()
rsi = 100 - 100 / (1 + g / (lo + 1e-10)) if lo > 1e-10 else 50.0
ma_cross = w[-7:].mean() - w[-21:].mean()
s20, st20 = w[-20:].mean(), w[-20:].std()
bb = (w[-1] - s20) / (2 * st20 + 1e-10)
vr = w[-7:].std() / (w.std() + 1e-10)
rs = (w[-1] - w.mean()) / (w.std() + 1e-10)
macd = w[-12:].mean() - w[-26:].mean()
cum = w[-10:].sum()
feats[i] = [rsi, ma_cross, bb, vr, rs, macd, cum]
return feats
# -- Walk-Forward (generic) -------------------------------------------------
def walk_forward_features(
features: np.ndarray,
labels: np.ndarray,
) -> dict | None:
"""Walk-forward using pre-computed features."""
n = len(labels)
n_folds = (n - INITIAL_TRAIN) // TEST_CHUNK
if n_folds < 3:
return None
all_preds, all_true = [], []
for fold in range(n_folds):
bnd = INITIAL_TRAIN + fold * TEST_CHUNK
te = min(bnd + TEST_CHUNK, n)
tl = labels[bnd:te]
if len(tl) == 0:
break
X_tr = np.nan_to_num(features[:bnd])
X_te = np.nan_to_num(features[bnd:te])
sc = StandardScaler()
Xtr = sc.fit_transform(X_tr)
Xte = sc.transform(X_te)
clf = LogisticRegression(
penalty="l1", solver="saga", C=1.0, l1_ratio=1.0,
max_iter=2000, random_state=RANDOM_STATE,
)
clf.fit(Xtr, labels[:bnd])
preds = clf.predict(Xte)
all_preds.extend(preds.tolist())
all_true.extend(tl.tolist())
all_preds = np.array(all_preds)
all_true = np.array(all_true)
n_total = len(all_true)
n_correct = int(np.sum(all_preds == all_true))
total_acc = n_correct / n_total
majority = max(all_true.mean(), 1 - all_true.mean())
binom = stats.binomtest(n_correct, n_total, majority, alternative="greater")
return {
"total_acc": total_acc,
"n_total": n_total,
"n_correct": n_correct,
"majority": majority,
"p_value": binom.pvalue,
"significant": binom.pvalue < 0.05,
}
# -- Main --------------------------------------------------------------------
def main():
t_start = time.time()
# Collect all results for final table
all_results = []
for asset in ASSETS:
prices, dates = fetch_asset(asset)
data = make_windows(prices, dates, WINDOW_SIZE, SHIFT, STRIDE, use_returns=False)
labels = data["labels"]
n = len(labels)
n_up = labels.sum()
print(f"\n{'=' * 70}")
print(f" {asset}: {n} windows (up={n_up}, down={n - n_up})")
print(f"{'=' * 70}")
# ── Phase A: Astrology only, different lags ──
print(f"\n Phase A: ASTROLOGY ONLY")
print(f" {'Lag':>5s} {'Acc':>6s} {'N':>5s} {'p-val':>8s} {'Sig':>5s}")
print(f" {'─' * 35}")
for lag in LAGS:
astro_feats = extract_astro_lagged(data["dates"], lag_days=lag)
r = walk_forward_features(astro_feats, labels)
if r is None:
print(f" {lag:>5d} [SKIP]")
continue
sig = "**" if r["significant"] else ""
print(f" {lag:>5d} {r['total_acc']:>5.1%} {r['n_total']:>5d} "
f"{r['p_value']:>8.4f} {sig:>5s}")
all_results.append({
"asset": asset, "type": "astro", "lag": lag, **r,
})
# ── Phase B: Technical only, different lags ──
print(f"\n Phase B: TECHNICAL ONLY")
print(f" {'Lag':>5s} {'Acc':>6s} {'N':>5s} {'p-val':>8s} {'Sig':>5s}")
print(f" {'─' * 35}")
for lag in LAGS:
if lag == 0:
tech_feats = extract_technical(data["windows"])
else:
tech_feats = extract_technical_lagged(
prices, dates, data["dates"], lag_days=lag,
)
r = walk_forward_features(tech_feats, labels)
if r is None:
print(f" {lag:>5d} [SKIP]")
continue
sig = "**" if r["significant"] else ""
print(f" {lag:>5d} {r['total_acc']:>5.1%} {r['n_total']:>5d} "
f"{r['p_value']:>8.4f} {sig:>5s}")
all_results.append({
"asset": asset, "type": "tech", "lag": lag, **r,
})
# ── Phase C: Astro + Tech at different lags ──
print(f"\n Phase C: ASTRO + TECH (independent lags)")
print(f" {'A.lag':>5s} {'T.lag':>5s} {'Acc':>6s} {'N':>5s} "
f"{'p-val':>8s} {'Sig':>5s}")
print(f" {'─' * 42}")
# Test key lag combinations
combos = [
(0, 0), (7, 0), (14, 0), (0, 7), (0, 14),
(7, 7), (14, 7), (7, 14), (14, 14), (21, 7),
]
for a_lag, t_lag in combos:
astro_f = extract_astro_lagged(data["dates"], lag_days=a_lag)
if t_lag == 0:
tech_f = extract_technical(data["windows"])
else:
tech_f = extract_technical_lagged(
prices, dates, data["dates"], lag_days=t_lag,
)
combined = np.hstack([astro_f, tech_f])
r = walk_forward_features(combined, labels)
if r is None:
print(f" {a_lag:>5d} {t_lag:>5d} [SKIP]")
continue
sig = "**" if r["significant"] else ""
print(f" {a_lag:>5d} {t_lag:>5d} {r['total_acc']:>5.1%} {r['n_total']:>5d} "
f"{r['p_value']:>8.4f} {sig:>5s}")
all_results.append({
"asset": asset, "type": "combo",
"lag": f"a{a_lag}+t{t_lag}", **r,
})
# ================================================================
# FINAL SUMMARY
# ================================================================
elapsed = time.time() - t_start
print(f"\n\n{'=' * 70}")
print(f"FINAL SUMMARY — ISOLATED FEATURES + LAGS ({elapsed:.0f}s)")
print(f"{'=' * 70}")
# Best per asset per type
for asset in ASSETS:
asset_results = [r for r in all_results if r["asset"] == asset]
if not asset_results:
continue
print(f"\n {asset}:")
for ftype in ["astro", "tech", "combo"]:
type_results = [r for r in asset_results if r["type"] == ftype]
if not type_results:
continue
best = max(type_results, key=lambda r: r["total_acc"])
sig = "**" if best["significant"] else ""
print(f" Best {ftype:<6s}: {best['total_acc']:.1%} "
f"(lag={best['lag']}) p={best['p_value']:.4f} {sig}")
# Significant results
sig_results = [r for r in all_results if r["significant"]]
print(f"\n Significant results (p<0.05): {len(sig_results)}/{len(all_results)}")
for r in sig_results:
print(f" {r['asset']} {r['type']} lag={r['lag']}: "
f"{r['total_acc']:.1%} p={r['p_value']:.4f}")
if not sig_results:
print(" None — neither astrology nor technical indicators alone")
print(" predict price direction at any tested lag.")
# Multiple testing correction
n_tests = len(all_results)
bonferroni = 0.05 / n_tests
print(f"\n Multiple testing: {n_tests} tests performed")
print(f" Bonferroni threshold: p < {bonferroni:.4f}")
bonf_sig = [r for r in all_results if r["p_value"] < bonferroni]
print(f" Survives Bonferroni: {len(bonf_sig)}")
print(f"\n{'=' * 70}")
if __name__ == "__main__":
main()