Files
remizov-crypto/astro_trade_analysis.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

583 lines
18 KiB
Python

"""
Astrology-filtered shape confirmation strategy.
1. Run shape confirmation backtest across all configs
2. Record every trade with 15 astro features
3. Find astro COMBINATIONS that predict winning trades
4. Validate on out-of-sample split
5. Final backtest with astro filter
"""
from __future__ import annotations
import time
import warnings
from datetime import date, timedelta
from itertools import combinations
import numpy as np
import torch
import torch.nn as nn
from scipy import stats
from sklearn.tree import DecisionTreeClassifier
from data_v2 import fetch_asset
from models import EnhancedRemizovNet
from retest_all import curated_astro_features
warnings.filterwarnings("ignore")
# -- Config ------------------------------------------------------------------
ASSETS = ["BTC-USD", "ETH-USD", "SOL-USD", "BNB-USD"]
WINDOW_SIZE = 64
N_STEPS = 20
TOTAL_TIME = 0.5
EPOCHS = 200
FINETUNE_EPOCHS = 50
LR = 3e-3
SHIFT = 7
INITIAL_EQUITY = 10000.0
RISK_PER_TRADE = 0.02
COMMISSION = 0.001
STOP_MULT = 1.5
ASTRO_NAMES = [
"lunar_sin", "lunar_cos",
"mercury_retro", "venus_retro", "mars_retro", "saturn_retro", "n_retro",
"jup_sat_sin", "jup_sat_cos",
"sun_jup_sin", "sun_jup_cos",
"ven_mars_sin", "ven_mars_cos",
"mercury_speed", "mars_speed",
]
# Strategy configs to test
CONFIGS = [
(2, 0.5), (2, 0.7), (2, 0.9),
(3, 0.5), (3, 0.7), (3, 0.9),
]
# -- Model -------------------------------------------------------------------
def create_model():
return EnhancedRemizovNet(
grid_size=WINDOW_SIZE, n_steps=N_STEPS, total_time=TOTAL_TIME,
dx=1.0 / WINDOW_SIZE, use_sde=True,
)
def train_model(model, windows, targets, epochs):
g = torch.tensor(windows, dtype=torch.float32)
y = torch.tensor(targets, dtype=torch.float32)
opt = torch.optim.Adam(model.parameters(), lr=LR, weight_decay=1e-4)
crit = nn.MSELoss()
bs = min(64, len(windows))
for _ in range(epochs):
model.train()
perm = torch.randperm(len(g))
for i in range(0, len(g), bs):
idx = perm[i:i + bs]
opt.zero_grad()
loss = crit(model(g[idx], stochastic=True), y[idx])
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
opt.step()
# -- Data --------------------------------------------------------------------
def prepare_data(prices):
n = len(prices)
data = []
for t in range(WINDOW_SIZE, n - SHIFT, SHIFT):
w = prices[t - WINDOW_SIZE:t].copy()
future = prices[t:t + SHIFT].copy()
if len(future) < SHIFT:
continue
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
s = prices[t - WINDOW_SIZE + SHIFT:t + SHIFT].copy()
data.append({
"price_at_entry": prices[t - 1],
"future_prices": future,
"norm_input": (w - mu) / std,
"norm_target": (s - mu) / std,
"mu": mu, "std": std,
})
return data
# -- Shape Confirmation + Full Trade Recording -------------------------------
def run_full_backtest(
data: list[dict],
dates: list[date],
model,
confirm_days: int,
corr_threshold: float,
train_size: int = 80,
) -> list[dict]:
"""Run backtest and return detailed trade list with astro features."""
n = len(data)
if n < train_size + 5:
return []
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)
trades = []
equity = INITIAL_EQUITY
retrain_ctr = 0
for i in range(train_size, n):
d = data[i]
model.eval()
with torch.no_grad():
inp = torch.tensor(d["norm_input"], dtype=torch.float32).unsqueeze(0)
pred = model(inp, stochastic=False).squeeze(0).numpy()
# Shape confirmation
if confirm_days >= SHIFT:
continue
pred_new = pred[-SHIFT:]
pred_confirm = pred_new[:confirm_days]
if len(pred_confirm) < 2:
continue
actual_norm = (d["future_prices"][:confirm_days] - d["mu"]) / d["std"]
corr = np.corrcoef(pred_confirm, actual_norm)[0, 1]
if np.isnan(corr) or corr < corr_threshold:
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
continue
entry_price = d["future_prices"][confirm_days - 1]
pred_end_norm = pred_new[-1]
pred_at_confirm = pred_new[confirm_days - 1]
pred_direction = pred_end_norm - pred_at_confirm
if abs(pred_direction) < 1e-10:
continue
direction = 1 if pred_direction > 0 else -1
pred_range = np.max(np.abs(pred_new[confirm_days:] - pred_at_confirm))
stop_dist = max(pred_range * d["std"] * STOP_MULT, entry_price * 0.005)
risk_amount = equity * RISK_PER_TRADE
pos_size = risk_amount / stop_dist
pos_value = pos_size * entry_price
if pos_value > equity:
pos_size = equity / entry_price
pos_value = equity
exit_idx = SHIFT - 1
exit_price = d["future_prices"][exit_idx]
stop_price = entry_price - direction * stop_dist
stopped = False
for hp in d["future_prices"][confirm_days:exit_idx + 1]:
if direction == 1 and hp <= stop_price:
exit_price = stop_price
stopped = True
break
elif direction == -1 and hp >= stop_price:
exit_price = stop_price
stopped = True
break
pnl_gross = pos_size * (exit_price - entry_price) * direction
commission_cost = pos_value * COMMISSION * 2
pnl_net = pnl_gross - commission_cost
equity += pnl_net
# Get trade date and astro features
# Approximate trade date from index
price_idx = WINDOW_SIZE + i * SHIFT
if price_idx < len(dates):
trade_date = dates[price_idx]
else:
trade_date = dates[-1]
astro = curated_astro_features(trade_date)
trades.append({
"idx": i,
"date": trade_date,
"direction": direction,
"entry": entry_price,
"exit": exit_price,
"pnl_pct": (pnl_net / pos_value * 100) if pos_value > 0 else 0,
"pnl_net": pnl_net,
"win": pnl_net > 0,
"stopped": stopped,
"correlation": corr,
"equity": equity,
"astro": astro,
})
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 trades
# -- Astro Pattern Mining ----------------------------------------------------
def discretize_astro(astro: np.ndarray) -> dict:
"""Convert continuous astro features to discrete categories."""
d = {}
# Lunar phase quadrant
lunar_angle = np.degrees(np.arctan2(astro[0], astro[1])) % 360
if lunar_angle < 90:
d["lunar_q"] = "new_wax"
elif lunar_angle < 180:
d["lunar_q"] = "wax_full"
elif lunar_angle < 270:
d["lunar_q"] = "full_wan"
else:
d["lunar_q"] = "wan_new"
# Retrogrades (already binary)
d["merc_retro"] = astro[2] > 0.5
d["venus_retro"] = astro[3] > 0.5
d["mars_retro"] = astro[4] > 0.5
d["saturn_retro"] = astro[5] > 0.5
d["n_retro_high"] = astro[6] >= 3 # 3+ planets retrograde
# Jupiter-Saturn angle quadrant
js_angle = np.degrees(np.arctan2(astro[7], astro[8])) % 360
d["jup_sat_q"] = int(js_angle // 90)
# Mercury speed (fast/slow/retrograde)
if astro[13] < -0.1:
d["merc_speed"] = "retro"
elif astro[13] < 0.8:
d["merc_speed"] = "slow"
else:
d["merc_speed"] = "fast"
# Mars speed
if astro[14] < 0:
d["mars_speed"] = "retro"
elif astro[14] < 0.3:
d["mars_speed"] = "slow"
else:
d["mars_speed"] = "fast"
return d
def find_astro_rules(trades: list[dict]) -> list[dict]:
"""Find combinations of astro conditions that predict winning trades.
Uses decision tree + manual rule mining.
"""
if len(trades) < 20:
return []
# Prepare feature matrix
X = np.array([t["astro"] for t in trades])
y = np.array([1 if t["win"] else 0 for t in trades])
base_wr = y.mean()
# Add discretized features
disc_features = [discretize_astro(t["astro"]) for t in trades]
rules = []
# 1. Single feature thresholds
for j, name in enumerate(ASTRO_NAMES):
vals = X[:, j]
for q in [25, 50, 75]:
thresh = np.percentile(vals, q)
mask_hi = vals >= thresh
mask_lo = vals < thresh
for mask, label in [(mask_hi, f"{name}>p{q}"), (mask_lo, f"{name}<p{q}")]:
if mask.sum() < 10:
continue
wr = y[mask].mean()
n = mask.sum()
if abs(wr - base_wr) > 0.08:
# Binomial test
binom = stats.binomtest(int(y[mask].sum()), n, base_wr)
rules.append({
"rule": label,
"win_rate": wr,
"n_trades": n,
"coverage": n / len(trades),
"lift": wr - base_wr,
"p_value": binom.pvalue,
})
# 2. Discrete combinations (2-way)
disc_keys = list(disc_features[0].keys())
for k1, k2 in combinations(disc_keys, 2):
# Get unique value combos
combos_seen = set()
for df in disc_features:
combos_seen.add((str(df[k1]), str(df[k2])))
for v1, v2 in combos_seen:
mask = np.array([
str(disc_features[i][k1]) == v1 and str(disc_features[i][k2]) == v2
for i in range(len(trades))
])
if mask.sum() < 8:
continue
wr = y[mask].mean()
n = mask.sum()
if abs(wr - base_wr) > 0.10:
binom = stats.binomtest(int(y[mask].sum()), n, base_wr)
rules.append({
"rule": f"{k1}={v1} & {k2}={v2}",
"win_rate": wr,
"n_trades": n,
"coverage": n / len(trades),
"lift": wr - base_wr,
"p_value": binom.pvalue,
})
# 3. Decision tree (finds multi-feature splits automatically)
if len(trades) > 30:
dt = DecisionTreeClassifier(
max_depth=3, min_samples_leaf=10, random_state=42,
)
dt.fit(X, y)
dt_preds = dt.predict(X)
# Extract leaf nodes where WR differs from base
leaves = dt.apply(X)
for leaf in np.unique(leaves):
mask = leaves == leaf
if mask.sum() < 8:
continue
wr = y[mask].mean()
if abs(wr - base_wr) > 0.10:
binom = stats.binomtest(int(y[mask].sum()), int(mask.sum()), base_wr)
rules.append({
"rule": f"tree_leaf_{leaf}",
"win_rate": wr,
"n_trades": int(mask.sum()),
"coverage": mask.sum() / len(trades),
"lift": wr - base_wr,
"p_value": binom.pvalue,
})
# Sort by lift
rules.sort(key=lambda r: r["lift"], reverse=True)
return rules
# -- Out-of-Sample Validation -----------------------------------------------
def validate_rules(trades: list[dict], rules: list[dict]) -> list[dict]:
"""Split trades in half, check if rules from first half work on second."""
n = len(trades)
split = n // 2
train_trades = trades[:split]
test_trades = trades[split:]
if len(test_trades) < 15:
return []
X_test = np.array([t["astro"] for t in test_trades])
y_test = np.array([1 if t["win"] else 0 for t in test_trades])
base_wr_test = y_test.mean()
disc_test = [discretize_astro(t["astro"]) for t in test_trades]
validated = []
for rule in rules:
rname = rule["rule"]
# Reconstruct mask for test data
if rname.startswith("tree_leaf"):
continue # tree leaves don't transfer
if " & " in rname:
# Combination rule
parts = rname.split(" & ")
k1, v1 = parts[0].split("=", 1)
k2, v2 = parts[1].split("=", 1)
mask = np.array([
str(disc_test[i].get(k1)) == v1 and str(disc_test[i].get(k2)) == v2
for i in range(len(test_trades))
])
elif ">" in rname:
fname, pstr = rname.split(">")
j = ASTRO_NAMES.index(fname)
q = int(pstr[1:])
thresh = np.percentile(X_test[:, j], q)
mask = X_test[:, j] >= thresh
elif "<" in rname:
fname, pstr = rname.split("<")
j = ASTRO_NAMES.index(fname)
q = int(pstr[1:])
thresh = np.percentile(X_test[:, j], q)
mask = X_test[:, j] < thresh
else:
continue
if mask.sum() < 5:
continue
wr_test = y_test[mask].mean()
lift_test = wr_test - base_wr_test
validated.append({
**rule,
"wr_test": wr_test,
"lift_test": lift_test,
"n_test": int(mask.sum()),
"confirmed": lift_test > 0.05,
})
return validated
# -- Main --------------------------------------------------------------------
def main():
t0 = time.time()
print("=" * 75)
print("ASTRO-FILTERED SHAPE CONFIRMATION STRATEGY")
print("=" * 75)
for asset in ASSETS:
time.sleep(2)
try:
prices, dates = fetch_asset(asset)
except Exception as e:
print(f"\n {asset}: FETCH ERROR ({e})")
continue
data = prepare_data(prices)
print(f"\n{'=' * 75}")
print(f" {asset}: {len(data)} decisions ({dates[WINDOW_SIZE]}→{dates[-1]})")
print(f"{'=' * 75}")
# Run best config for this asset
best_trades = None
best_equity = 0
best_config = None
for K, thresh in CONFIGS:
model = create_model()
trades = run_full_backtest(data, dates, model, K, thresh)
if not trades:
continue
final_eq = trades[-1]["equity"] if trades else INITIAL_EQUITY
n_trades = len(trades)
wins = sum(1 for t in trades if t["win"])
wr = wins / n_trades if n_trades > 0 else 0
ret = (final_eq / INITIAL_EQUITY - 1) * 100
print(f" K={K} corr>{thresh}: ${final_eq:>9,.0f} ({ret:>+6.1f}%) "
f"{n_trades} trades WR={wr:.0%}")
if final_eq > best_equity:
best_equity = final_eq
best_trades = trades
best_config = (K, thresh)
if not best_trades or len(best_trades) < 20:
print(f" [SKIP] Not enough trades for analysis")
continue
K, thresh = best_config
n_trades = len(best_trades)
wins = sum(1 for t in best_trades if t["win"])
base_wr = wins / n_trades
print(f"\n BEST CONFIG: K={K} corr>{thresh}")
print(f" {n_trades} trades, WR={base_wr:.1%}")
# ── Astro Pattern Mining ──
print(f"\n ASTRO PATTERN MINING (base WR={base_wr:.1%}):")
rules = find_astro_rules(best_trades)
if not rules:
print(f" No significant astro patterns found")
continue
# Top rules by lift
top_rules = [r for r in rules if r["p_value"] < 0.10][:15]
if top_rules:
print(f" {'Rule':<40s} {'WR':>5s} {'Lift':>6s} {'N':>4s} "
f"{'Cover':>6s} {'p':>7s}")
print(f" {'─' * 72}")
for r in top_rules:
sig = "**" if r["p_value"] < 0.05 else ""
print(f" {r['rule']:<40s} {r['win_rate']:>4.0%} "
f"{r['lift']:>+5.0%} {r['n_trades']:>4d} "
f"{r['coverage']:>5.0%} {r['p_value']:>7.4f} {sig}")
# ── Out-of-Sample Validation ──
print(f"\n OUT-OF-SAMPLE VALIDATION (first half→second half):")
validated = validate_rules(best_trades, top_rules)
confirmed = [v for v in validated if v["confirmed"]]
if confirmed:
print(f" {'Rule':<40s} {'Train':>5s} {'Test':>5s} {'N_test':>6s}")
print(f" {'─' * 60}")
for v in confirmed:
print(f" {v['rule']:<40s} {v['win_rate']:>4.0%} "
f"{v['wr_test']:>4.0%} {v['n_test']:>6d}")
else:
print(f" No rules confirmed out-of-sample")
# ── Winning vs Losing Trade Astro Profile ──
print(f"\n ASTRO PROFILE: WINNERS vs LOSERS")
win_trades = [t for t in best_trades if t["win"]]
lose_trades = [t for t in best_trades if not t["win"]]
if win_trades and lose_trades:
X_win = np.array([t["astro"] for t in win_trades])
X_lose = np.array([t["astro"] for t in lose_trades])
print(f" {'Feature':<18s} {'Winners':>8s} {'Losers':>8s} "
f"{'Diff':>7s} {'p':>7s}")
print(f" {'─' * 52}")
for j, name in enumerate(ASTRO_NAMES):
w_mean = X_win[:, j].mean()
l_mean = X_lose[:, j].mean()
diff = w_mean - l_mean
_, p = stats.mannwhitneyu(
X_win[:, j], X_lose[:, j], alternative="two-sided",
) if len(X_win[:, j]) > 5 and len(X_lose[:, j]) > 5 else (0, 1)
sig = "**" if p < 0.05 else ""
print(f" {name:<18s} {w_mean:>+7.3f} {l_mean:>+7.3f} "
f"{diff:>+6.3f} {p:>7.3f} {sig}")
elapsed = time.time() - t0
print(f"\n\n{'=' * 75}")
print(f"COMPLETED in {elapsed:.0f}s")
print(f"{'=' * 75}")
if __name__ == "__main__":
main()