File size: 3,118 Bytes
77dc165
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import streamlit as st
import yfinance as yf
import matplotlib.pyplot as plt
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestRegressor
from sklearn.metrics import mean_squared_error

st.title("Stockiza: Stock Price App")

# Get user input for stock symbol
stock_symbol = st.text_input("Enter a stock symbol:", "AAPL")

# Add a button to fetch data
fetch_button = st.button("Fetch Data")

if fetch_button:
    try:
        # Fetch stock data using yfinance
        stock = yf.Ticker(stock_symbol)
        stock_info = stock.info

        # Display stock information
        st.subheader(f"{stock_info['longName']} ({stock_symbol})")

        # Check if 'currentPrice' key exists in stock_info
        if 'currentPrice' in stock_info:
            st.write(f"Current Price: ${stock_info['currentPrice']:.2f}")
        else:
            st.write("Current Price: Not available")

        # Check if other keys exist before accessing them
        if'regularMarketDayRange' in stock_info:
            st.write(f"Day's Range: ${stock_info['regularMarketDayRange']}")
        if 'fiftyTwoWeekRange' in stock_info:
            st.write(f"52-Week Range: ${stock_info['fiftyTwoWeekRange']}")
        if'regularMarketVolume' in stock_info:
            st.write(f"Volume: {stock_info['regularMarketVolume']:,.0f}")
        if'marketCap' in stock_info:
            st.write(f"Market Cap: ${stock_info['marketCap']:,.2f}")

        # Add a graph
        stock_data = stock.history(period="5y")
        fig, ax = plt.subplots()
        ax.plot(stock_data.index, stock_data["Close"])
        ax.set_title(f"{stock_symbol} Stock Price")
        ax.set_xlabel("Date")
        ax.set_ylabel("Price ($)")
        st.pyplot(fig)

        # Prepare data for time series model
        stock_data['Date'] = pd.to_datetime(stock_data.index)
        stock_data['Year'] = stock_data['Date'].dt.year
        stock_data['Month'] = stock_data['Date'].dt.month
        stock_data['Day'] = stock_data['Date'].dt.day

        # Split data into training and testing sets
        X = stock_data[['Year', 'Month', 'Day']]
        y = stock_data['Close']
        X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)

        # Train a random forest regressor model
        model = RandomForestRegressor(n_estimators=100, random_state=42)
        model.fit(X_train, y_train)

        # Make predictions on the test set
        y_pred = model.predict(X_test)

        # Evaluate the model
        mse = mean_squared_error(y_test, y_pred)
        rmse = mse ** 0.5
        st.write(f"Root Mean Squared Error (RMSE): {rmse:.2f}")

        # Use the model to predict the stock price 5 years from now
        future_date = pd.to_datetime('2027-12-31')
        future_data = pd.DataFrame({'Year': [future_date.year], 'Month': [future_date.month], 'Day': [future_date.day]})
        future_price = model.predict(future_data)
        st.write(f"Predicted Price 5 Years from Now: ${future_price[0]:.2f}")

    except Exception as e:
        st.error(f"Error: {e}")