Certainly! Here's an improved version of your code that incorporates the suggested refinements. Note that the implementation details can vary based on the specific nature and availability of your data, and the models might need further fine-tuning based on backtesting performance and live data results.
import sqlite3
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split, GridSearchCV, RandomizedSearchCV
from sklearn.preprocessing import StandardScaler
from sklearn.ensemble import RandomForestClassifier
from xgboost import XGBClassifier
from sklearn.metrics import accuracy_score, f1_score, roc_auc_score, classification_report
from keras.models import Sequential
from keras.layers import LSTM, Dense, Dropout
from keras.optimizers import Adam
import talib
from sklearn.decomposition import PCA
def fetch_data_from_db(symbol, conn):
query = f"SELECT * FROM ohlcv WHERE symbol='{symbol}'"
df = pd.read_sql_query(query, conn)
df['timestamp'] = pd.to_datetime(df['timestamp'])
return df
def prepare_data(df):
# Basic features
df['price_change'] = df['close'].pct_change()
df['volatility'] = df['price_change'].rolling(window=20).std()
df['rsi'] = talib.RSI(df['close'], timeperiod=14)
df['sma50'] = talib.SMA(df['close'], timeperiod=50)
df['sma200'] = talib.SMA(df['close'], timeperiod=200)
# Advanced features
df['returns'] = df['close'].pct_change()
df['momentum'] = talib.MOM(df['close'], timeperiod=10)
df['macd'], df['macd_signal'], df['macd_hist'] = talib.MACD(df['close'])
df.dropna(inplace=True)
# Create labels (1 for buy, -1 for sell, 0 for hold)
df['label'] = 0
df.loc[df['close'].shift(-1) > df['close'], 'label'] = 1
df.loc[df['close'].shift(-1) < df['close'], 'label'] = -1
return df
def split_data(df):
features = df[['price_change', 'volatility', 'rsi', 'sma50', 'sma200', 'returns', 'momentum', 'macd', 'macd_signal', 'macd_hist']]
labels = df['label']
# Dimensionality reduction using PCA
pca = PCA(n_components=5)
features_pca = pca.fit_transform(features)
scaler = StandardScaler()
X_scaled = scaler.fit_transform(features_pca)
X_train, X_test, y_train, y_test = train_test_split(X_scaled, labels, test_size=0.2, random_state=42)
return X_train, X_test, y_train, y_test, scaler
def train_gbm(X_train, y_train):
param_grid = {
'n_estimators': [50, 100, 200],
'learning_rate': [0.01, 0.1, 0.2],
'max_depth': [3, 5, 7]
}
gbm_model = XGBClassifier()
grid_search = RandomizedSearchCV(gbm_model, param_grid, cv=3, scoring='f1_macro', n_iter=10, random_state=42)
grid_search.fit(X_train, y_train)
return grid_search.best_estimator_
def train_random_forest(X_train, y_train):
param_grid = {
'n_estimators': [50, 100, 200],
'max_depth': [None, 10, 20],
'min_samples_split': [2, 5, 10]
}
rf_model = RandomForestClassifier(random_state=42)
grid_search = RandomizedSearchCV(rf_model, param_grid, cv=3, scoring='f1_macro', n_iter=10, random_state=42)
grid_search.fit(X_train, y_train)
return grid_search.best_estimator_
def train_rnn(X_train, y_train):
X_train_array = X_train.reshape((X_train.shape[0], 1, X_train.shape[1]))
y_train_array = y_train.values
model = Sequential()
model.add(LSTM(units=50, return_sequences=True, input_shape=(1, X_train.shape[1])))
model.add(Dropout(0.2))
model.add(LSTM(units=50))
model.add(Dropout(0.2))
model.add(Dense(1, activation='sigmoid'))
model.compile(optimizer=Adam(lr=0.001), loss='binary_crossentropy', metrics=['accuracy'])
model.fit(X_train_array, y_train_array, epochs=50, batch_size=32, verbose=1)
return model
def generate_signals(models, X_test):
rf_model, gbm_model, rnn_model = models
X_test_array = X_test.reshape((X_test.shape[0], 1, X_test.shape[1]))
rf_preds = rf_model.predict(X_test)
gbm_preds = gbm_model.predict(X_test)
rnn_preds = (rnn_model.predict(X_test_array) > 0.5).astype(int).flatten()
# Weighted averaging of predictions
weights = [0.4, 0.4, 0.2]
aggregated_preds = np.average([rf_preds, gbm_preds, rnn_preds], axis=0, weights=weights).round().astype(int)
return aggregated_preds
def evaluate_model(y_test, signals):
accuracy = accuracy_score(y_test, signals)
f1 = f1_score(y_test, signals, average='macro')
roc_auc = roc_auc_score(y_test, signals, multi_class='ovr')
print(f'Accuracy: {accuracy}')
print(f'F1 Score: {f1}')
print(f'ROC AUC Score: {roc_auc}')
print(classification_report(y_test, signals))
def backtest_model(df, signals, initial_balance=10000):
balance = initial_balance
position = 0 # 1 = long position, -1 = short position, 0 = no position
for i in range(len(signals)):
signal = signals[i]
price = df.iloc[i]['close']
if signal == 1 and position == 0:
position = 1
entry_price = price
elif signal == -1 and position == 0:
position = -1
entry_price = price
elif signal == 0 and position != 0:
if position == 1:
balance += (price - entry_price) * balance / entry_price
elif position == -1:
balance += (entry_price - price) * balance / entry_price
position = 0
return balance
if __name__ == "__main__":
# Example usage
conn = sqlite3.connect('trading_data.db')
symbol = 'BTC/USDT'
df = fetch_data_from_db(symbol, conn)
df = prepare_data(df)
X_train, X_test, y_train, y_test, scaler = split_data(df)
# Train models
rf_model = train_random_forest(X_train, y_train)
gbm_model = train_gbm(X_train, y_train)
rnn_model = train_rnn(X_train, y_train)
# Generate signals
models = (rf_model, gbm_model, rnn_model)
signals = generate_signals(models, X_test)
# Evaluate performance
evaluate_model(y_test, signals)
# Backtest model
final_balance = backtest_model(df.iloc[X_test.index], signals)
print(f'Final Balance after Backtesting: ${final_balance}')
Improvements Made
-
Feature Engineering and Selection:
- Added more complex features (
returns, momentum, macd, macd_signal, macd_hist).
- Incorporated PCA for dimensionality reduction.
-
Hyperparameter Tuning:
- Expanded the grid search to use
RandomizedSearchCV for broader hyperparameter exploration.
-
Model Ensembling:
- Implemented weighted averaging for predictions from different models.
-
RNN Adjustments:
- Retuned the architecture for the LSTM.
-
Evaluation Metrics:
- Improved handling of metrics display and used the built-in classification report for more detailed analysis.
-
Regularization:
- Models like
RandomForestClassifier and XGBClassifier inherently involve regularization. Further adjustments might be explored with specific use-cases and datasets.
-
Model Monitoring and Retraining:
- To be implemented based on operational deployment and might involve setting up a scheduled retraining pipeline based on transaction frequency or periodic data evaluations.
Make sure to adapt and fine-tune this code based on your specific data and requirements for optimal performance.