Lancer : Codespaces Colab

title: research_btc_ml cost: api_usd_est: 0.0 api_provider: none cpu_min: 45 gpu_required: false network: true external_account: quantconnect-free free_alternative: null reduced_pedagogical: MyIA.AI.Notebooks/QuantConnect/Python/QC-Py-22-Deep-Learning-LSTM.ipynb reproducibility: MEDIUM metadata_written: 2026-07-23T01:30Z validator: qc_cloud

BTC-ML Strategy Research Notebook

Objectif

Ameliorer le Sharpe ratio de 0.166 vers >0.5 en analysant: 1. L’importance des features du modèle ML 2. Les seuils optimaux de confiance et volatilite 3. Les paramètres de risk management (stop-loss, take-profit) 4. La frequence de retraining optimale

Performance actuelle

  • Sharpe: 0.166
  • CAGR: ~5%
  • Max DD: ~15%

Navigation : Index recherche | << intraday_volume_periodicity | research_composite_ff_aw >>

# Imports et setup QuantBook
from AlgorithmImports import *
import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import TimeSeriesSplit
from sklearn.metrics import accuracy_score
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

qb = QuantBook()
symbol = qb.add_crypto('BTCUSDT', Resolution.DAILY, Market.Binance).symbol
print(f'Symbol: {symbol}, Market: Binance')
Symbol: BTCUSDT, Market: Binance
# Chargement donnees etendues (2019-2025)
start_date = datetime(2019, 1, 1)
end_date = datetime(2025, 12, 31)

history = qb.history([symbol], start_date, end_date, Resolution.DAILY)
print(f"Data loaded: {len(history)} days")
history.head()
Data loaded: 2556 days
close high low open volume
symbol time
BTCUSDT 2019-01-02 3797.14 3810.16 3642.00 3701.23 23741.687033
2019-01-03 3858.56 3882.14 3750.45 3796.45 35156.463369
2019-01-04 3766.78 3862.74 3730.00 3857.57 29406.948359
2019-01-05 3792.01 3823.64 3703.57 3767.20 29519.554671
2019-01-06 3770.96 3840.99 3751.00 3790.09 30490.667751
# Detection des regimes de marche
df = history.droplevel(0).copy()
df['returns'] = df['close'].pct_change()
df['volatility_20'] = df['returns'].rolling(20).std() * np.sqrt(252)
df['sma_200'] = df['close'].rolling(200).mean()

# Classification des regimes
df['regime'] = 'SIDEWAYS'
df.loc[df['close'] > df['sma_200'] * 1.05, 'regime'] = 'BULL'
df.loc[df['close'] < df['sma_200'] * 0.95, 'regime'] = 'BEAR'

# Visualisation
fig, axes = plt.subplots(3, 1, figsize=(14, 10))

# Prix et SMA200
axes[0].plot(df.index, df['close'], label='BTC', alpha=0.8)
axes[0].plot(df.index, df['sma_200'], label='SMA200', linestyle='--')
axes[0].set_title('BTC Price & SMA200')
axes[0].legend()
axes[0].set_yscale('log')

# Volatilite
axes[1].plot(df.index, df['volatility_20'], label='Volatility 20d', color='orange')
axes[1].axhline(y=0.60, color='r', linestyle='--', label='60% threshold')
axes[1].set_title('Annualized Volatility')
axes[1].legend()

# Regimes
regime_colors = {'BULL': 'green', 'BEAR': 'red', 'SIDEWAYS': 'gray'}
for regime in ['BULL', 'BEAR', 'SIDEWAYS']:
    mask = df['regime'] == regime
    axes[2].scatter(df.index[mask], df['close'][mask], c=regime_colors[regime], label=regime, s=10, alpha=0.5)
axes[2].set_title('Market Regimes')
axes[2].legend()
axes[2].set_yscale('log')

plt.tight_layout()
plt.show()

# Stats par regime
print("\nRegime Statistics:")
print(df.groupby('regime')['returns'].agg(['count', 'mean', 'std', 'sum']))

Regime Statistics:
          count      mean       std       sum
regime                                       
BEAR        687 -0.003020  0.037919 -2.074436
BULL       1367  0.003649  0.029091  4.988080
SIDEWAYS    501  0.003271  0.034502  1.638837
# Feature engineering
def compute_features(df):
    """Compute ML features - STRICTEMENT walk-forward"""
    features = pd.DataFrame(index=df.index)
    
    # Price-based features
    features['returns_1d'] = df['close'].pct_change()
    features['returns_5d'] = df['close'].pct_change(5)
    features['returns_20d'] = df['close'].pct_change(20)
    
    # Moving averages
    features['sma_20'] = df['close'].rolling(20).mean() / df['close'] - 1
    features['ema_10'] = df['close'].ewm(span=10).mean() / df['close'] - 1
    features['ema_50'] = df['close'].ewm(span=50).mean() / df['close'] - 1
    features['ema_200'] = df['close'].ewm(span=200).mean() / df['close'] - 1
    
    # RSI
    delta = df['close'].diff()
    gain = delta.where(delta > 0, 0).rolling(14).mean()
    loss = (-delta.where(delta < 0, 0)).rolling(14).mean()
    rs = gain / loss.replace(0, 1e-10)
    features['rsi_14'] = 100 - (100 / (1 + rs))
    
    # Volatility
    features['volatility_20'] = df['returns'].rolling(20).std() * np.sqrt(252)
    features['atr_14'] = (df['high'] - df['low']).rolling(14).mean() / df['close']
    
    # Momentum
    features['momentum_10'] = df['close'] / df['close'].shift(10) - 1
    features['momentum_20'] = df['close'] / df['close'].shift(20) - 1
    
    # Trend strength
    features['price_vs_sma200'] = df['close'] / df['close'].rolling(200).mean() - 1
    
    return features

features = compute_features(df)
features['target'] = (df['close'].shift(-1) > df['close']).astype(int)  # Next day direction

# Nettoyage
features = features.dropna()
print(f"Features shape: {features.shape}")
features.head()
Features shape: (2357, 14)
returns_1d returns_5d returns_20d sma_20 ema_10 ema_50 ema_200 rsi_14 volatility_20 atr_14 momentum_10 momentum_20 price_vs_sma200 target
time
2019-07-20 -0.011562 0.032446 -0.117519 0.054993 0.013871 -0.042511 -0.282836 47.136536 1.030146 0.100697 -0.162565 -0.117519 0.733820 1
2019-07-21 0.022461 -0.009087 -0.010491 0.031287 -0.006874 -0.061052 -0.295160 46.811186 0.984426 0.098608 -0.112991 -0.010491 0.762664 0
2019-07-22 -0.014039 0.121812 -0.003339 0.045804 0.005946 -0.045812 -0.281853 44.955527 0.982605 0.100594 -0.066424 -0.003339 0.728372 0
2019-07-23 -0.023527 0.069549 -0.046348 0.068572 0.024695 -0.021927 -0.261519 37.366076 0.983846 0.099323 -0.120514 -0.046348 0.678703 0
2019-07-24 -0.045975 -0.071727 -0.173793 0.109550 0.060608 0.024219 -0.223347 32.569248 0.918585 0.102627 -0.131286 -0.173793 0.593668 0
# Analyse de l'importance des features
train_end = datetime(2022, 12, 31)
train_data = features[features.index <= train_end]

feature_cols = [c for c in features.columns if c != 'target']
X_train = train_data[feature_cols].values
y_train = train_data['target'].values

# Training
rf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
rf.fit(X_train, y_train)

# Feature importance
importance = pd.DataFrame({
    'feature': feature_cols,
    'importance': rf.feature_importances_
}).sort_values('importance', ascending=True)

plt.figure(figsize=(10, 6))
plt.barh(importance['feature'], importance['importance'])
plt.title('Feature Importance (Random Forest)')
plt.xlabel('Importance')
plt.tight_layout()
plt.show()

print("\nTop 5 features:")
print(importance.tail(5))

Top 5 features:
         feature  importance
5         ema_50    0.078679
4         ema_10    0.079561
1     returns_5d    0.083984
8  volatility_20    0.087426
0     returns_1d    0.117919
# Grid search: Volatility threshold optimal
test_data = features[features.index > train_end]
X_test = test_data[feature_cols].values
y_test = test_data['target'].values

# Probabilites
proba = rf.predict_proba(X_test)
confidence = proba[:, 1]  # Probabilite de hausse

# Test differents seuils de volatilite
vol_thresholds = [0.40, 0.50, 0.60, 0.70, 0.80, 0.90, 1.0]
results_vol = []

for vol_thresh in vol_thresholds:
    mask = test_data['volatility_20'].values <= vol_thresh
    if mask.sum() < 50:
        continue
    
    y_test_masked = y_test[mask]
    pred_masked = (confidence[mask] > 0.5).astype(int)
    
    acc = accuracy_score(y_test_masked, pred_masked)
    
    # Simuler returns avec filtre vol
    returns = test_data['returns_1d'].values[mask]
    positions = np.where(confidence[mask] > 0.55, 1, 0)
    strategy_returns = positions * returns
    
    sharpe = np.mean(strategy_returns) / np.std(strategy_returns) * np.sqrt(252) if np.std(strategy_returns) > 0 else 0
    win_rate = (strategy_returns > 0).sum() / len(strategy_returns) if len(strategy_returns) > 0 else 0
    
    results_vol.append({
        'vol_threshold': vol_thresh,
        'accuracy': acc,
        'sharpe': sharpe,
        'win_rate': win_rate,
        'trades': mask.sum()
    })

results_vol_df = pd.DataFrame(results_vol)
print("\nVolatility Threshold Analysis:")
print(results_vol_df)

best_vol = results_vol_df.loc[results_vol_df['sharpe'].idxmax()]
print(f"\nBest volatility threshold: {best_vol['vol_threshold']:.0%} (Sharpe: {best_vol['sharpe']:.3f})")

Volatility Threshold Analysis:
   vol_threshold  accuracy    sharpe  win_rate  trades
0            0.4  0.521498 -3.298543  0.029126     721
1            0.5  0.521376 -3.637915  0.021898     959
2            0.6  0.526265 -3.810189  0.021401    1028
3            0.7  0.530220 -3.928206  0.022894    1092
4            0.8  0.531022 -3.976403  0.022810    1096
5            0.9  0.531022 -3.976403  0.022810    1096
6            1.0  0.531022 -3.976403  0.022810    1096

Best volatility threshold: 40% (Sharpe: -3.299)
# Grid search: Confidence threshold optimal
confidence_thresholds = [(0.45, 0.55), (0.50, 0.50), (0.55, 0.45), (0.60, 0.40), (0.65, 0.35)]
results_conf = []

for long_thresh, exit_thresh in confidence_thresholds:
    # Positions basees sur confidence
    positions = np.zeros(len(test_data))
    for i in range(len(test_data)):
        if confidence[i] > long_thresh:
            positions[i] = 1
        elif confidence[i] < exit_thresh:
            positions[i] = 0
    
    returns = test_data['returns_1d'].values
    strategy_returns = positions * returns
    
    sharpe = np.mean(strategy_returns) / np.std(strategy_returns) * np.sqrt(252) if np.std(strategy_returns) > 0 else 0
    total_return = (1 + strategy_returns).prod() - 1
    max_dd = (strategy_returns.cumsum() - np.maximum.accumulate(strategy_returns.cumsum())).min()
    
    results_conf.append({
        'long_threshold': long_thresh,
        'exit_threshold': exit_thresh,
        'sharpe': sharpe,
        'total_return': total_return,
        'max_drawdown': max_dd,
        'trades': (np.diff(positions) != 0).sum()
    })

results_conf_df = pd.DataFrame(results_conf)
print("\nConfidence Threshold Analysis:")
print(results_conf_df)

best_conf = results_conf_df.loc[results_conf_df['sharpe'].idxmax()]
print(f"\nBest confidence: Long > {best_conf['long_threshold']:.2f}, Exit < {best_conf['exit_threshold']:.02f}")
print(f"Expected Sharpe: {best_conf['sharpe']:.3f}")

Confidence Threshold Analysis:
   long_threshold  exit_threshold    sharpe  total_return  max_drawdown  \
0            0.45            0.55 -1.402564     -0.896199     -2.231279   
1            0.50            0.50 -3.288892     -0.979073     -3.818950   
2            0.55            0.45 -3.976403     -0.959697     -3.227741   
3            0.60            0.40 -2.038665     -0.563506     -0.809987   
4            0.65            0.35 -0.479726     -0.004578     -0.004578   

   trades  
0     321  
1     364  
2     212  
3      50  
4       2  

Best confidence: Long > 0.65, Exit < 0.35
Expected Sharpe: -0.480
# Grid search: Stop-loss et Take-profit optimaux
stop_loss_values = [0.05, 0.08, 0.10, 0.12, 0.15]
take_profit_values = [0.10, 0.15, 0.20, 0.25, 0.30]

results_sl_tp = []

for sl in stop_loss_values:
    for tp in take_profit_values:
        # Simulation simple avec SL/TP
        returns = test_data['returns_1d'].values
        cum_returns = np.zeros(len(returns))
        position = 0
        entry_price = 0
        
        for i in range(len(returns)):
            if position == 0 and confidence[i] > 0.55:
                position = 1
                entry_price = 100  # Normalise
            elif position == 1:
                current_price = entry_price * (1 + returns[i])
                pnl = (current_price - entry_price) / entry_price
                
                if pnl <= -sl or pnl >= tp or confidence[i] < 0.45:
                    cum_returns[i] = pnl
                    position = 0
                else:
                    cum_returns[i] = returns[i]
        
        sharpe = np.mean(cum_returns) / np.std(cum_returns) * np.sqrt(252) if np.std(cum_returns) > 0 else 0
        total_return = cum_returns.sum()
        
        results_sl_tp.append({
            'stop_loss': sl,
            'take_profit': tp,
            'sharpe': sharpe,
            'total_return': total_return
        })

results_sl_tp_df = pd.DataFrame(results_sl_tp)
results_sl_tp_pivot = results_sl_tp_df.pivot(index='stop_loss', columns='take_profit', values='sharpe')

plt.figure(figsize=(10, 6))
plt.imshow(results_sl_tp_pivot.values, cmap='RdYlGn', aspect='auto')
plt.colorbar(label='Sharpe Ratio')
plt.xticks(range(len(take_profit_values)), [f'{x:.0%}' for x in take_profit_values])
plt.yticks(range(len(stop_loss_values)), [f'{x:.0%}' for x in stop_loss_values])
plt.xlabel('Take Profit')
plt.ylabel('Stop Loss')
plt.title('Sharpe Ratio: Stop-Loss vs Take-Profit')
plt.tight_layout()
plt.show()

best_sl_tp = results_sl_tp_df.loc[results_sl_tp_df['sharpe'].idxmax()]
print(f"\nBest SL/TP: Stop {best_sl_tp['stop_loss']:.0%}, TP {best_sl_tp['take_profit']:.0%}")
print(f"Expected Sharpe: {best_sl_tp['sharpe']:.3f}")

Best SL/TP: Stop 10%, TP 10%
Expected Sharpe: 0.785
# Walk-forward validation
print("\n=== WALK-FORWARD VALIDATION ===")

# Split en 5 periodes
n_splits = 5
tscv = TimeSeriesSplit(n_splits=n_splits)

wf_results = []
train_score_total = 0
test_score_total = 0

for fold, (train_idx, test_idx) in enumerate(tscv.split(features)):
    X_train_wf = features.iloc[train_idx][feature_cols].values
    y_train_wf = features.iloc[train_idx]['target'].values
    X_test_wf = features.iloc[test_idx][feature_cols].values
    y_test_wf = features.iloc[test_idx]['target'].values
    
    rf_wf = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=42)
    rf_wf.fit(X_train_wf, y_train_wf)
    
    train_acc = rf_wf.score(X_train_wf, y_train_wf)
    test_acc = rf_wf.score(X_test_wf, y_test_wf)
    
    train_score_total += train_acc
    test_score_total += test_acc
    
    wf_results.append({
        'fold': fold + 1,
        'train_size': len(train_idx),
        'test_size': len(test_idx),
        'train_acc': train_acc,
        'test_acc': test_acc
    })
    print(f"Fold {fold+1}: Train acc={train_acc:.2%}, Test acc={test_acc:.2%}")

wf_df = pd.DataFrame(wf_results)
avg_train = train_score_total / n_splits
avg_test = test_score_total / n_splits
ratio = avg_test / avg_train if avg_train > 0 else 0

print(f"\nAverage Train: {avg_train:.2%}")
print(f"Average Test: {avg_test:.2%}")
print(f"OOS/IS Ratio: {ratio:.1%}")

if ratio > 0.6:
    print("PASS: Model generalizes well (ratio > 60%)")
else:
    print("FAIL: Model overfits (ratio < 60%)")

=== WALK-FORWARD VALIDATION ===
Fold 1: Train acc=88.92%, Test acc=52.81%
Fold 2: Train acc=82.26%, Test acc=52.30%
Fold 3: Train acc=77.31%, Test acc=57.91%
Fold 4: Train acc=77.50%, Test acc=55.61%
Fold 5: Train acc=71.81%, Test acc=48.47%

Average Train: 79.56%
Average Test: 53.42%
OOS/IS Ratio: 67.1%
PASS: Model generalizes well (ratio > 60%)

Synthese et Recommandations

Paramètres optimaux identifies

D’après les analyses ci-dessus, voici les paramètres recommandes:

# Resume des recommandations
print("\n" + "="*60)
print("RECOMMANDATIONS POUR BTC-ML")
print("="*60)

recommendations = {
    'volatility_threshold': best_vol['vol_threshold'],
    'confidence_long': best_conf['long_threshold'],
    'confidence_exit': best_conf['exit_threshold'],
    'stop_loss': best_sl_tp['stop_loss'],
    'take_profit': best_sl_tp['take_profit'],
    'expected_sharpe': max(best_vol['sharpe'], best_conf['sharpe'], best_sl_tp['sharpe']),
    'walk_forward_ratio': ratio
}

print(f"""
Parametres actuels:
- VOLATILITY_THRESHOLD = 0.60
- CONFIDENCE_LONG_THRESHOLD = 0.55
- CONFIDENCE_EXIT_THRESHOLD = 0.45
- STOP_LOSS_PCT = 0.10
- TAKE_PROFIT_PCT = 0.20

Parametres recommandes:
- VOLATILITY_THRESHOLD = {recommendations['volatility_threshold']:.0%}
- CONFIDENCE_LONG_THRESHOLD = {recommendations['confidence_long']:.2f}
- CONFIDENCE_EXIT_THRESHOLD = {recommendations['confidence_exit']:.2f}
- STOP_LOSS_PCT = {recommendations['stop_loss']:.0%}
- TAKE_PROFIT_PCT = {recommendations['take_profit']:.0%}

Sharpe attendu: {recommendations['expected_sharpe']:.3f}
Walk-forward ratio: {recommendations['walk_forward_ratio']:.1%}
""")

# Export JSON pour application
import json
print("\nJSON pour mise a jour du code:")
print(json.dumps(recommendations, indent=2))

============================================================
RECOMMANDATIONS POUR BTC-ML
============================================================

Parametres actuels:
- VOLATILITY_THRESHOLD = 0.60
- CONFIDENCE_LONG_THRESHOLD = 0.55
- CONFIDENCE_EXIT_THRESHOLD = 0.45
- STOP_LOSS_PCT = 0.10
- TAKE_PROFIT_PCT = 0.20

Parametres recommandes:
- VOLATILITY_THRESHOLD = 40%
- CONFIDENCE_LONG_THRESHOLD = 0.65
- CONFIDENCE_EXIT_THRESHOLD = 0.35
- STOP_LOSS_PCT = 10%
- TAKE_PROFIT_PCT = 10%

Sharpe attendu: 0.785
Walk-forward ratio: 67.1%


JSON pour mise a jour du code:
{
  "volatility_threshold": 0.4,
  "confidence_long": 0.65,
  "confidence_exit": 0.35,
  "stop_loss": 0.1,
  "take_profit": 0.1,
  "expected_sharpe": 0.785008530792587,
  "walk_forward_ratio": 0.6714526097118796
}

Lecture D1-D3 : ce que les sorties valent comme preuve

Ce carnet n’imprime pas de jeton de verdict. Ses sorties disent : Expected Sharpe: -0.480 (grille de confiance), Expected Sharpe: 0.785 (grille stop-loss / take-profit), PASS: Model generalizes well (ratio > 60%) (validation walk-forward), et un expected_sharpe de 0.785 dans le resume. Lu sur le code et les sorties :

  • D1 – stationnarite : le decoupage existe (train_end = datetime(2022, 12, 31), test apres cette date), mais les trois grilles choisissent leur meilleur Sharpe sur le test (results_vol_df.loc[results_vol_df['sharpe'].idxmax()], et de meme pour la confiance et pour stop-loss / take-profit). Le 0.785 est le maximum de trois grilles lues sur la periode de test (max(best_vol['sharpe'], best_conf['sharpe'], best_sl_tp['sharpe'])), pas une performance hors echantillon.
  • D2 – separabilite : aucune baseline (buy-and-hold, majoritaire) et aucun cout de transaction. De plus, strategy_returns = positions * returns utilise returns_1d, le rendement qui va de la veille au jour meme : la position decidee avec les donnees du jour est remuneree par le rendement qui a conduit a ce jour.
  • D3 – exploration non appariee : une seule graine (random_state=42), un seul decoupage. Le « PASS » de la validation porte sur un ratio d’exactitude de classification OOS/IS de 67.1%, pas sur un resultat de trading.

Ces trois ecarts portent sur le protocole de mesure, pas sur la lecture des sorties : les corriger demande de choisir les parametres sur le seul entrainement, de decaler le rendement d’un jour, d’ajouter une baseline et les couts, puis de repeter sur plusieurs graines avant de lire un Sharpe.

Retour au sommet