# Section 1: Setup -- QC Cloud QuantBook (minute variant)
from AlgorithmImports import *
from QuantConnect.Research import *
import numpy as np
import pandas as pd
from scipy import stats
import gc
qb = QuantBook()
print('QC Cloud ready -- QuantBook initialized (minute variant)')INTRINSIC mesure – QC Cloud, re-teste 2026-08-12 (2e reproduction). Specification multi-coin NON EXECUTEE. Ce notebook QuantBook QC Cloud (7 coins, Resolution.Minute) n’a jamais pu s’executer : le research-node QC Cloud chute sous les transferts minute. La mitigation chunked-mois (section 2 ci-dessous, ecrite apres l’echec 2026-06-24 run #4132) a ete re-testee le 2026-08-12 sur le PoC 3y x 3 coins (projet QC #33294403) : le kernel a de nouveau chute – alerte UI “Connecting to kernel: Foundation-Py-Default” bloquee plus de 25 s, zero barre minute chargee (
daily_data={},pieces=[],n_minute_total=0), cell 3 tuee mid-transfer (execution_count=3maisoutputs=[]non flushed). Le chunk annuel -> mensuel (12x plus petit) ne fixe pas le drop : l’echec est le transport WebSocket sous charge minute soutenue, pas la taille du pull. Verdict executer-sur-QC-Cloud = INTRINSIC (infra research-node, 2e reproduction independante). Il reste la specification ideale multi-coin, non un livrable executable sur QC Cloud aujourd’hui.Le verdict BTC reel M12-HF a ete obtenu via le pipeline local 0-QCC (tick BTC Bitstamp possede -> resample minute) : voir
research_m12_hf_btc_local.ipynb(companion local, outputs reels). Pipeline reproductible :scripts/minute_loader.py+scripts/m12_hf_har_rv_j.py+scripts/m12_hf_compare.py.Ce notebook reste la cible QC Cloud native (generaliserait le verdict BTC aux 6 autres coins si l’infra cloud minute se debloquait). Voie de contournement sanctionnee (RECOVERABLE-MACHINE) : le converter yfinance->LEAN
scripts/qc/yfinance_to_lean_daily.py(#8788) materialise la crypto minute en local, executee dans un kernel LEAN Research local – meme strategie que le companion BTC ci-dessus.
M12-HF: HAR-RV-J at Resolution.Minute (high-frequency upgrade)
Model: HAR-RV-J (Andersen, Bollerslev & Diebold 2007, “Roughing It Up”). This notebook: the minute-resolution variant of the hourly QuantBook research_m12_har_rv_j.ipynb. The hourly run (Coinbase bars) returned an honest NO BEATS verdict (sign-test p=1.0, 11/21 Sharpe wins). The M12-HF hypothesis is that jump detection tightens when RV/BPV are estimated from intraday minute bars (Andersen-Bollerslev-Diebold 2003 microstructure floor: minute is the standard sparse-sampling horizon, vs hour which is too coarse to separate the continuous and jump components cleanly).
Architecture
RV_t = BPV_t + J_t (Huang-Tauchen bipower decomposition)
J_t = max(RV_t - mu*BPV_t, 0), mu = pi/2 * (1 + 1/n) ~ 0.6
log(RV_{t+h}) = b0 + b_d*log(RV_t) + b_w*log(RV_w) + b_m*log(RV_m)
+ b_dj*J_t + b_wj*J_w + b_mj*J_m + e
- Walk-forward 5-fold expanding OLS (numpy lstsq)
- 7 coins (BTC, ETH, SOL, LTC, XRP, ADA, DOT) x 3 horizons (h=1,5,10)
- Kelly cap=1.0, fee=50bps, sign-test vs HAR Classic
OOM mitigation (minute = ~60x hourly)
A full 10-year minute series is ~5.2M bars/coin. Loading it all in one History call OOMs the Research node. The pipeline below is per-coin incremental + yearly chunked (lesson from the m12-hf-vol-proposal memory): for each coin we pull qb.History(symbol, 1 year, Resolution.Minute) year-by-year, aggregate each year to a ~250-row daily RV/BPV/J series on the fly, del + gc.collect() before the next year, then concat the daily series. Peak memory is bounded to one year of minute data (~520k bars). The downstream HAR-RV-J model (cells 4-8) is byte-identical to the hourly variant and consumes the daily series only.
Navigation : Index recherche | << research_m12_har_rv_j | research_m12_hf_btc_local >>
# Section 2: Load crypto MINUTE data via QuantBook (per-coin + MONTHLY chunked + per-call retry)
# A single year pull (~520k bars) repeatedly dropped the research-node WebSocket under heavy
# transfer (2026-06-24 infra finding: "Connection lost" / "[qc] Failed to reconnect" at the
# first BTCUSD yearly call). Mitigation: chunk by MONTH (~44k bars/call, 12x smaller per
# transfer) with a single per-call retry on failure, aggregate each month to daily RV/BPV/J
# immediately, free memory, then concat. Total scope (10y x 7 coins) is unchanged; only the
# per-call transfer size shrinks. Downstream cells 4-8 are byte-identical to the hourly variant.
coins = ['BTCUSD', 'ETHUSD', 'SOLUSD', 'LTCUSD', 'XRPUSD', 'ADAUSD', 'DOTUSD']
# Window mirrors the hourly run (~3650 days). Whole years for clean chunking.
START_YEAR = 2015
END_YEAR = 2024 # inclusive: 10 calendar years
years = list(range(START_YEAR, END_YEAR + 1))
mu_bpv = np.pi / 2 # Huang-Tauchen bipower variation constant
def _minute_frame_to_daily(span):
"""Aggregate a chunk of minute bars to a daily RV/BPV/J/close frame."""
if span is None:
return None
df = span.copy()
if isinstance(df.index, pd.MultiIndex):
df = df.reset_index(level=0, drop=True)
df = df[['close']].dropna()
if len(df) < 2:
return None
df['log_ret'] = np.log(df['close'] / df['close'].shift(1))
df = df.dropna(subset=['log_ret'])
df['date'] = pd.to_datetime(df.index).date
daily = df.groupby('date').agg(
rv=('log_ret', lambda x: float(np.sum(x**2))),
n_bars=('log_ret', 'count'),
close=('close', 'last'),
)
bpv_map = {}
for date, g in df.groupby('date'):
r = g['log_ret'].values
bpv_map[date] = mu_bpv * float(np.sum(np.abs(r[1:]) * np.abs(r[:-1]))) if len(r) >= 2 else np.nan
daily['bpv'] = pd.Series(bpv_map)
daily['jumps'] = np.maximum(daily['rv'] - daily['bpv'], 0.0)
del df
return daily
def _pull_month_chunk(symbol, month_start, span_days):
"""Pull one month of minute bars with a single retry on failure (handles transient WebSocket drops)."""
try:
return qb.History(symbol, timedelta(days=span_days), Resolution.Minute, start=month_start)
except Exception:
try:
return qb.History(symbol, timedelta(days=span_days), Resolution.Minute, start=month_start)
except Exception:
return None
def minute_year_to_daily(symbol, year):
"""Pull one coin-year of minute bars MONTH-BY-MONTH; return daily RV/BPV/J frame; free memory per month."""
pieces = []
for month in range(1, 13):
month_start = datetime(year, month, 1)
month_end = datetime(year + (month // 12), (month % 12) + 1, 1)
span_days = (month_end - month_start).days + 1
span = _pull_month_chunk(symbol, month_start, span_days)
d = _minute_frame_to_daily(span)
if d is not None and len(d) > 0:
pieces.append(d)
del span
gc.collect()
if not pieces:
return None
return pd.concat(pieces).sort_index()
print(f'Minute data window: {START_YEAR}-{END_YEAR} ({len(years)} years) x {len(coins)} coins, MONTHLY chunked + per-call retry')# Section 3: Build daily_data per coin (minute -> daily aggregation loop)
# Outer loop = coin, inner loop = year. Memory bounded to ~1 year of minute bars at a time.
daily_data = {}
for symbol_str in coins:
crypto = None
used_market = None
for market in [Market.Coinbase, Market.Bitfinex]:
try:
c = qb.AddCrypto(symbol_str, Resolution.Minute, market)
if c is not None:
crypto = c
used_market = market
break
except Exception:
continue
if crypto is None:
print(f'{symbol_str}: no market available')
continue
pieces = []
n_minute_total = 0
for year in years:
try:
d = minute_year_to_daily(crypto.Symbol, year)
except Exception as e:
print(f' {symbol_str} {year}: ERROR {type(e).__name__}')
continue
if d is not None and len(d) > 0:
pieces.append(d)
n_minute_total += int(d['n_bars'].sum())
if not pieces:
print(f'{symbol_str}: no minute data on Coinbase/Bitfinex')
continue
daily = pd.concat(pieces).sort_index()
daily_data[symbol_str] = daily
print(f'{symbol_str}: {len(daily)} daily rows from ~{n_minute_total:,} minute bars '
f'({used_market}), RV range [{daily["rv"].min():.6f}, {daily["rv"].max():.6f}]')
print(f'\nTotal coins loaded: {len(daily_data)}')# Section 4: HAR-RV-J model (walk-forward expanding OLS via numpy)
# OLS via numpy.linalg.lstsq (sklearn not available on QC Cloud)
def ols_fit_predict(X_train, y_train, X_test):
"""OLS regression via numpy lstsq with intercept."""
X_aug = np.column_stack([np.ones(len(X_train)), X_train])
coefs, _, _, _ = np.linalg.lstsq(X_aug, y_train, rcond=None)
X_test_aug = np.column_stack([np.ones(len(X_test)), X_test])
return X_test_aug @ coefs
def har_rv_j_features(daily_df, horizon=1):
"""Build HAR-RV-J feature matrix: log(RV) lags + jump lags."""
df = daily_df.copy()
df["log_rv"] = np.log(df["rv"].clip(lower=1e-10))
# HAR lag features (daily=1, weekly=5, monthly=22)
df["rv_d"] = df["log_rv"]
df["rv_w"] = df["log_rv"].rolling(5).mean()
df["rv_m"] = df["log_rv"].rolling(22).mean()
# Jump lag features
df["j_d"] = df["jumps"]
df["j_w"] = df["jumps"].rolling(5).mean()
df["j_m"] = df["jumps"].rolling(22).mean()
# Target: log(RV_{t+h})
df["target"] = df["log_rv"].shift(-horizon)
return df.dropna()
def walk_forward_har_rv_j(df, n_folds=5, horizon=1):
"""Walk-forward expanding window with n_folds."""
features = ["rv_d", "rv_w", "rv_m", "j_d", "j_w", "j_m"]
prepared = har_rv_j_features(df, horizon=horizon)
n = len(prepared)
fold_size = n // (n_folds + 1)
predictions = []
actuals = []
for fold in range(1, n_folds + 1):
split = fold_size * fold
train = prepared.iloc[:split]
test_start = split
test_end = min(split + fold_size, n)
test = prepared.iloc[test_start:test_end]
if len(test) == 0:
continue
X_train = train[features].values
y_train = train["target"].values
X_test = test[features].values
y_test = test["target"].values
pred = ols_fit_predict(X_train, y_train, X_test)
predictions.extend(pred)
actuals.extend(y_test)
return np.array(predictions), np.array(actuals)
print("HAR-RV-J model functions defined (numpy OLS)")# Section 5: HAR Classic baseline (3 regressors: log(RV_d), log(RV_w), log(RV_m))
def har_classic_features(daily_df, horizon=1):
"""Build HAR Classic feature matrix: log(RV) lags only."""
df = daily_df.copy()
df["log_rv"] = np.log(df["rv"].clip(lower=1e-10))
df["rv_d"] = df["log_rv"]
df["rv_w"] = df["log_rv"].rolling(5).mean()
df["rv_m"] = df["log_rv"].rolling(22).mean()
df["target"] = df["log_rv"].shift(-horizon)
return df.dropna()
def walk_forward_har_classic(df, n_folds=5, horizon=1):
"""Walk-forward expanding window HAR Classic."""
features = ["rv_d", "rv_w", "rv_m"]
prepared = har_classic_features(df, horizon=horizon)
n = len(prepared)
fold_size = n // (n_folds + 1)
predictions = []
actuals = []
for fold in range(1, n_folds + 1):
split = fold_size * fold
train = prepared.iloc[:split]
test_start = split
test_end = min(split + fold_size, n)
test = prepared.iloc[test_start:test_end]
if len(test) == 0:
continue
X_train = train[features].values
y_train = train["target"].values
X_test = test[features].values
y_test = test["target"].values
pred = ols_fit_predict(X_train, y_train, X_test)
predictions.extend(pred)
actuals.extend(y_test)
return np.array(predictions), np.array(actuals)
print("HAR Classic baseline functions defined (numpy OLS)")# Section 6: Run M12 vs HAR Classic sweep
horizons = [1, 5, 10]
results = []
for symbol, daily in daily_data.items():
for h in horizons:
try:
pred_jrv, actual_jrv = walk_forward_har_rv_j(daily, n_folds=5, horizon=h)
pred_har, actual_har = walk_forward_har_classic(daily, n_folds=5, horizon=h)
mse_jrv = np.mean((pred_jrv - actual_jrv)**2)
mse_har = np.mean((pred_har - actual_har)**2)
# Kelly-based Sharpe comparison
rv_pred_jrv = np.exp(pred_jrv) # back to RV level
rv_pred_har = np.exp(pred_har)
rv_actual = np.exp(actual_jrv)
results.append({
"coin": symbol,
"horizon": h,
"mse_har_rv_j": mse_jrv,
"mse_har": mse_har,
"mse_change_pct": (mse_jrv - mse_har) / mse_har * 100,
"n_oos": len(actual_jrv),
})
print(f"{symbol} h={h}: MSE_HAR={mse_har:.6f}, MSE_JRV={mse_jrv:.6f}, "
f"change={results[-1]['mse_change_pct']:+.1f}%")
except Exception as e:
print(f"{symbol} h={h}: ERROR — {e}")
results_df = pd.DataFrame(results)
print(f"\nTotal combos: {len(results_df)}")
print(results_df.to_string())# Section 7: Kelly position sizing & Sharpe comparison
def kelly_sharpe(pred_rv, actual_rv, close_prices, fee_bps=50, cap=1.0, mu_window=60):
"""Kelly position sizing based on vol forecast, compute OOS Sharpe."""
n = len(pred_rv)
if n < mu_window + 10:
return np.nan, np.nan
# Signal: forecast vol vs rolling mean vol
rolling_mu = pd.Series(actual_rv).rolling(mu_window).mean().values
signal = np.where(pred_rv < rolling_mu, 1.0, -1.0) # long if vol predicted low
# Position sizing: inverse vol
vol_forecast = np.sqrt(pred_rv) * np.sqrt(252) # annualized
vol_forecast = np.maximum(vol_forecast, 0.01) # floor
kelly_weight = np.minimum(1.0 / vol_forecast, cap)
# Returns
returns = np.diff(np.log(close_prices[-(n+1):]))[:n]
if len(returns) < n:
returns = np.pad(returns, (0, n - len(returns)), constant_values=0)
# Apply Kelly sizing and signal
weighted_returns = signal * kelly_weight * returns
# Net of fees
fee = fee_bps / 10000
trades = np.abs(np.diff(np.concatenate([[0], signal * kelly_weight])))
fee_costs = np.concatenate([[0], trades * fee])[:n]
net_returns = weighted_returns - fee_costs
sharpe = np.mean(net_returns) / (np.std(net_returns) + 1e-10) * np.sqrt(252)
return sharpe, np.mean(net_returns)
# Compute Sharpe for each combo
for i, row in results_df.iterrows():
symbol = row["coin"]
h = row["horizon"]
daily = daily_data[symbol]
close = daily["close"].values
pred_jrv, actual_jrv = walk_forward_har_rv_j(daily, n_folds=5, horizon=h)
pred_har, actual_har = walk_forward_har_classic(daily, n_folds=5, horizon=h)
rv_pred_jrv = np.exp(pred_jrv)
rv_pred_har = np.exp(pred_har)
rv_actual = np.exp(actual_jrv)
# Align close prices
prepared = har_rv_j_features(daily, horizon=h)
n_oos = len(pred_jrv)
close_oos = close[-(n_oos+1):]
sharpe_jrv, _ = kelly_sharpe(rv_pred_jrv, rv_actual, close_oos, fee_bps=50)
sharpe_har, _ = kelly_sharpe(rv_pred_har, rv_actual, close_oos, fee_bps=50)
results_df.loc[i, "sharpe_har_rv_j"] = sharpe_jrv
results_df.loc[i, "sharpe_har"] = sharpe_har
results_df.loc[i, "delta_sharpe"] = sharpe_jrv - sharpe_har
results_df.loc[i, "beats"] = int(sharpe_jrv > sharpe_har)
print("Kelly Sharpe comparison complete")
print(results_df[["coin", "horizon", "sharpe_har_rv_j", "sharpe_har", "delta_sharpe", "beats"]].to_string())# Section 8: Sign-test & verdict
from scipy.stats import binomtest
beats = int(results_df["beats"].sum())
total = len(results_df)
win_rate = beats / total if total > 0 else 0
if total > 0:
p_value = binomtest(beats, total, 0.5).pvalue
else:
p_value = 1.0
median_delta_sharpe = results_df["delta_sharpe"].median()
print("=" * 60)
print(f"M12 HAR-RV-J vs HAR Classic — QC Cloud Verdict")
print(f"={'=' * 60}")
print(f"Beats: {beats}/{total} ({win_rate:.1%})")
print(f"Sign-test p-value: {p_value:.4f}")
print(f"Median delta-Sharpe: {median_delta_sharpe:+.4f}")
print(f"\nBEATS criteria: p < 0.05 AND win_rate >= 60%")
if p_value < 0.05 and win_rate >= 0.60:
print(f"VERDICT: BEATS (p={p_value:.4f}, win={win_rate:.1%})")
else:
print(f"VERDICT: NO BEATS (p={p_value:.4f}, win={win_rate:.1%})")
# Per-horizon breakdown
print(f"\nPer-horizon breakdown:")
for h in horizons:
subset = results_df[results_df["horizon"] == h]
if len(subset) > 0:
h_beats = int(subset["beats"].sum())
h_total = len(subset)
h_win = h_beats / h_total
h_med_ds = subset["delta_sharpe"].median()
print(f" h={h}: {h_beats}/{h_total} ({h_win:.1%}), "
f"median delta-Sharpe={h_med_ds:+.4f}")
# Comparison with local result
print(f"\nLocal M12 result: BEATS p=7.9e-7, 64/84 (76.2%), delta-Sharpe +0.0032")
print(f"QC Cloud result: {beats}/{total} ({win_rate:.1%}), p={p_value:.4f}, "
f"delta-Sharpe={median_delta_sharpe:+.4f}")Interpretation
Ce notebook QC Cloud reste NON EXECUTE (INTRINSIC-blocked, voir banniere cell 0). Le verdict scientifique M12-HF (minute vs horaire) a ete obtenu via le companion local 0-QCC
research_m12_hf_btc_local.ipynb(BTC Bitstamp, outputs reels), puis durci statistiquement par le test de Diebold-Marianoresearch_m12_hf_dm_test.ipynb(PR #4452). Ce qui suit reporte ce verdict (BTC uniquement) ; la generalisation multi-coin (ETH/SOL/ADA/DOT/LTC/XRP) reste la cible QC Cloud future de ce notebook, gated par le deblocage de l’infra cloud minute. La cell 8 ci-dessus est la spec du verdict multi-coin qui s’afficherait SI ce notebook tournait.
Verdict BTC (companion local + test de Diebold-Mariano, PR #4255 + #4452)
Le passage horaire -> minute DENSIFIE l’estimation de la Realized Variance et ameliore significativement la prevision de volatilite (BTC Bitstamp, 2018-2024, frais 50 bps) :
| Metrique | h=1 | h=5 | h=10 |
|---|---|---|---|
| Delta-Sharpe (minute - horaire, HAR-RV-J) | +0.548 | +0.433 | +0.633 |
| Reduction MSE (minute vs horaire) | -54.8 % | -50.7 % | -56.8 % |
| Diebold-Mariano stat (Newey-West HAC) | -19.03 | -13.01 | -10.68 |
| DM p-value (H0 : precision egale) | 0.000 | 0.000 | 0.000 |
BEATS minute >> horaire : les 3 horizons gagnent (delta median +0.548), MSE minute ~ moitie de l’hourly, et le test de Diebold-Mariano confirme la significativite (p ~ 0, block-bootstrap 22-j IC95 entierement < 0 sur 100 % des resamples).
Cause = FREQUENCE, pas les sauts (falsification de l’hypothese de depart)
Le gain minute ne vient pas du composant jump du HAR-RV-J. Le temoin HAR-Classic (sans composante sauts) montre le même gain (delta median +0.5496 ~ HAR-RV-J +0.5477), et les sauts n’ajoutent rien a l’echelle minute (delta HAR-RV-J vs HAR-Classic @minute = -0.0007). Cause reelle : la RV estimee sur grille 1440 b/j est un estimateur de la volatilite latente systematiquement meilleur que la grille 24 b/j (convergence Andersen-Bollerslev-Diebold 2003 : RV -> variance vraie quand la frequence d’echantillonnage augmente). L’hourly crypto RV est trop bruitee pour le vol-targeting Kelly.
Caveats (a generaliser sur QC Cloud)
- BTC uniquement (1/7 coins). La generalisation ETH/SOL/ADA/DOT/LTC/XRP reste la cible de ce notebook QuantBook, gated par
lean data download+ deblocage de l’infra cloud minute. - Bitstamp intra-source (hourly ~0.57 vs KEEPER multi-source ~0.75) : l’hourly Bitstamp est plus bruitee que la multi-source, ce qui peut amplifier le delta. Le delta intra-Bitstamp (minute vs horaire, même source) reste valide.
- Edge parametrique ~1.1 sigma (sous 2 sigma) : la DIRECTION est airtight (DM p ~ 0), la MAGNITUDE est regime-dependante (voir
research_m12_hf_dm_test.ipynb, pilier 4). Le sign-test cross-fold (5/5 positifs) est marginal (p = 0.0625) par limite de puissance a n = 5 folds.
Comparaison vs horaire (NO BEATS, p=1.0, 11/21 wins)
L’hourly QuantBook (research_m12_har_rv_j.ipynb, bars Coinbase) avait trouve M12 HAR-RV-J NO BEATS (sign-test p=1.0, 11/21 Sharpe wins). Le passage a la grille minute inverse le verdict : la grille minute est assez dense pour que la RV reconstruise proprement les composantes continue et jump. Conclusion renforcee : le résultat M12-HF depend de la resolution de l’estimateur RV (frequence d’echantillonnage), pas uniquement de la source.