|
|
|
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 |
|
|
|
|
|
def fetch_stock_data(symbol, start_date, end_date): |
|
data = yf.download(symbol, start=start_date, end=end_date) |
|
return data |
|
|
|
|
|
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 |
|
|
|
|
|
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) |
|
|
|
|
|
predictions = model.predict(X_test) |
|
mse = mean_squared_error(y_test, predictions) |
|
st.write(f"Mean Squared Error: {mse}") |
|
|
|
return model |
|
|
|
|
|
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"): |
|
|
|
stock_data = fetch_stock_data(symbol, start_date, end_date) |
|
|
|
|
|
stock_data = create_features(stock_data) |
|
|
|
|
|
model = train_model(stock_data) |
|
|
|
|
|
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}") |
|
|
|
|
|
if __name__ == '__main__': |
|
main() |