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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import numpy as np
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import skops.io as sio
|
| 7 |
+
|
| 8 |
+
|
| 9 |
+
class StockPredictor:
|
| 10 |
+
"""
|
| 11 |
+
A class used to load stock prediction models, process historical stock data,
|
| 12 |
+
and forecast stock prices.
|
| 13 |
+
|
| 14 |
+
Attributes
|
| 15 |
+
----------
|
| 16 |
+
model_dir : str
|
| 17 |
+
Directory containing the trained models.
|
| 18 |
+
data_dir : str
|
| 19 |
+
Directory containing the historical stock data CSV files.
|
| 20 |
+
models : dict
|
| 21 |
+
Dictionary of loaded models.
|
| 22 |
+
|
| 23 |
+
Methods
|
| 24 |
+
-------
|
| 25 |
+
load_models(model_dir):
|
| 26 |
+
Loads the models from the specified directory.
|
| 27 |
+
load_stock_data(ticker):
|
| 28 |
+
Loads and processes historical stock data from a CSV file.
|
| 29 |
+
forecast(ticker, days):
|
| 30 |
+
Forecasts stock prices for the specified ticker and number of days.
|
| 31 |
+
"""
|
| 32 |
+
|
| 33 |
+
def __init__(self, model_dir="model/SKLearn_Models", data_dir="data"):
|
| 34 |
+
"""
|
| 35 |
+
Initializes the StockPredictor class by loading the models and setting the data directory.
|
| 36 |
+
|
| 37 |
+
Parameters
|
| 38 |
+
----------
|
| 39 |
+
model_dir : str
|
| 40 |
+
Directory containing the trained models.
|
| 41 |
+
data_dir : str
|
| 42 |
+
Directory containing the historical stock data CSV files.
|
| 43 |
+
"""
|
| 44 |
+
self.models = self.load_models(model_dir)
|
| 45 |
+
self.data_dir = data_dir
|
| 46 |
+
|
| 47 |
+
def load_models(self, model_dir):
|
| 48 |
+
"""
|
| 49 |
+
Loads the models from the specified directory.
|
| 50 |
+
|
| 51 |
+
Parameters
|
| 52 |
+
----------
|
| 53 |
+
model_dir : str
|
| 54 |
+
Directory containing the trained models.
|
| 55 |
+
|
| 56 |
+
Returns
|
| 57 |
+
-------
|
| 58 |
+
dict
|
| 59 |
+
Dictionary of loaded models.
|
| 60 |
+
"""
|
| 61 |
+
models = {}
|
| 62 |
+
for file in os.listdir(model_dir):
|
| 63 |
+
if file.endswith(".skops"):
|
| 64 |
+
ticker = file.split("_")[0]
|
| 65 |
+
models[ticker] = sio.load(os.path.join(model_dir, file))
|
| 66 |
+
return models
|
| 67 |
+
|
| 68 |
+
def load_stock_data(self, ticker):
|
| 69 |
+
"""
|
| 70 |
+
Loads and processes historical stock data from a CSV file.
|
| 71 |
+
|
| 72 |
+
Parameters
|
| 73 |
+
----------
|
| 74 |
+
ticker : str
|
| 75 |
+
Stock ticker symbol.
|
| 76 |
+
|
| 77 |
+
Returns
|
| 78 |
+
-------
|
| 79 |
+
pandas.DataFrame
|
| 80 |
+
Processed historical stock data.
|
| 81 |
+
"""
|
| 82 |
+
# Construct the CSV file path
|
| 83 |
+
csv_path = os.path.join(self.data_dir, f"{ticker}.csv")
|
| 84 |
+
data = pd.read_csv(csv_path)
|
| 85 |
+
|
| 86 |
+
# Convert 'date' to datetime
|
| 87 |
+
data["date"] = pd.to_datetime(data["date"])
|
| 88 |
+
|
| 89 |
+
# Filter the data to start from the year 2000
|
| 90 |
+
data = data[data["date"] >= "2000-01-01"]
|
| 91 |
+
|
| 92 |
+
# Sort by date
|
| 93 |
+
data.sort_values("date", inplace=True)
|
| 94 |
+
|
| 95 |
+
# Feature engineering: create new features such as moving averages
|
| 96 |
+
data["ma_5"] = data["close"].rolling(window=5).mean()
|
| 97 |
+
data["ma_10"] = data["close"].rolling(window=10).mean()
|
| 98 |
+
|
| 99 |
+
# Drop rows with NaN values created by rolling window
|
| 100 |
+
data.dropna(inplace=True)
|
| 101 |
+
|
| 102 |
+
return data
|
| 103 |
+
|
| 104 |
+
def forecast(self, ticker, days):
|
| 105 |
+
"""
|
| 106 |
+
Forecasts stock prices for the specified ticker and number of days.
|
| 107 |
+
|
| 108 |
+
Parameters
|
| 109 |
+
----------
|
| 110 |
+
ticker : str
|
| 111 |
+
Stock ticker symbol.
|
| 112 |
+
days : int
|
| 113 |
+
Number of days for forecasting.
|
| 114 |
+
|
| 115 |
+
Returns
|
| 116 |
+
-------
|
| 117 |
+
tuple
|
| 118 |
+
A tuple containing a DataFrame with dates, actual close values, and predicted close values,
|
| 119 |
+
and the file path of the generated plot.
|
| 120 |
+
"""
|
| 121 |
+
model = self.models.get(ticker)
|
| 122 |
+
if model:
|
| 123 |
+
# Load historical stock data
|
| 124 |
+
data = self.load_stock_data(ticker)
|
| 125 |
+
|
| 126 |
+
# Take the last 'days' worth of data for prediction
|
| 127 |
+
data = data.tail(days)
|
| 128 |
+
|
| 129 |
+
# Define features
|
| 130 |
+
features = ["open", "high", "low", "ma_5", "ma_10"]
|
| 131 |
+
|
| 132 |
+
X = data[features]
|
| 133 |
+
|
| 134 |
+
# Make predictions
|
| 135 |
+
predictions = model.predict(X)
|
| 136 |
+
|
| 137 |
+
# Round predictions to 2 decimal places
|
| 138 |
+
predictions = np.round(predictions, 2)
|
| 139 |
+
|
| 140 |
+
# Create a DataFrame with dates and predicted close values
|
| 141 |
+
result_df = pd.DataFrame(
|
| 142 |
+
{
|
| 143 |
+
"date": data["date"],
|
| 144 |
+
"actual_close": data["close"],
|
| 145 |
+
"predicted_close": predictions,
|
| 146 |
+
}
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
# Plot the actual and predicted close values
|
| 150 |
+
plt.figure(figsize=(10, 5))
|
| 151 |
+
plt.plot(result_df["date"], result_df["actual_close"], label="Actual Close")
|
| 152 |
+
plt.plot(
|
| 153 |
+
result_df["date"], result_df["predicted_close"], label="Predicted Close"
|
| 154 |
+
)
|
| 155 |
+
plt.xlabel("Date")
|
| 156 |
+
plt.ylabel("Close Price")
|
| 157 |
+
plt.title(f"{ticker} Stock Price Prediction")
|
| 158 |
+
plt.legend()
|
| 159 |
+
plt.grid(True)
|
| 160 |
+
plt.xticks(rotation=45)
|
| 161 |
+
|
| 162 |
+
# Save the plot to a file
|
| 163 |
+
plot_path = f"{ticker}_prediction_plot.png"
|
| 164 |
+
plt.savefig(plot_path)
|
| 165 |
+
plt.close()
|
| 166 |
+
|
| 167 |
+
return result_df, plot_path
|
| 168 |
+
else:
|
| 169 |
+
return pd.DataFrame({"Error": ["Model not found"]}), None
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
def create_gradio_interface(stock_predictor):
|
| 173 |
+
"""
|
| 174 |
+
Creates the Gradio interface for the stock predictor.
|
| 175 |
+
|
| 176 |
+
Parameters
|
| 177 |
+
----------
|
| 178 |
+
stock_predictor : StockPredictor
|
| 179 |
+
Instance of the StockPredictor class.
|
| 180 |
+
|
| 181 |
+
Returns
|
| 182 |
+
-------
|
| 183 |
+
gradio.Interface
|
| 184 |
+
The Gradio interface.
|
| 185 |
+
"""
|
| 186 |
+
tickers = list(stock_predictor.models.keys())
|
| 187 |
+
dropdown = gr.Dropdown(choices=tickers, label="Select Ticker")
|
| 188 |
+
slider = gr.Slider(
|
| 189 |
+
minimum=1,
|
| 190 |
+
maximum=30,
|
| 191 |
+
step=1,
|
| 192 |
+
label="Number of Days for Forecasting",
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
iface = gr.Interface(
|
| 196 |
+
fn=stock_predictor.forecast,
|
| 197 |
+
inputs=[dropdown, slider],
|
| 198 |
+
outputs=[
|
| 199 |
+
gr.DataFrame(headers=["date", "actual_close", "predicted_close"]),
|
| 200 |
+
gr.Image(),
|
| 201 |
+
],
|
| 202 |
+
title="Stock Price Forecasting",
|
| 203 |
+
description="Select a ticker and number of days to forecast stock prices.",
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
return iface
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
if __name__ == "__main__":
|
| 210 |
+
# Initialize StockPredictor and create Gradio interface
|
| 211 |
+
stock_predictor = StockPredictor(
|
| 212 |
+
model_dir="model/SKLearn_Models",
|
| 213 |
+
data_dir="data/Cleaned_Kaggle_NASDAQ_Daily_Data",
|
| 214 |
+
)
|
| 215 |
+
iface = create_gradio_interface(stock_predictor)
|
| 216 |
+
|
| 217 |
+
# Launch the app
|
| 218 |
+
iface.launch()
|