Here is a simple implementation of a stock trading algorithm using SMA (Simple Moving Average) strategy and hyperparameter optimization with Hyperopt.
import pandas as pd
import numpy as np
from hyperopt import fmin, tpe, hp, STATUS_OK, Trials
from sklearn.metrics import mean_squared_error
# Simple Moving Average Strategy
def SMA_Strategy(data, short_window, long_window):
signals = pd.DataFrame(index=data.index)
signals['signal'] = 0.0
# Short simple moving average
signals['short_mavg'] = data['Close'].rolling(window=short_window, min_periods=1, center=False).mean()
# Long simple moving average
signals['long_mavg'] = data['Close'].rolling(window=long_window, min_periods=1, center=False).mean()
# Create signals
signals['signal'][short_window:] = np.where(signals['short_mavg'][short_window:] > signals['long_mavg'][short_window:], 1.0, 0.0)
# Generate trading orders
signals['positions'] = signals['signal'].diff()
return signals
# Objective function for hyperopt
def objective(params):
short_window = int(params['short_window'])
long_window = int(params['long_window'])
signals = SMA_Strategy(data, short_window, long_window)
# Calculate strategy return
data['strategy_return'] = data['Return'] * signals['positions'].shift()
strategy_return = data['strategy_return'].sum()
# Minimize negative strategy return
return {'loss': -strategy_return, 'status': STATUS_OK}
# Define the hyperparameters space
space = {
'short_window': hp.quniform('short_window', 5, 30, 1),
'long_window': hp.quniform('long_window', 31, 100, 1)
}
# Run the algorithm
trials = Trials()
best = fmin(fn=objective,
space=space,
algo=tpe.suggest,
max_evals=1000,
trials=trials)
print("Best hyperparameters: ", best)
This script is a simple algorithm that uses the Simple Moving Average (SMA) trading strategy and optimizes the parameters (short moving average window and long moving average window) with Hyperopt.
Please replace data with your own stock price data. The 'Close' column should contain the closing prices of the stock, and 'Return' column should contain the daily returns of the stock.
This script uses the TPE (Tree-structured Parzen Estimator) algorithm for hyperparameter optimization, and it iterates 1000 times to find the optimal parameters. The optimal parameters are those that maximize the strategy return.
Please note that this is a simple example and might not be suitable for real trading. You might want to add more sophisticated features or use more advanced models for a real trading strategy.