Files
remizov-trader/experiments/exp28_volume/volume_test.py
T
anorandClaude Opus 4.6 45835e3f2b 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>
2026-03-11 08:07:38 +10:00

438 lines
16 KiB
Python

"""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()