Spaces:
Sleeping
Sleeping
Sync App files
Browse files
app.py
CHANGED
|
@@ -4,6 +4,7 @@ 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:
|
|
@@ -92,7 +93,10 @@ class StockPredictor:
|
|
| 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 |
|
|
@@ -116,55 +120,84 @@ class StockPredictor:
|
|
| 116 |
-------
|
| 117 |
tuple
|
| 118 |
A tuple containing a DataFrame with dates, actual close values, and predicted close values,
|
| 119 |
-
and the
|
| 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 = ["
|
| 131 |
-
|
| 132 |
-
X = data[features]
|
| 133 |
|
| 134 |
-
#
|
| 135 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 136 |
|
| 137 |
-
#
|
| 138 |
-
|
|
|
|
|
|
|
| 139 |
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 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 |
-
|
|
|
|
|
|
|
| 154 |
)
|
| 155 |
plt.xlabel("Date")
|
| 156 |
-
plt.ylabel("
|
| 157 |
-
plt.title(
|
|
|
|
|
|
|
| 158 |
plt.legend()
|
| 159 |
plt.grid(True)
|
| 160 |
plt.xticks(rotation=45)
|
| 161 |
|
| 162 |
-
# Save the plot to a
|
| 163 |
-
|
| 164 |
-
plt.savefig(
|
|
|
|
|
|
|
| 165 |
plt.close()
|
| 166 |
|
| 167 |
-
return
|
| 168 |
else:
|
| 169 |
return pd.DataFrame({"Error": ["Model not found"]}), None
|
| 170 |
|
|
@@ -197,7 +230,7 @@ def create_gradio_interface(stock_predictor):
|
|
| 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.",
|
|
|
|
| 4 |
import numpy as np
|
| 5 |
import pandas as pd
|
| 6 |
import skops.io as sio
|
| 7 |
+
from io import BytesIO
|
| 8 |
|
| 9 |
|
| 10 |
class StockPredictor:
|
|
|
|
| 93 |
# Sort by date
|
| 94 |
data.sort_values("date", inplace=True)
|
| 95 |
|
| 96 |
+
# Feature engineering: create new features such as year, month, day, and moving averages
|
| 97 |
+
data["year"] = data["date"].dt.year
|
| 98 |
+
data["month"] = data["date"].dt.month
|
| 99 |
+
data["day"] = data["date"].dt.day
|
| 100 |
data["ma_5"] = data["close"].rolling(window=5).mean()
|
| 101 |
data["ma_10"] = data["close"].rolling(window=10).mean()
|
| 102 |
|
|
|
|
| 120 |
-------
|
| 121 |
tuple
|
| 122 |
A tuple containing a DataFrame with dates, actual close values, and predicted close values,
|
| 123 |
+
and the plot as a numpy array.
|
| 124 |
"""
|
| 125 |
model = self.models.get(ticker)
|
| 126 |
if model:
|
| 127 |
# Load historical stock data
|
| 128 |
data = self.load_stock_data(ticker)
|
| 129 |
|
|
|
|
|
|
|
|
|
|
| 130 |
# Define features
|
| 131 |
+
features = ["year", "month", "day", "ma_5", "ma_10"]
|
|
|
|
|
|
|
| 132 |
|
| 133 |
+
# Use the last available values for features
|
| 134 |
+
last_date = data["date"].max()
|
| 135 |
+
next_30_days = pd.date_range(
|
| 136 |
+
start=last_date + pd.Timedelta(days=1), periods=days
|
| 137 |
+
)
|
| 138 |
+
last_values = data[features].iloc[-1].copy()
|
| 139 |
+
last_5_close = data["close"].iloc[-5:].tolist()
|
| 140 |
+
last_10_close = data["close"].iloc[-10:].tolist()
|
| 141 |
+
predictions = []
|
| 142 |
+
|
| 143 |
+
for date in next_30_days:
|
| 144 |
+
last_values["year"] = date.year
|
| 145 |
+
last_values["month"] = date.month
|
| 146 |
+
last_values["day"] = date.day
|
| 147 |
+
|
| 148 |
+
# Ensure input features are in the correct format
|
| 149 |
+
prediction_input = pd.DataFrame([last_values], columns=features)
|
| 150 |
+
prediction = model.predict(prediction_input)[0]
|
| 151 |
+
predictions.append(prediction)
|
| 152 |
+
|
| 153 |
+
# Update the moving averages dynamically
|
| 154 |
+
last_5_close.append(prediction)
|
| 155 |
+
last_10_close.append(prediction)
|
| 156 |
+
if len(last_5_close) > 5:
|
| 157 |
+
last_5_close.pop(0)
|
| 158 |
+
if len(last_10_close) > 10:
|
| 159 |
+
last_10_close.pop(0)
|
| 160 |
+
|
| 161 |
+
last_values["ma_5"] = np.mean(last_5_close)
|
| 162 |
+
last_values["ma_10"] = np.mean(last_10_close)
|
| 163 |
+
|
| 164 |
+
prediction_df = pd.DataFrame(
|
| 165 |
+
{"date": next_30_days, "predicted_close": predictions}
|
| 166 |
+
)
|
| 167 |
|
| 168 |
+
# Concatenate actual and predicted data for plotting
|
| 169 |
+
actual_df = data[["date", "close"]].iloc[-30:].copy()
|
| 170 |
+
actual_df.rename(columns={"close": "actual_close"}, inplace=True)
|
| 171 |
+
plot_data = pd.concat([actual_df, prediction_df], ignore_index=True)
|
| 172 |
|
| 173 |
+
plt.figure(figsize=(14, 7))
|
| 174 |
+
plt.plot(
|
| 175 |
+
plot_data["date"].iloc[:30],
|
| 176 |
+
plot_data["actual_close"].iloc[:30],
|
| 177 |
+
label="Actual",
|
|
|
|
|
|
|
| 178 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 179 |
plt.plot(
|
| 180 |
+
plot_data["date"].iloc[30:],
|
| 181 |
+
plot_data["predicted_close"].iloc[30:],
|
| 182 |
+
label="Predicted",
|
| 183 |
)
|
| 184 |
plt.xlabel("Date")
|
| 185 |
+
plt.ylabel("Stock Price")
|
| 186 |
+
plt.title(
|
| 187 |
+
f"Last 30 Days Actual and Next {days} Days Prediction for {ticker}"
|
| 188 |
+
)
|
| 189 |
plt.legend()
|
| 190 |
plt.grid(True)
|
| 191 |
plt.xticks(rotation=45)
|
| 192 |
|
| 193 |
+
# Save the plot to a numpy array
|
| 194 |
+
buf = BytesIO()
|
| 195 |
+
plt.savefig(buf, format="png")
|
| 196 |
+
buf.seek(0)
|
| 197 |
+
img = np.array(plt.imread(buf))
|
| 198 |
plt.close()
|
| 199 |
|
| 200 |
+
return plot_data, img
|
| 201 |
else:
|
| 202 |
return pd.DataFrame({"Error": ["Model not found"]}), None
|
| 203 |
|
|
|
|
| 230 |
inputs=[dropdown, slider],
|
| 231 |
outputs=[
|
| 232 |
gr.DataFrame(headers=["date", "actual_close", "predicted_close"]),
|
| 233 |
+
gr.Image(type="numpy"),
|
| 234 |
],
|
| 235 |
title="Stock Price Forecasting",
|
| 236 |
description="Select a ticker and number of days to forecast stock prices.",
|