Spaces:
Sleeping
Sleeping
Sync App files
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218import os
import gradio as gr
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import skops.io as sio
class StockPredictor:
"""
A class used to load stock prediction models, process historical stock data,
and forecast stock prices.
Attributes
----------
model_dir : str
Directory containing the trained models.
data_dir : str
Directory containing the historical stock data CSV files.
models : dict
Dictionary of loaded models.
Methods
-------
load_models(model_dir):
Loads the models from the specified directory.
load_stock_data(ticker):
Loads and processes historical stock data from a CSV file.
forecast(ticker, days):
Forecasts stock prices for the specified ticker and number of days.
"""
def __init__(self, model_dir="model/SKLearn_Models", data_dir="data"):
"""
Initializes the StockPredictor class by loading the models and setting the data directory.
Parameters
----------
model_dir : str
Directory containing the trained models.
data_dir : str
Directory containing the historical stock data CSV files.
"""
self.models = self.load_models(model_dir)
self.data_dir = data_dir
def load_models(self, model_dir):
"""
Loads the models from the specified directory.
Parameters
----------
model_dir : str
Directory containing the trained models.
Returns
-------
dict
Dictionary of loaded models.
"""
models = {}
for file in os.listdir(model_dir):
if file.endswith(".skops"):
ticker = file.split("_")[0]
models[ticker] = sio.load(os.path.join(model_dir, file))
return models
def load_stock_data(self, ticker):
"""
Loads and processes historical stock data from a CSV file.
Parameters
----------
ticker : str
Stock ticker symbol.
Returns
-------
pandas.DataFrame
Processed historical stock data.
"""
# Construct the CSV file path
csv_path = os.path.join(self.data_dir, f"{ticker}.csv")
data = pd.read_csv(csv_path)
# Convert 'date' to datetime
data["date"] = pd.to_datetime(data["date"])
# Filter the data to start from the year 2000
data = data[data["date"] >= "2000-01-01"]
# Sort by date
data.sort_values("date", inplace=True)
# Feature engineering: create new features such as moving averages
data["ma_5"] = data["close"].rolling(window=5).mean()
data["ma_10"] = data["close"].rolling(window=10).mean()
# Drop rows with NaN values created by rolling window
data.dropna(inplace=True)
return data
def forecast(self, ticker, days):
"""
Forecasts stock prices for the specified ticker and number of days.
Parameters
----------
ticker : str
Stock ticker symbol.
days : int
Number of days for forecasting.
Returns
-------
tuple
A tuple containing a DataFrame with dates, actual close values, and predicted close values,
and the file path of the generated plot.
"""
model = self.models.get(ticker)
if model:
# Load historical stock data
data = self.load_stock_data(ticker)
# Take the last 'days' worth of data for prediction
data = data.tail(days)
# Define features
features = ["open", "high", "low", "ma_5", "ma_10"]
X = data[features]
# Make predictions
predictions = model.predict(X)
# Round predictions to 2 decimal places
predictions = np.round(predictions, 2)
# Create a DataFrame with dates and predicted close values
result_df = pd.DataFrame(
{
"date": data["date"],
"actual_close": data["close"],
"predicted_close": predictions,
}
)
# Plot the actual and predicted close values
plt.figure(figsize=(10, 5))
plt.plot(result_df["date"], result_df["actual_close"], label="Actual Close")
plt.plot(
result_df["date"], result_df["predicted_close"], label="Predicted Close"
)
plt.xlabel("Date")
plt.ylabel("Close Price")
plt.title(f"{ticker} Stock Price Prediction")
plt.legend()
plt.grid(True)
plt.xticks(rotation=45)
# Save the plot to a file
plot_path = f"{ticker}_prediction_plot.png"
plt.savefig(plot_path)
plt.close()
return result_df, plot_path
else:
return pd.DataFrame({"Error": ["Model not found"]}), None
def create_gradio_interface(stock_predictor):
"""
Creates the Gradio interface for the stock predictor.
Parameters
----------
stock_predictor : StockPredictor
Instance of the StockPredictor class.
Returns
-------
gradio.Interface
The Gradio interface.
"""
tickers = list(stock_predictor.models.keys())
dropdown = gr.Dropdown(choices=tickers, label="Select Ticker")
slider = gr.Slider(
minimum=1,
maximum=30,
step=1,
label="Number of Days for Forecasting",
)
iface = gr.Interface(
fn=stock_predictor.forecast,
inputs=[dropdown, slider],
outputs=[
gr.DataFrame(headers=["date", "actual_close", "predicted_close"]),
gr.Image(),
],
title="Stock Price Forecasting",
description="Select a ticker and number of days to forecast stock prices.",
)
return iface
if __name__ == "__main__":
# Initialize StockPredictor and create Gradio interface
stock_predictor = StockPredictor(
model_dir="model/SKLearn_Models",
data_dir="data/Cleaned_Kaggle_NASDAQ_Daily_Data",
)
iface = create_gradio_interface(stock_predictor)
# Launch the app
iface.launch()app.pyAdded+218