import pandas as pd import streamlit as st from vnstock import * import seaborn as sns import matplotlib.pyplot as plt import plotly.express as px import plotly.graph_objects as go import statsmodels.api as sm from statsmodels.tsa.arima.model import ARIMA from prophet import Prophet from datetime import datetime, timedelta import pytz start_date = str((datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')) - timedelta(days=365)).strftime("%Y-%m-%d")) end_date = str((datetime.now(pytz.timezone('Asia/Ho_Chi_Minh')) - timedelta(days=0)).strftime("%Y-%m-%d")) def prophet_ts(symbol, periods = 10): data = stock_historical_data(symbol=symbol, start_date=start_date, end_date=end_date, resolution='1D', type='stock') m = Prophet() pdf = pd.DataFrame() pdf['ds'] = data.index pdf['y'] = data.close.values m.fit(pdf) future = m.make_future_dataframe(periods=periods) forecast = m.predict(future) fig = go.Figure() fig.add_trace(go.Scatter(x= pdf.ds, y=pdf.y, name = f"{symbol}_true" )) fig.add_trace(go.Scatter(x= forecast.ds, y=forecast.yhat, name = f"{symbol}_pred" )) return fig class TS: def __init__(self, symbol): self.symbol = symbol def get_data(self): data = stock_historical_data(symbol=self.symbol, start_date=start_date, end_date=end_date, resolution='1D', type='stock') pdf = pd.DataFrame() pdf["time"] = data["time"] pdf['ds'] = data["time"] pdf['ds'] = pd.to_datetime(pdf['ds']) pdf["open"] = data["open"] pdf["close"] = data["close"] pdf["high"] = data["high"] pdf["low"] = data["low"] pdf['y'] = data.close return pdf def prophet(self, period = 28): df = self.get_data() model = Prophet() model.fit(df) future = model.make_future_dataframe(periods=period) forecast = model.predict(future) return self.viz(df, forecast) def viz(self, data, future): fig = go.Figure() fig.add_trace(go.Candlestick(x = data["time"], open = data["open"], high = data["high"], low = data["low"], close = data["close"], name = f"{self.symbol}" )) fig.add_trace(go.Scatter(x= future.ds, y=future.yhat, name = f"{self.symbol}_pred" )) return fig def arima(self, period = 3): df = self.get_data() df.index = df.ds model = ARIMA(df.y, order = (1, 0, 7)) model = model.fit() forecast = pd.DataFrame() predictions = model.forecast(period) forecast["yhat"] = predictions forecast["ds"] = pd.date_range(start = df.index.max() + timedelta(days = 1), end = df.index.max() + timedelta(days = period)) return self.viz(df, forecast) # ts = TS(symbol = "FPT") # data = ts.arima() # print(data.index.min(), data.index.max()) st.title("Vietnam Trading by Time Series") model = st.selectbox("model", ["Prophet", "ARIMA"]) sb = st.text_input('Symbol', 'VIC') period = st.slider('Period', 1, 365, 28) # fig = prophet_ts(symbol=sb, periods = periods) ts = TS(symbol = sb) fig = None with st.spinner('Wait for it...'): if model == "Prophet": fig = ts.prophet(period = period) elif model == "ARIMA": fig = ts.arima(period = period) st.success('Done!') st.plotly_chart(fig, use_container_width=True)