#Building a stock prediction app

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


START = "2015-01-01"
TODAY = date.today().strftime("%Y-%m-%d")

st.title ("Stock Prediction App")

stocks = ("NFLX", "DIS", "CSCO","NTAP", "AMZN", "BABA", "TSLA", "UBER", "AAPL", "MSFT")
selected_stocks = st.selectbox("Select dataset for prediction", stocks)

n_years = st.slider("Years of prediction:", 1, 4 ) #Add a slider to select the number of years for prediction
period = n_years * 365

@st.cache #This will cash the data
def load_data(ticker):
    data = yf.download(ticker, START, TODAY)
    data.reset_index(inplace=True)
    return data

data_load_state = st.text("Load data...")
data = load_data(selected_stocks)
data_load_state.text("Loading data...done!")

st.subheader('Raw Data')
st.write(data.tail())

#Let's plot this raw data
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["Open"], name='stock_close'))
    fig.layout.update(title_text="Time Series Data", xaxis_rangeslider_visible = True)
    st.plotly_chart(fig)

plot_raw_data()

#Now we are doing some Forecasting
df_train = data[['Date', 'Close']]
df_train = df_train.rename(columns={"Date": "ds", "Close": "y"})

m = Prophet()
m.fit(df_train)
future = m.make_future_dataframe(periods=period) #Dataframe which goes into the future
forecast = m.predict(future)

st.subheader('Forecast data')
st.write(forecast.tail())

#Plot the forcasting data
st.write('forecast data')
fig1 = plot_plotly(m, forecast)
st.plotly_chart(fig1)

st.write('forecast components')
fig2 = m.plot_components(forecast)
st.write(fig2)

