Upload 2 files
Browse files- app.py +150 -0
- requirements.txt +10 -0
app.py
ADDED
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import streamlit as st
|
2 |
+
import pandas as pd
|
3 |
+
import numpy as np
|
4 |
+
import yfinance as yf
|
5 |
+
from datetime import date, timedelta
|
6 |
+
import matplotlib.pyplot as plt
|
7 |
+
from pmdarima.arima import auto_arima
|
8 |
+
|
9 |
+
# Custom CSS for professional look
|
10 |
+
st.markdown("""
|
11 |
+
<style>
|
12 |
+
.main {
|
13 |
+
background-color: #f5f5f5;
|
14 |
+
padding: 20px;
|
15 |
+
}
|
16 |
+
.sidebar .sidebar-content {
|
17 |
+
background-color: #fafafa;
|
18 |
+
}
|
19 |
+
.stButton>button {
|
20 |
+
background-color: #2e7d32;
|
21 |
+
color: white;
|
22 |
+
border-radius: 5px;
|
23 |
+
font-weight: bold;
|
24 |
+
}
|
25 |
+
.stButton>button:hover {
|
26 |
+
background-color: #388e3c;
|
27 |
+
}
|
28 |
+
h1, h2, h3 {
|
29 |
+
color: #333;
|
30 |
+
}
|
31 |
+
.stDataFrame {
|
32 |
+
background-color: #ffffff;
|
33 |
+
}
|
34 |
+
.stTable {
|
35 |
+
color: #333;
|
36 |
+
}
|
37 |
+
.stPlotlyChart {
|
38 |
+
background-color: #ffffff;
|
39 |
+
}
|
40 |
+
</style>
|
41 |
+
""", unsafe_allow_html=True)
|
42 |
+
|
43 |
+
# App Title
|
44 |
+
st.title("π Stock Market Forecasting")
|
45 |
+
|
46 |
+
# Sidebar Inputs
|
47 |
+
st.sidebar.header("User Input")
|
48 |
+
|
49 |
+
# Inputs for stock ticker, date range, and forecast days
|
50 |
+
ticker = st.sidebar.text_input("Enter stock ticker:", value="GOOGL")
|
51 |
+
end_date = st.sidebar.date_input("End Date", value=date.today())
|
52 |
+
start_date = st.sidebar.date_input("Start Date", value=date.today() - timedelta(days=365))
|
53 |
+
forecast_days = st.sidebar.slider("Forecast days", min_value=10, max_value=30, value=15)
|
54 |
+
|
55 |
+
# Ensure start_date is not later than end_date
|
56 |
+
if start_date > end_date:
|
57 |
+
st.sidebar.error("β Start date cannot be later than end date.")
|
58 |
+
st.stop()
|
59 |
+
|
60 |
+
# Feature selection for stock attributes (e.g., Close, High, Low, Open)
|
61 |
+
feature_select = st.sidebar.multiselect(
|
62 |
+
label="Select Stock Features to Forecast",
|
63 |
+
options=["Close", "High", "Low", "Open"],
|
64 |
+
default=["Close"]
|
65 |
+
)
|
66 |
+
|
67 |
+
# Feature descriptions (explanation for each stock feature)
|
68 |
+
feature_descriptions = {
|
69 |
+
"Close": "The closing price of the stock at the end of the trading day.",
|
70 |
+
"High": "The highest price at which the stock traded during the day.",
|
71 |
+
"Low": "The lowest price at which the stock traded during the day.",
|
72 |
+
"Open": "The price at which the stock opened at the beginning of the trading day."
|
73 |
+
}
|
74 |
+
|
75 |
+
# Fetch Stock Data based on user input
|
76 |
+
if st.sidebar.button("Fetch Data"):
|
77 |
+
st.subheader(f"Stock Data for {ticker.upper()} ({start_date} to {end_date})")
|
78 |
+
|
79 |
+
try:
|
80 |
+
# Download stock data from Yahoo Finance
|
81 |
+
df = yf.download(ticker, start=start_date, end=end_date, progress=False)
|
82 |
+
|
83 |
+
# Check if data is available
|
84 |
+
if df.empty:
|
85 |
+
st.error("β No data found for the selected ticker or date range.")
|
86 |
+
st.stop()
|
87 |
+
|
88 |
+
st.success("β
Data fetched successfully!")
|
89 |
+
|
90 |
+
# Reset index and insert 'Date' column for better readability
|
91 |
+
df.insert(0, "Date", df.index)
|
92 |
+
df.reset_index(drop=True, inplace=True)
|
93 |
+
|
94 |
+
st.dataframe(df.head()) # Display first few rows of the stock data
|
95 |
+
|
96 |
+
# Initialize an empty DataFrame to store forecasted data for all features
|
97 |
+
combined_forecast_df = pd.DataFrame()
|
98 |
+
|
99 |
+
# Iterate over each selected feature and generate forecasts
|
100 |
+
for feature in feature_select:
|
101 |
+
st.write(f"### π Forecasting: {feature}")
|
102 |
+
st.write(feature_descriptions[feature])
|
103 |
+
|
104 |
+
# Prepare the time series for forecasting (drop NaN values)
|
105 |
+
series = df[feature].dropna()
|
106 |
+
|
107 |
+
# Fit the ARIMA model using the selected feature's time series
|
108 |
+
model = auto_arima(series,
|
109 |
+
start_p=1, start_q=1,
|
110 |
+
max_p=2, max_q=2,
|
111 |
+
m=12, # Monthly seasonal cycle
|
112 |
+
start_P=0,
|
113 |
+
seasonal=True,
|
114 |
+
d=1, D=1,
|
115 |
+
trace=True, # Display fitting progress
|
116 |
+
error_action='ignore',
|
117 |
+
suppress_warnings=True)
|
118 |
+
|
119 |
+
# Forecast future values for the specified number of days
|
120 |
+
forecast = model.predict(n_periods=forecast_days)
|
121 |
+
future_dates = pd.date_range(start=df["Date"].iloc[-1] + timedelta(days=1), periods=forecast_days)
|
122 |
+
|
123 |
+
# Create a DataFrame to hold the forecasted values
|
124 |
+
forecast_df = pd.DataFrame({
|
125 |
+
"Date": future_dates,
|
126 |
+
feature: forecast
|
127 |
+
})
|
128 |
+
|
129 |
+
# Combine the forecasted data for each feature into a single DataFrame
|
130 |
+
combined_forecast_df = pd.merge(combined_forecast_df, forecast_df, on="Date", how="outer") if not combined_forecast_df.empty else forecast_df
|
131 |
+
|
132 |
+
# Plot historical data and forecasted data
|
133 |
+
fig, ax = plt.subplots(figsize=(10, 4))
|
134 |
+
ax.plot(df["Date"], series, label="Historical", color='blue') # Historical data
|
135 |
+
ax.plot(forecast_df["Date"], forecast_df[feature], label="Forecast", color='orange') # Forecasted data
|
136 |
+
ax.set_title(f"{feature} Forecast for {ticker.upper()}")
|
137 |
+
ax.set_xlabel("Date")
|
138 |
+
ax.set_ylabel(feature)
|
139 |
+
ax.legend()
|
140 |
+
|
141 |
+
# Display the plot
|
142 |
+
st.pyplot(fig)
|
143 |
+
|
144 |
+
# Display the combined forecasted data for all selected features
|
145 |
+
st.subheader("Combined Forecasted Data")
|
146 |
+
st.dataframe(combined_forecast_df.head())
|
147 |
+
|
148 |
+
except Exception as e:
|
149 |
+
st.error(f"β An error occurred: {str(e)}")
|
150 |
+
st.stop()
|
requirements.txt
ADDED
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
pandas
|
2 |
+
numpy
|
3 |
+
yfinance
|
4 |
+
matplotlib
|
5 |
+
seaborn
|
6 |
+
plotly
|
7 |
+
scikit-learn
|
8 |
+
statsmodels
|
9 |
+
streamlit
|
10 |
+
pmdarima
|