This Python code is designed to facilitate the training, loading, evaluation, and prediction of stock prices using multiple machine learning models. It provides a comprehensive workflow for processing one or multiple stock symbols, leveraging various algorithms to generate and visualize predictions. Below is a detailed breakdown of each component and its role within the system:
1. load_pretrained_models Function
Purpose:
Loads pre-trained machine learning models for a specified stock symbol from the filesystem.
Parameters:
stock_symbol (str): The ticker symbol of the stock (e.g., "AAPL" for Apple Inc.).
progress_callback (callable, optional): A function to send progress updates or log messages.
Returns:
A list of tuples, each containing a loaded model and its corresponding name (e.g., ('lstm', lstm_model)).
Functionality:
- LSTM Model: Checks for an
.h5 file corresponding to the LSTM model. If found, loads it using TensorFlow's Keras API.
- XGBoost Model: Looks for a
.json file for the XGBoost model and loads it using XGBRegressor.
- Random Forest Model: Searches for a
.pkl file for the Random Forest model and loads it using pandas.read_pickle.
- Linear Regression Model: Similarly, loads the Linear Regression model from a
.pkl file.
- Sends progress updates at each step via the
progress_callback if provided.
- Handles exceptions and logs error messages if any issues occur during loading.
2. evaluate_model Function
Purpose:
Evaluates a given model's performance by computing its Mean Squared Error (MSE) on the test dataset and returns the model's predictions.
Parameters:
model: The trained machine learning model to evaluate.
X_test (array-like): Test features.
y_test (array-like): Actual target values for the test set.
model_name (str): Name of the model (e.g., "lstm", "xgboost").
stock_symbol (str): The stock's ticker symbol.
progress_callback (callable, optional): Function to send progress updates.
Returns:
Predicted values as a NumPy array or None if evaluation fails.
Functionality:
- Generates predictions using the provided model. If the model is an LSTM, it ensures the output is flattened.
- Computes the MSE between actual and predicted values.
- Sends an evaluation summary via
progress_callback.
- Returns the predictions or
None in case of errors.
3. weighted_average_prediction Function
Purpose:
Aggregates predictions from multiple models by computing a weighted average, where weights are inversely proportional to each model's MSE. This approach gives more influence to models with better performance (lower MSE).
Parameters:
models (List[Tuple]): A list of tuples containing models and their names.
X_test (array-like): Test features.
y_test (array-like): Actual target values for the test set.
stock_symbol (str): The stock's ticker symbol.
progress_callback (callable, optional): Function to send progress updates.
Returns:
Final weighted average predictions as a NumPy array or None if computation fails.
Functionality:
- Iterates through each provided model, generates predictions, and calculates the MSE.
- Determines the weight for each model as the inverse of its MSE (
weight = 1 / mse).
- Accumulates the weighted predictions and total weights.
- Computes the final prediction by dividing the sum of weighted predictions by the total weight.
- Handles exceptions and logs errors accordingly.
4. visualize_predictions Function
Purpose:
Generates a plot comparing actual stock prices with predicted prices and optionally saves the plot as an image.
Parameters:
stock_symbol (str): The stock's ticker symbol.
actual (np.ndarray): Actual closing prices.
predicted (np.ndarray): Predicted closing prices.
save (bool, default False): Flag indicating whether to save the plot.
progress_callback (callable, optional): Function to send progress updates.
Functionality:
- Uses Matplotlib to create a plot with actual prices in blue and predicted prices in red dashed lines.
- Adds titles, labels, legends, and grid for better readability.
- If
save is True, saves the plot to a predefined directory (PLOTS_DIR) with a filename incorporating the stock symbol.
- Logs the action via
progress_callback and closes the plot to free resources.
- Handles exceptions and logs errors if plotting fails.
5. process_stock Function
Purpose:
Handles the end-to-end processing of a single stock symbol, including data fetching, preprocessing, model training/loading, prediction, and visualization.
Parameters:
stock_symbol (str): The stock's ticker symbol.
start_date (str): Start date for fetching historical data.
end_date (str): End date for fetching historical data.
interval (str): Data interval (e.g., daily, hourly).
train_mode (str): Operation mode, either 'train' to train new models or 'use' to utilize pre-trained models.
progress_callback (callable, optional): Function to send progress updates.
Returns:
Final predicted stock price as a float or None if processing fails.
Functionality:
-
Data Fetching:
- Calls
fetch_stock_data (assumed to be defined elsewhere) to retrieve historical stock data between start_date and end_date with the specified interval.
- If no data is found, logs the issue and exits.
-
Data Preprocessing:
- Calls
preprocess_data (assumed to be defined elsewhere) to process the fetched data and apply scaling. This typically involves feature engineering such as calculating moving averages, RSI, MACD, Bollinger Bands, etc.
- Splits the data into features (
X) and target (y), then further divides them into training and testing sets.
- Reshapes the data appropriately for LSTM models (which require 3D input).
-
Model Training or Loading:
- If
train_mode is 'train', trains the following models:
- LSTM Model: Trained using
train_lstm_model (assumed to be defined elsewhere).
- XGBoost Model: Trained using
train_xgboost_model.
- Random Forest Model: Trained using
train_random_forest_model.
- Linear Regression Model: Trained using
train_linear_regression_model.
- If
train_mode is 'use', loads pre-trained models using load_pretrained_models.
-
Prediction and Aggregation:
- Utilizes the available models to make predictions on the test set.
- Aggregates the predictions using
weighted_average_prediction to compute a final predicted value.
-
Visualization:
- Calls
visualize_predictions to plot and optionally save the comparison between actual and predicted prices.
-
Return Value:
- Returns the final predicted stock price or
None if any step fails.
6. multi_stock_prediction Function
Purpose:
Processes multiple stock symbols sequentially by invoking process_stock for each, enabling batch processing of stocks for training or prediction.
Parameters:
stock_symbols (List[str]): A list of stock ticker symbols to process.
start_date (str): Start date for fetching historical data.
end_date (str): End date for fetching historical data.
interval (str): Data interval.
train_mode (str): Operation mode, either 'train' or 'use'.
progress_callback (callable, optional): Function to send progress updates.
Returns:
A dictionary mapping each stock symbol to its final predicted price (Dict[str, float]).
Functionality:
- Initializes an empty dictionary to store predictions.
- Iterates over each stock symbol in
stock_symbols.
- Calls
process_stock for each symbol with the provided parameters.
- If a prediction is returned, adds it to the dictionary with the stock symbol as the key.
- Returns the dictionary containing final predictions for all processed stocks.
Overall Workflow
-
Initialization:
The system is set up with directories for trained models (TRAINED_MODELS_DIR) and plots (PLOTS_DIR). It also assumes the existence of functions like fetch_stock_data, preprocess_data, and various train_*_model functions for different algorithms.
-
Processing Stocks:
- For each stock symbol, data is fetched and preprocessed.
- Depending on the
train_mode, models are either trained anew or pre-trained models are loaded.
- Predictions are made using all available models, and a weighted average is computed to derive a final prediction.
- The results are visualized through plots comparing actual and predicted prices.
- Predictions are aggregated into a dictionary for all processed stocks.
-
Usage Scenarios:
- Training Mode (
train_mode='train'):
The system trains new models for each stock, evaluates their performance, and likely saves the trained models for future use.
- Usage Mode (
train_mode='use'):
The system loads existing pre-trained models to make predictions without retraining, which is useful for real-time or future predictions based on historical models.
-
Extensibility:
The modular design allows for easy addition of new models or modification of existing ones. The use of callbacks for progress updates makes the system suitable for integration with user interfaces or logging mechanisms.
Dependencies and Assumptions
-
External Libraries:
tensorflow (for LSTM models)
xgboost (for XGBoost models)
pandas (for data manipulation and model loading)
matplotlib (for plotting)
numpy (for numerical operations)
scikit-learn (for metrics and data splitting)
-
Predefined Directories:
TRAINED_MODELS_DIR: Directory path where trained models are stored.
PLOTS_DIR: Directory path where generated plots are saved.
-
Assumed Functions:
fetch_stock_data: Fetches historical stock data.
preprocess_data: Processes and scales the fetched data.
train_lstm_model, train_xgboost_model, train_random_forest_model, train_linear_regression_model: Functions to train respective models.
Potential Enhancements
-
Parallel Processing:
For handling multiple stocks more efficiently, especially when dealing with a large list of stock symbols.
-
Error Handling:
More granular exception handling and logging to troubleshoot specific issues during different stages of processing.
-
Model Selection:
Incorporating model selection techniques to choose the best-performing models automatically.
-
Hyperparameter Tuning:
Implementing methods for optimizing model hyperparameters to improve prediction accuracy.
-
User Interface Integration:
Connecting the backend processing with a frontend UI to provide real-time feedback and visualization to users.
Conclusion
This code provides a robust framework for stock price prediction using multiple machine learning models. It emphasizes modularity, allowing for easy maintenance and scalability. By supporting both training and usage modes, it caters to scenarios where models need to be updated with new data or when instant predictions are required without retraining.