Spaces:
Sleeping
Sleeping
File size: 6,453 Bytes
ae131a8 4ebb53d ae131a8 4ebb53d ae131a8 4708b6f ae131a8 4ebb53d f6a2537 4ebb53d 6d1de8e ae131a8 6d1de8e 4ebb53d 6db8df3 ae131a8 4ebb53d ae131a8 6d1de8e 4ebb53d 6db8df3 ae131a8 4ebb53d ae131a8 6d1de8e 4ebb53d ae131a8 4ebb53d ae131a8 |
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 |
import streamlit as st
import numpy as np
import pandas as pd
import yfinance as yf
from datetime import datetime
from tensorflow.keras.models import load_model
from joblib import load
# Load the saved LSTM model and scaler
lstm_model = load_model('lstm_model.h5')
scaler = load('scaler.joblib')
# Dictionary of stock tickers and their full names
stock_dict = {
'GOOG': 'Alphabet Inc.',
'AAPL': 'Apple Inc.',
'TSLA': 'Tesla, Inc.',
'AMZN': 'Amazon.com, Inc.',
'MSFT': 'Microsoft Corporation'
}
# Function to get the last row of stock data
def get_last_stock_data(ticker):
try:
start_date = '2010-01-01'
end_date = datetime.now().strftime('%Y-%m-%d')
data = yf.download(ticker, start=start_date, end=end_date)
last_row = data.iloc[-1]
return last_row.to_dict()
except Exception as e:
return str(e)
# Function to make predictions
def predict_stock_price(ticker, open_price, close_price):
try:
start_date = '2010-01-01'
end_date = datetime.now().strftime('%Y-%m-%d')
data = yf.download(ticker, start=start_date, end=end_date)
# Prepare the data
data = data[['Close']]
dataset = data.values
scaled_data = scaler.transform(dataset)
# Append the user inputs as the last row in the data
user_input = np.array([[close_price]])
user_input_scaled = scaler.transform(user_input)
scaled_data = np.vstack([scaled_data, user_input_scaled])
# Prepare the data for LSTM
x_test_lstm = []
for i in range(60, len(scaled_data)):
x_test_lstm.append(scaled_data[i-60:i])
x_test_lstm = np.array(x_test_lstm)
x_test_lstm = np.reshape(x_test_lstm, (x_test_lstm.shape[0], x_test_lstm.shape[1], 1))
# LSTM Predictions
lstm_predictions = lstm_model.predict(x_test_lstm)
lstm_predictions = scaler.inverse_transform(lstm_predictions)
next_day_lstm_price = lstm_predictions[-1][0]
result = f"Predicted future price for {ticker}: ${next_day_lstm_price:.2f}"
return result
except Exception as e:
return str(e)
# Function to predict next month's price
def predict_next_month_price(ticker, close_price):
try:
start_date = '2010-01-01'
end_date = datetime.now().strftime('%Y-%m-%d')
data = yf.download(ticker, start=start_date, end=end_date)
# Prepare the data
data = data[['Close']]
dataset = data.values
scaled_data = scaler.transform(dataset)
# Append the user inputs as the last row in the data
user_input = np.array([[close_price]])
user_input_scaled = scaler.transform(user_input)
scaled_data = np.vstack([scaled_data, user_input_scaled])
# Prepare the data for LSTM
x_test_lstm = []
for i in range(60, len(scaled_data)):
x_test_lstm.append(scaled_data[i-60:i])
x_test_lstm = np.array(x_test_lstm)
x_test_lstm = np.reshape(x_test_lstm, (x_test_lstm.shape[0], x_test_lstm.shape[1], 1))
# Predicting the next 30 days
predictions = []
for _ in range(30):
pred = lstm_model.predict(x_test_lstm[-1].reshape(1, 60, 1))
predictions.append(pred[0])
new_input = np.append(x_test_lstm[-1][1:], pred)
x_test_lstm = np.append(x_test_lstm, new_input.reshape(1, 60, 1), axis=0)
predictions = np.array(predictions)
next_month_predictions = scaler.inverse_transform(predictions)
next_month_price = next_month_predictions[-1][0]
result = f"Predicted price for {ticker} next month: ${next_month_price:.2f}"
return result
except Exception as e:
return str(e)
# Function to display historical data
def display_historical_data(ticker):
try:
start_date = '2010-01-01'
end_date = datetime.now().strftime('%Y-%m-%d')
data = yf.download(ticker, start=start_date, end=end_date)
return data.tail(30).iloc[::-1] # Reverse to have the latest date on top
except Exception as e:
return str(e)
# Streamlit interface
st.title("Stockstream")
# Sidebar for adding new stocks
st.sidebar.header("Add a New Stock Ticker")
new_ticker = st.sidebar.text_input("Stock Ticker", value="")
new_full_name = st.sidebar.text_input("Full Name", value="")
if st.sidebar.button("Add Stock Ticker"):
if new_ticker and new_full_name:
stock_dict[new_ticker.upper()] = new_full_name
# Sidebar for viewing historical trends
st.sidebar.header("View Historical Trends")
historical_ticker_input = st.sidebar.selectbox("Stock Ticker", [f"{key} - {value}" for key, value in stock_dict.items()], key="sidebar_historical_ticker")
if st.sidebar.button("View Historical Data"):
ticker = historical_ticker_input.split(' - ')[0]
data = display_historical_data(ticker)
st.sidebar.line_chart(data['Close'])
# Tabs for different functionalities
tab1, tab2, tab3 = st.tabs(["Today's Price", "Next Month's Price", "Historical Data"])
with tab1:
st.header("Today's Price")
ticker_input = st.selectbox("Stock Ticker", [f"{key} - {value}" for key, value in stock_dict.items()], key="today_ticker")
open_price = st.number_input("Open Price", value=0.0, key="today_open_price")
close_price = st.number_input("Close Price", value=0.0, key="today_close_price")
if st.button("Predict Today's Price"):
ticker = ticker_input.split(' - ')[0]
result = predict_stock_price(ticker, open_price, close_price)
st.write(result)
with tab2:
st.header("Next Month's Price")
next_month_ticker_input = st.selectbox("Stock Ticker", [f"{key} - {value}" for key, value in stock_dict.items()], key="next_month_ticker")
next_month_close_price = st.number_input("Close Price", value=0.0, key="next_month_close_price")
if st.button("Predict Next Month's Price"):
ticker = next_month_ticker_input.split(' - ')[0]
result = predict_next_month_price(ticker, next_month_close_price)
st.write(result)
with tab3:
st.header("Historical Data")
historical_ticker_input = st.selectbox("Stock Ticker", [f"{key} - {value}" for key, value in stock_dict.items()], key="historical_ticker")
if st.button("View Data"):
ticker = historical_ticker_input.split(' - ')[0]
data = display_historical_data(ticker)
st.dataframe(data)
|