Spaces:
Running
Running
import streamlit as st | |
from datetime import date | |
import yfinance as yf | |
from fbprophet import Prophet | |
from fbprophet.plot import plot_plotly | |
from plotly import graph_objs as go | |
# Constants for date range | |
START = "2015-01-01" | |
TODAY = date.today().strftime("%Y-%m-%d") | |
# Streamlit app title | |
st.title('Stock Forecast App') | |
# Stock selection | |
stocks = ('GOOG', 'AAPL', 'MSFT', 'GME') | |
selected_stock = st.selectbox('Select dataset for prediction', stocks) | |
# Years of prediction slider | |
n_years = st.slider('Years of prediction:', 1, 4) | |
period = n_years * 365 | |
def load_data(ticker): | |
"""Load stock data from Yahoo Finance.""" | |
data = yf.download(ticker, START, TODAY) | |
data.reset_index(inplace=True) | |
return data | |
# Load data and show loading state | |
data_load_state = st.text('Loading data...') | |
data = load_data(selected_stock) | |
data_load_state.text('Loading data... done!') | |
# Display raw data | |
st.subheader('Raw data') | |
st.write(data.tail()) | |
# Plot raw data function | |
def plot_raw_data(): | |
fig = go.Figure() | |
fig.add_trace(go.Scatter(x=data['Date'], y=data['Open'], name="Stock Open")) | |
fig.add_trace(go.Scatter(x=data['Date'], y=data['Close'], name="Stock Close")) | |
fig.layout.update(title_text='Time Series Data with Rangeslider', xaxis_rangeslider_visible=True) | |
st.plotly_chart(fig) | |
# Call the plotting function | |
plot_raw_data() | |
# Prepare data for Prophet model | |
df_train = data[['Date', 'Close']] | |
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"}) | |
# Create and fit the Prophet model | |
m = Prophet() | |
m.fit(df_train) | |
# Create future dataframe and make predictions | |
future = m.make_future_dataframe(periods=period) | |
forecast = m.predict(future) | |
# Show forecast data and plot forecast | |
st.subheader('Forecast data') | |
st.write(forecast.tail()) | |
st.write(f'Forecast plot for {n_years} years') | |
fig1 = plot_plotly(m, forecast) | |
st.plotly_chart(fig1) | |
# Show forecast components | |
st.write("Forecast components") | |
fig2 = m.plot_components(forecast) | |
st.write(fig2) | |