# Import necessary libraries import pandas as pd import yfinance as yf from sklearn.model_selection import train_test_split from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error import streamlit as st from datetime import datetime, timedelta, timezone # Function to fetch historical stock data def fetch_stock_data(symbol, start_date, end_date): data = yf.download(symbol, start=start_date, end=end_date) return data # Function to create features for the model def create_features(data): data['Date'] = data.index data['Year'] = data['Date'].dt.year data['Month'] = data['Date'].dt.month data['Day'] = data['Date'].dt.day data['Hour'] = data['Date'].dt.hour data['Minute'] = data['Date'].dt.minute return data # Function to train a machine learning model def train_model(data): features = ['Year', 'Month', 'Day', 'Hour', 'Minute'] target = 'Close' X = data[features] y = data[target] X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42) model = RandomForestRegressor() model.fit(X_train, y_train) # Evaluate the model predictions = model.predict(X_test) mse = mean_squared_error(y_test, predictions) st.write(f"Mean Squared Error: {mse}") return model # Streamlit UI def main(): st.title("Stock Price Prediction Tool") symbol = st.text_input("Enter Stock Symbol (e.g., AAPL):") start_date = st.date_input("Select Start Date:") end_date = st.date_input("Select End Date:") if st.button("Predict Stock Price"): # Fetch stock data stock_data = fetch_stock_data(symbol, start_date, end_date) # Create features stock_data = create_features(stock_data) # Train the model model = train_model(stock_data) # Predict the stock price for a specific date (e.g., the last date in the dataset) prediction_date = stock_data['Date'].iloc[-1] prediction_features = [[ prediction_date.year, prediction_date.month, prediction_date.day, prediction_date.hour, prediction_date.minute ]] predicted_price = model.predict(prediction_features)[0] st.subheader(f"Predicted Stock Price on {prediction_date} (UTC):") st.write(f"${predicted_price:.2f}") # Run the Streamlit app if __name__ == '__main__': main()