File size: 2,001 Bytes
ebf57c0 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import yfinance as yf
from TSEnsemble.ensemble import Ensemble
from TSEnsemble import arima, nn, utils
# Function to load stock data using yfinance
def get_stock_data(symbol, start_date, end_date):
stock_data = yf.download(symbol, start=start_date, end=end_date)
return stock_data['Close']
# Load stock data
symbol = 'AAPL' # Replace with the desired stock symbol
start_date = '2020-01-01'
end_date = '2023-01-01'
stock_prices = get_stock_data(symbol, start_date, end_date)
# Set up ARIMA, CNN, LSTM, and Transformer models
ar = arima.auto_arima(stock_prices, method='stepwise', season=12, max_p=3, max_q=3, max_Q=3, max_P=3, train_split=0.8, plot=False)
transformer = nn.generate_transformer(
look_back=12,
horizon=1,
n_features=1,
num_transformer_blocks=4,
dropout=0.25,
head_size=256,
num_heads=4,
ff_dim=4,
mlp_units=[128],
mlp_dropout=0.4
)
lstm = nn.generate_rnn(look_back=12, hidden_layers=1, units=64, type="LSTM", dropout=0.0)
cnn = nn.generate_cnn(look_back=12, hidden_layers=3, kernel_size=2, filters=64, dilation_rate=1, dilation_mode="multiplicative")
# Create an ensemble model
ensemble_model = Ensemble(models=[ar, cnn, lstm, transformer], regressor='wmean')
# Fit the ensemble model
ensemble_model.fit(stock_prices, train_size=0.8, look_back=12, val_size=0.2, train_models_size=0.7, epochs=20, batch_size=16, metric="rmse")
# Forecast with the ensemble model
ensemble_forecast = ensemble_model.forecast(stock_prices, steps=12, fig_size=(10, 6))
# Streamlit app
st.title("Stock Price Prediction App")
# Display historical stock prices
st.subheader("Historical Stock Prices")
st.line_chart(stock_prices)
# Display ensemble forecast
st.subheader("Ensemble Forecast")
st.line_chart(ensemble_forecast)
# Display ARIMA forecast
arima_forecast = utils.model_forecast(ar, stock_prices, steps=12)
st.subheader("ARIMA Forecast")
st.line_chart(arima_forecast) |