@staticmethod
def calculate_vwap(df):
df['vwap'] = (df['volume'] * (df['high'] + df['low'] + df['close']) / 3).cumsum() / df['volume'].cumsum()
return df
@staticmethod
def calculate_bollinger_bands(df, window=20, num_std=2):
df['bb_mid'] = df['close'].rolling(window).mean()
df['bb_std'] = df['close'].rolling(window).std()
df['bb_upper'] = df['bb_mid'] + num_std * df['bb_std']
df['bb_lower'] = df['bb_mid'] - num_std * df['bb_std']
return df
@staticmethod
def calculate_atr(df, window=14):
high_low = df['high'] - df['low']
high_close = np.abs(df['high'] - df['close'].shift())
low_close = np.abs(df['low'] - df['close'].shift())
true_range = np.max(np.vstack([high_low, high_close, low_close]), axis=0)
df['atr'] = pd.Series(true_range).rolling(window).mean()
return df
@staticmethod
def calculate_moving_averages(df, periods=[5, 8, 13, 21, 34, 55, 89]):
for period in periods:
df[f'ema_{period}'] = df['close'].ewm(span=period, adjust=False).mean()
df[f'sma_{period}'] = df['close'].rolling(window=period).mean()
return df
@staticmethod
def calculate_rsi(df, periods=[7, 14, 21]):
for period in periods:
delta = df['close'].diff()
gain = (delta.where(delta > 0, 0)).rolling(window=period).mean()
loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean()
rs = gain / loss
df[f'rsi_{period}'] = 100 - (100 / (1 + rs))
return df
# Charger les modèles existants au démarrage s'ils existent
self.load_saved_models()
def init_models(self, n_features: int):
self.n_features = n_features
"""Initialise de nouveaux modèles ou charge les existants"""
self.n_features = n_features
if not self.models: # Seulement si aucun modèle n'est chargé
self.models = [self.build_model(self.seq_length, self.n_features) for _ in range(2)]
def load_saved_models(self):
"""Charge les modèles sauvegardés s'ils existent"""
try:
model_files = list(CONFIG['MODEL_DIR'].glob('attention_model_*.keras'))
if model_files:
self.models = []
for model_file in sorted(model_files):
model = load_model(model_file)
self.models.append(model)
self.logger.info(f"Modèle chargé: {model_file}")
print(f"Modèles chargés avec succès: {len(self.models)} modèle(s)")
# Définir n_features basé sur le premier modèle
if self.models:
self.n_features = self.models[0].input_shape[-1]
else:
print("Aucun modèle sauvegardé trouvé. Veuillez d'abord entraîner le modèle.")
except Exception as e:
self.logger.error(f"Erreur lors du chargement des modèles: {str(e)}")
print(f"Erreur lors du chargement des modèles: {str(e)}")
self.models = []
def build_model(self, seq_length, n_features):
inputs = Input(shape=(seq_length, n_features))
x = BatchNormalization()(inputs)
lstm_out = Bidirectional(
LSTM(128, return_sequences=True, dropout=0.2, kernel_regularizer=l2(1e-5))
)(x)
attention_output = MultiHeadAttention(num_heads=4, key_dim=128, dropout=0.1)(lstm_out, lstm_out)
x = GlobalAveragePooling1D()(attention_output)
x = Dense(64, activation='relu')(x)
x = Dropout(0.3)(x)
output = Dense(1, activation='linear')(x)
model = Model(inputs, output)
model.compile(optimizer=Adam(learning_rate=0.0001), loss='mse', metrics=['mae'])
return model
def add_technical_indicators(self, df):
return TechnicalIndicators.calculate_all_indicators(df)
def prepare_data(self, df):
"""
Prépare les données pour l'entraînement ou la prédiction
"""
if df.empty:
self.logger.error("DataFrame vide lors de la préparation des données.")
raise ValueError("Le DataFrame est vide.")
try:
df = self.add_technical_indicators(df)
# On s'assure d'abord que la colonne close est bien au bon niveau de prix
print(f"Prix de clôture min: {df['close'].min():.2f}, max: {df['close'].max():.2f}")
features = [col for col in df.columns if col not in ['date', 'close', 'timeframe']]
x_data = df[features].values
y_data = df['close'].values.reshape(-1, 1) # Reshape pour le scaler
# Vérification des valeurs avant scaling
print(f"Valeurs y avant scaling - min: {y_data.min():.2f}, max: {y_data.max():.2f}")
x_data = np.nan_to_num(x_data, nan=0.0, posinf=1e6, neginf=-1e6)
y_data = np.nan_to_num(y_data, nan=0.0, posinf=1e6, neginf=-1e6)
# Fit les scalers seulement si nécessaire
if not hasattr(self.feature_scaler, 'n_features_in_'):
self.feature_scaler.fit(x_data)
if not hasattr(self.target_scaler, 'n_features_in_'):
self.target_scaler.fit(y_data)
x_data = self.feature_scaler.transform(x_data)
y_data = self.target_scaler.transform(y_data)
# Vérification des valeurs après scaling
y_orig = self.target_scaler.inverse_transform(y_data)
print(f"Test inverse transform - min: {y_orig.min():.2f}, max: {y_orig.max():.2f}")
x, y = [], []
for i in range(len(df) - self.seq_length):
x.append(x_data[i:i + self.seq_length])
y.append(y_data[i + self.seq_length])
if not x or not y:
self.logger.error("Pas assez de données pour créer des séquences.")
raise ValueError("Pas assez de données pour créer des séquences.")
return np.array(x), np.array(y)
except Exception as e:
self.logger.error(f"Erreur dans prepare_data: {str(e)}")
raise e
def train(self, df, update_only=False):
try:
x, y = self.prepare_data(df)
x_train, x_val, y_train, y_val = train_test_split(x, y, test_size=self.validation_split, shuffle=False)
self.init_models(x_train.shape[2])
callbacks = [
EarlyStopping(monitor='val_loss', patience=15, restore_best_weights=True),
ReduceLROnPlateau(monitor='val_loss', factor=0.5, patience=5, min_lr=1e-6),
ModelCheckpoint(CONFIG['MODEL_DIR'] / 'best_model.keras', monitor='val_loss', save_best_only=True)
]
for idx, model in enumerate(self.models):
self.logger.info(f"Entraînement du modèle {idx}...")
history = model.fit(
x_train, y_train,
validation_data=(x_val, y_val),
epochs=self.epochs if not update_only else 10,
batch_size=self.batch_size,
callbacks=callbacks,
verbose=1
)
model.save(CONFIG['MODEL_DIR'] / f'attention_model_{idx}.keras')
self.logger.info(f"Modèle {idx} sauvegardé.")
print("Entraînement terminé.")
except Exception as e:
logging.error(f"Erreur lors de l'entraînement : {str(e)}")
print(f"Erreur lors de l'entraînement : {str(e)}")
def predict(self, df_recent):
x, _ = self.prepare_data(df_recent)
if len(x) < 1:
self.logger.error("Pas assez de données pour la prédiction.")
raise ValueError("Pas assez de données pour la prédiction.")
predictions = [model.predict(x[-1:], verbose=0) for model in self.models]
avg_pred = np.mean(predictions)
return self.target_scaler.inverse_transform([[avg_pred]])[0][0]
def plot_predictions(self, df_recent):
x, y_true = self.prepare_data(df_recent)
y_true = self.target_scaler.inverse_transform(y_true).flatten()
predictions = []
for model in self.models:
pred = model.predict(x, verbose=0)
predictions.append(self.target_scaler.inverse_transform(pred).flatten())
y_pred = np.mean(predictions, axis=0)
plt.figure(figsize=(14, 7))
plt.plot(df_recent['date'][self.seq_length:], y_true, label='Réel', color='blue')
plt.plot(df_recent['date'][self.seq_length:], y_pred, label='Prévisions', color='red', linestyle='--')
plt.xlabel('Date')
plt.ylabel('Prix')
plt.title('Prix Réel vs Prévisions')
plt.legend()
plt.show()
def run_backtesting(self, df, start_date=None, end_date=None, initial_capital=100, lot_size=0.5):
try:
# Conversion des dates
df['date'] = pd.to_datetime(df['date'], errors='coerce')
df.dropna(subset=['date'], inplace=True)
df.set_index('date', inplace=True)
# Filtrer la période de backtesting si applicable
if start_date:
start_date = pd.to_datetime(start_date)
df = df[df.index >= start_date]
if end_date:
end_date = pd.to_datetime(end_date)
df = df[df.index <= end_date]
if df.empty:
print(f"Aucune donnée disponible pour la période de {start_date} à {end_date}.")
return
# Afficher des détails des données d'entrée
print("Vérification des données d'entrée:")
print(f"Prix de clôture moyens: {df['close'].mean():.2f}")
print(f"Prix de clôture min/max: {df['close'].min():.2f}/{df['close'].max():.2f}")
# Préparation des données du début à la fin
x, y_true = self.prepare_data(df)
y_true = self.target_scaler.inverse_transform(y_true).flatten()
# Génération des prédictions par modèle
predictions = []
for i, model in enumerate(self.models):
if model is None:
print(f"Le modèle {i} n'est pas chargé.")
return
pred = model.predict(x, verbose=0)
pred_prices = self.target_scaler.inverse_transform(pred).flatten()
predictions.append(pred_prices)
# Moyenne des prédictions des modèles
y_pred = np.mean(predictions, axis=0)
# Initialisation des variables de trading
capital = initial_capital
position = None
entry_price = 0
trades = []
consecutive_losses = 0
max_consecutive_losses = 3
daily_trades = 0
max_daily_trades = 3
current_day = None
# Exécution de la simulation de trading
for i in range(len(y_pred)):
current_price = y_true[i]
predicted_price = y_pred[i]
trade_day = df.index[self.seq_length + i]
# Réinitialiser le nombre de trades quotidiens
if current_day != trade_day:
current_day = trade_day
daily_trades = 0
# Logique de clôture de position
if position is not None:
profit_loss = 0
price_diff = current_price - entry_price
if position == "long":
profit_loss = price_diff * lot_size
else:
profit_loss = -price_diff * lot_size
capital += profit_loss
trades.append({
'type': position,
'entry': entry_price,
'exit': current_price,
'profit_loss': profit_loss,
'capital': capital,
'date': trade_day
})
position = None
# Logique d'ouverture de position
if position is None and not (daily_trades >= max_daily_trades or consecutive_losses >= max_consecutive_losses):
if predicted_price > current_price:
position = "long"
entry_price = current_price
daily_trades += 1
elif predicted_price < current_price:
position = "short"
entry_price = current_price
daily_trades += 1
# Analyse des résultats de la simulation
if trades:
winning_trades = sum(1 for t in trades if t['profit_loss'] > 0)
total_trades = len(trades)
win_rate = winning_trades / total_trades if total_trades > 0 else 0
profits = [t['profit_loss'] for t in trades if t['profit_loss'] > 0]
losses = [t['profit_loss'] for t in trades if t['profit_loss'] <= 0]
avg_profit = np.mean(profits) if profits else 0
avg_loss = np.mean(losses) if losses else 0
profit_factor = abs(sum(profits) / sum(losses)) if losses and sum(losses) != 0 else float('inf')
# Calcul du drawdown maximum
max_drawdown = 0
peak_capital = initial_capital
for trade in trades:
if trade['capital'] > peak_capital:
peak_capital = trade['capital']
drawdown = (peak_capital - trade['capital']) / peak_capital
if drawdown > max_drawdown:
max_drawdown = drawdown
# Calcul de la série max. de gains consécutifs
if any(t['profit_loss'] > 0 for t in trades):
max_consecutive_wins = max(sum(1 for _ in g) for k, g in itertools.groupby([t['profit_loss'] > 0 for t in trades]) if k)
else:
max_consecutive_wins = 0
# Afficher les résultats du backtesting
print("\n=== Résultats du Backtesting ===")
print(f"Capital initial: ${initial_capital:,.2f}")
print(f"Capital final: ${capital:,.2f}")
print(f"Profit/Perte total: ${(capital - initial_capital):,.2f}")
print(f"Rendement total: {((capital - initial_capital) / initial_capital * 100):.2f}%")
print(f"Nombre total de trades: {total_trades}")
print(f"Win rate: {win_rate:.2%}")
print(f"Profit factor: {profit_factor:.2f}")
print(f"Gain moyen sur trades gagnants: ${avg_profit:,.2f}")
print(f"Perte moyenne sur trades perdants: ${avg_loss:,.2f}")
print(f"Drawdown maximum: {max_drawdown:.2%}")
print(f"Série max. de gains consécutifs: {max_consecutive_wins}")
# Afficher les 5 derniers trades réalisés
print("\nDerniers 5 trades réalisés:")
for trade in trades[-5:]:
print(f"Date: {trade['date']}, Type: {trade['type']}, Entry: {trade['entry']:.2f}, Exit: {trade['exit']:.2f}, "
f"P/L: ${trade['profit_loss']:,.2f}")
else:
print("Aucun trade n'a été effectué pendant la période de test.")
# Afficher le statut de la position ouverte et suggérer une clôture
if position is not None:
print(f"\nPosition ouverte: {position} à un prix d'entrée de {entry_price:.2f}")
# Suggestion de clôture si nécessaire
if position == "long":
print(f"Suggérée de clôturer la position longue à {current_price:.2f} pour réaliser {capital - initial_capital:.2f} de bénéfice/potentiel de gain.")
else:
print(f"Suggérée de clôturer la position courte à {current_price:.2f} pour réaliser {capital - initial_capital:.2f} de bénéfice/potentiel de gain.")
except Exception as e:
print(f"Erreur lors du backtesting: {str(e)}")
import traceback
print(traceback.format_exc())
def calculate_performance_metrics(self, y_true, y_pred):
mape = mean_absolute_percentage_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
print(f"MAPE: {mape:.4f}, R2: {r2:.4f}")