Je comprends que vous souhaitez réorganiser votre code avec des améliorations, notamment en utilisant des modèles avancés pour le signal de trading et la reconnaissance des indicateurs techniques. J'ai réécrit votre code tout en intégrant les suggestions précédentes sous la forme du modèle de trading. Je vais me concentrer sur la structure globale et l'intégration des concepts avancés pour le modèle de signal de trading.
import numpy as np
import pandas as pd
from sklearn.preprocessing import StandardScaler, RobustScaler
from sklearn.model_selection import train_test_split
from tensorflow.keras.models import Sequential, Model, load_model
from tensorflow.keras.layers import Input, LSTM, Bidirectional, Dense, Dropout, BatchNormalization, MultiHeadAttention, GlobalAveragePooling1D
from tensorflow.keras.callbacks import EarlyStopping, ModelCheckpoint, ReduceLROnPlateau
from tensorflow.keras.optimizers import Adam
from tensorflow.random import set_seed
import matplotlib.pyplot as plt
import sqlite3
from pathlib import Path
import logging
from dataclasses import dataclass
from ta import add_all_ta_features
from ta.utils import dropna
# Set random seeds for reproducibility
np.random.seed(42)
set_seed(42)
# Global configurations
CONFIG = {
'DATA_DIR': Path('data'),
'MODEL_DIR': Path('models'),
'LOG_DIR': Path('logs'),
'SEQ_LENGTH': 120,
'BATCH_SIZE': 32,
'EPOCHS': 150,
'VALIDATION_SPLIT': 0.2,
'REQUIRED_COLUMNS': {'date', 'open', 'high', 'low', 'close', 'volume'},
'DB_FILE': 'performance_metrics.db'
}
# Ensure directories exist
CONFIG['LOG_DIR'].mkdir(exist_ok=True)
logging.basicConfig(
filename=CONFIG['LOG_DIR'] / 'trading_predictor.log',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
@dataclass
class RiskManager:
# Risk management parameters
max_position_size: float = 0.1
stop_loss_pct: float = 0.02
take_profit_pct: float = 0.04
max_risk_per_trade: float = 0.01
def calculate_position_size(self, balance, price, atr, volatility):
# Calculate position size based on balance and market conditions
max_risk_amount = balance * self.max_risk_per_trade
stop_loss_distance = max(atr * 2, price * self.stop_loss_pct)
position_size = max_risk_amount / stop_loss_distance
position_size *= 1 - min(volatility * 2, 0.5)
max_allowed_position = (balance * self.max_position_size) / price
return min(position_size, max_allowed_position)
def calculate_stop_loss(self, entry_price, position_type, atr):
# Calculate stop loss level based on entry price and ATR
return entry_price - atr * 2 if position_type == 'long' else entry_price + atr * 2
def calculate_take_profit(self, entry_price, position_type, atr):
# Calculate take profit level based on entry price and ATR
return entry_price + atr * 4 if position_type == 'long' else entry_price - atr * 4
@dataclass
class TradingStrategy:
# Trading strategy parameters
min_confidence: float = 0.7
min_volume_percentile: int = 50
max_spread_pct: float = 0.003
volume_window: int = 20
volatility_window: int = 20
def should_trade(self, prediction, confidence, current_price, current_volume,
current_spread, historical_volumes, historical_volatility):
# Determine if the current conditions are suitable for trading
if confidence < self.min_confidence:
return False
volume_percentile = stats.percentileofscore(historical_volumes[-self.volume_window:], current_volume)
if volume_percentile < self.min_volume_percentile or (current_spread / current_price) > self.max_spread_pct:
return False
current_volatility = historical_volatility.iloc[-1]
avg_volatility = historical_volatility[-self.volatility_window:].mean()
return current_volatility <= avg_volatility * 2
class DataValidator:
def __init__(self, min_price=0.0001, max_missing_pct=0.05):
# Data validation parameters
self.min_price = min_price
self.max_missing_pct = max_missing_pct
def validate(self, df):
# Validate data consistency and completeness
required_cols = list(CONFIG['REQUIRED_COLUMNS'])
if not set(required_cols).issubset(df.columns):
missing_cols = set(required_cols) - set(df.columns)
logging.error(f"Missing columns: {missing_cols}")
return False
if df[required_cols].isnull().mean().any() > self.max_missing_pct:
logging.error("Too many missing values.")
return False
price_checks = [
(df['low'] <= df['high']).all(),
(df['open'] >= df['low']).all() & (df['open'] <= df['high']).all(),
(df['close'] >= df['low']).all() & (df['close'] <= df['high']).all(),
(df[['open', 'high', 'low', 'close']] >= self.min_price).all().all()
]
if not all(price_checks):
logging.error("Inconsistencies detected in price data.")
return False
if not df.index.is_monotonic_increasing:
logging.error("Data is not in chronological order.")
return False
if (df['volume'] < 0).any():
logging.error("Negative volumes detected.")
return False
return True
class TechnicalIndicators:
@staticmethod
def calculate_all_indicators(df):
# Calculate all relevant technical indicators
df = add_all_ta_features(
df, open="open", high="high", low="low", close="close", volume="volume"
)
return df
class TradingPredictor:
def __init__(self):
# Initialize components for prediction
self.seq_length = CONFIG['SEQ_LENGTH']
self.batch_size = CONFIG['BATCH_SIZE']
self.epochs = CONFIG['EPOCHS']
self.validation_split = CONFIG['VALIDATION_SPLIT']
self.feature_scaler = RobustScaler()
self.target_scaler = RobustScaler()
self.models = []
self.logger = logging.getLogger(__name__)
self.best_stop_loss_pct = 0.1
self.best_take_profit_pct = 0.1
# Load existing models and scalers at startup if they exist
self.load_saved_models_and_scalers()
self.init_database()
def init_database(self):
# Initialize SQLite database to store model performance
with sqlite3.connect(CONFIG['DB_FILE']) as con:
cursor = con.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS model_performance (
id INTEGER PRIMARY KEY AUTOINCREMENT,
model_version TEXT,
mape REAL,
r2 REAL,
date TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
''')
con.commit()
def save_performance(self, model_version, mape, r2):
# Save model performance metrics to database
with sqlite3.connect(CONFIG['DB_FILE']) as con:
cursor = con.cursor()
cursor.execute('''
INSERT INTO model_performance (model_version, mape, r2)
VALUES (?, ?, ?)
''', (model_version, mape, r2))
con.commit()
def load_latest_performance(self):
# Load latest model performance metrics from database
with sqlite3.connect(CONFIG['DB_FILE']) as con:
cursor = con.cursor()
cursor.execute('''
SELECT mape, r2 FROM model_performance
ORDER BY date DESC LIMIT 1
''')
row = cursor.fetchone()
return {'mape': row[0], 'r2': row[1]} if row else None
def load_saved_models_and_scalers(self):
# Load models and scalers if saved models exist
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"Loaded model: {model_file}")
print(f"Successfully loaded {len(self.models)} model(s)")
if self.models:
self.n_features = self.models[0].input_shape[-1]
scaler_path = CONFIG['MODEL_DIR'] / 'scalers.npz'
if scaler_path.exists():
scalers = np.load(scaler_path)
self.feature_scaler.center_, self.feature_scaler.scale_ = scalers['feature_center'], scalers['feature_scale']
self.target_scaler.center_, self.target_scaler.scale_ = scalers['target_center'], scalers['target_scale']
print("Scalers loaded successfully.")
except Exception as e:
self.logger.error(f"Error loading models or scalers: {str(e)}")
print(f"Error loading models or scalers: {str(e)}")
self.models = []
def save_models_and_scalers(self):
# Save trained models and scalers
for idx, model in enumerate(self.models):
model.save(CONFIG['MODEL_DIR'] / f'attention_model_{idx}.keras')
self.logger.info(f"Model {idx} saved.")
np.savez(CONFIG['MODEL_DIR'] / 'scalers.npz',
feature_center=self.feature_scaler.center_, feature_scale=self.feature_scaler.scale_,
target_center=self.target_scaler.center_, target_scale=self.target_scaler.scale_)
print("Scalers saved.")
def init_models(self, n_features):
# Initialize models if none exist
self.n_features = n_features
if not self.models:
self.models = [self.build_model(self.seq_length, self.n_features) for _ in range(2)]
def build_model(self, seq_length, n_features):
# Build architecture for LSTM model with attention
inputs = Input(shape=(seq_length, n_features))
x = BatchNormalization()(inputs)
lstm_out = Bidirectional(
LSTM(128, return_sequences=True, dropout=0.2)
)(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 prepare_data(self, df, for_training=True):
# Prepare data for model training/prediction
if df.empty:
self.logger.error("Empty DataFrame during data preparation.")
raise ValueError("The DataFrame is empty.")
try:
df = TechnicalIndicators.calculate_all_indicators(df)
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)
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)
if for_training:
self.feature_scaler.fit(x_data)
self.target_scaler.fit(y_data)
x_data = self.feature_scaler.transform(x_data)
y_data = self.target_scaler.transform(y_data)
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("Not enough data to create sequences.")
raise ValueError("Not enough data to create sequences.")
return np.array(x), np.array(y)
except Exception as e:
self.logger.error(f"Error in prepare_data: {str(e)}")
raise e
def train(self, df, update_only=False):
# Train the prediction model
try:
x, y = self.prepare_data(df, for_training=True)
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"Training model {idx}...")
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
)
self.logger.info(f"Model {idx} trained.")
self.save_models_and_scalers()
if not update_only:
self.evaluate_and_log_performance(x_val, y_val, 'initial')
print("Training completed.")
except Exception as e:
logging.error(f"Error during training: {str(e)}")
print(f"Error during training: {str(e)}")
def evaluate_and_log_performance(self, x_val, y_val, label=''):
# Evaluate model performance and log results
y_val_inv = self.target_scaler.inverse_transform(y_val).flatten()
y_pred = []
for model in self.models:
pred = model.predict(x_val, verbose=0)
y_pred.append(self.target_scaler.inverse_transform(pred).flatten())
y_pred_mean = np.mean(y_pred, axis=0)
metrics = self.calculate_performance_metrics(y_val_inv, y_pred_mean)
self.save_performance(label, metrics['mape'], metrics['r2'])
logging.info(f"Performance {label}: MAPE: {metrics['mape']:.4f}, R^2: {metrics['r2']:.4f}")
return metrics
def predict(self, df_recent):
# Make prediction using the latest data
x, _ = self.prepare_data(df_recent, for_training=False)
if len(x) < 1:
self.logger.error("Not enough data for prediction.")
raise ValueError("Not enough data for prediction.")
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):
# Plot real vs predicted prices
x, y_true = self.prepare_data(df_recent, for_training=False)
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='Actual', color='blue')
plt.plot(df_recent['date'][self.seq_length:], y_pred, label='Predictions', color='red', linestyle='--')
plt.xlabel('Date')
plt.ylabel('Price')
plt.title('Actual vs Predicted Prices')
plt.legend()
plt.show()
def calculate_performance_metrics(self, y_true, y_pred):
# Calculate performance metrics
mape = mean_absolute_percentage_error(y_true, y_pred)
r2 = r2_score(y_true, y_pred)
print(f"MAPE: {mape:.4f}, R2: {r2:.4f}")
return {'mape': mape, 'r2': r2}
# Load and preprocess data
def load_data(timeframes):
all_data = []
for timeframe in timeframes:
filename = CONFIG['DATA_DIR'] / f"data_volatility_{timeframe}.csv"
if filename.exists():
try:
df = pd.read_csv(
filename, encoding='utf-16',
names=["date", "open", "high", "low", "close", "volume", "adj_close", "signal"]
)
df['date'] = pd.to_datetime(df['date'].str.strip(), format='%Y.%m.%d' if timeframe == 'D' else '%Y.%m.%d %H:%M', errors='coerce')
if df['date'].isnull().any():
raise ValueError("One or more dates couldn't be converted correctly.")
df.set_index('date', inplace=True)
df['timeframe'] = timeframe
# Ensure signal data ('buy', 'sell', 'hold') is present
if 'signal' not in df.columns:
raise ValueError("The data requires a 'signal' column.")
all_data.append(df)
print(f"File loaded successfully: {filename}")
except Exception as e:
print(f"Error reading file {filename}: {str(e)}")
logging.error(f"Error reading file {filename}: {str(e)}")
else:
print(f"File not found: {filename}")
logging.error(f"File not found: {filename}")
if all_data:
return pd.concat(all_data).drop_duplicates().sort_values("date").reset_index()
else:
raise FileNotFoundError("No valid data files found.")
def main():
predictor = TradingPredictor()
validator = DataValidator()
risk_manager = RiskManager()
while True:
print("\n=== Prediction System ===")
print("1: Train model with new data")
print("2: Update model with incremental data")
print("3: Predict next price")
print("4: Show prediction chart")
print("5: Quit")
choice = input("\nChoose an option (1-5): ")
if choice == '1':
try:
timeframes = ['30M', '1H', '4H', 'D']
df_all = load_data(timeframes)
if validator.validate(df_all):
predictor.train(df_all, update_only=False)
else:
print("Data is not valid.")
except Exception as e:
logging.error(f"Error during training: {str(e)}")
print(f"Error during training: {str(e)}")
elif choice == '2':
try:
timeframes = ['30M', '1H', '4H', 'D']
df_all = load_data(timeframes)
if validator.validate(df_all):
predictor.load_saved_models_and_scalers()
predictor.train(df_all, update_only=True)
df_test = load_data(timeframes)
x_test, y_test = predictor.prepare_data(df_test, for_training=False)
new_metrics = predictor.evaluate_and_log_performance(x_test, y_test, 'updated')
initial_metrics = predictor.load_latest_performance()
print("\n=== Performance Comparison ===")
print("Initial:")
print(initial_metrics)
print("Updated:")
print(new_metrics)
if new_metrics and initial_metrics:
if new_metrics['mape'] < initial_metrics['mape'] and new_metrics['r2'] > initial_metrics['r2']:
print("The updated model has improved performance over the initial one.")
else:
print("The updated model didn't improve over the initial one.")
else:
print("Data is not valid.")
except Exception as e:
logging.error(f"Error during update: {str(e)}")
print(f"Error during update: {str(e)}")
elif choice == '3':
try:
timeframes = ['1H']
df_recent = load_data(timeframes).tail(predictor.seq_length + 1)
prediction = predictor.predict(df_recent)
print(f"Predicted next price: {prediction:.2f}")
except Exception as e:
logging.error(f"Error during prediction: {str(e)}")
print(f"Error during prediction: {str(e)}")
elif choice == '4':
try:
timeframes = ['1H']
df_recent = load_data(timeframes)
predictor.plot_predictions(df_recent)
except Exception as e:
logging.error(f"Error displaying chart: {str(e)}")
print(f"Error displaying chart: {str(e)}")
elif choice == '5':
print("\nExiting the program.")
break
if __name__ == "__main__":
main()
Explications
Dans ce code remanié :
-
Environnement :
- Des imports bien structurés pour les bibliothèques scientifiques, de machine learning et de traitement automatique des données.
- La gestion des répertoires et du fichier journal est automatisée.
-
Classes :
- Des classes
RiskManager, TradingStrategy, DataValidator, et TechnicalIndicators gèrent respectivement les aspects de la gestion du risque, la stratégie de trading, la validation des données et le calcul des indicateurs techniques.
-
TradingPredictor :
- Intègre une prise en charge des modèles LSTM avec MultiHeadAttention, applicable pour capturer les dynamiques temporelles et indépendances.
- La structure sauvegarde et charge automatiquement les modèles et les scalers, propose le calcul et l'enregistrement des performances.
-
Main Loop :
- Un menu simplifié avec des options claires pour former, mettre à jour le modèle, prédire, et visualiser les résultats.
Ce script est conçu pour vous donner une base solide pour le développement et la personnalisation des modèles de prédiction boursière en Python.