Spaces:
Sleeping
Sleeping
ANON STUDIOS 254 commited on
Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import streamlit as st
|
| 2 |
+
import yfinance as yf
|
| 3 |
+
import matplotlib.pyplot as plt
|
| 4 |
+
import pandas as pd
|
| 5 |
+
from sklearn.model_selection import train_test_split
|
| 6 |
+
from sklearn.ensemble import RandomForestRegressor
|
| 7 |
+
from sklearn.metrics import mean_squared_error
|
| 8 |
+
|
| 9 |
+
st.title("Stockiza: Stock Price App")
|
| 10 |
+
|
| 11 |
+
# Get user input for stock symbol
|
| 12 |
+
stock_symbol = st.text_input("Enter a stock symbol:", "AAPL")
|
| 13 |
+
|
| 14 |
+
# Add a button to fetch data
|
| 15 |
+
fetch_button = st.button("Fetch Data")
|
| 16 |
+
|
| 17 |
+
if fetch_button:
|
| 18 |
+
try:
|
| 19 |
+
# Fetch stock data using yfinance
|
| 20 |
+
stock = yf.Ticker(stock_symbol)
|
| 21 |
+
stock_info = stock.info
|
| 22 |
+
|
| 23 |
+
# Display stock information
|
| 24 |
+
st.subheader(f"{stock_info['longName']} ({stock_symbol})")
|
| 25 |
+
|
| 26 |
+
# Check if 'currentPrice' key exists in stock_info
|
| 27 |
+
if 'currentPrice' in stock_info:
|
| 28 |
+
st.write(f"Current Price: ${stock_info['currentPrice']:.2f}")
|
| 29 |
+
else:
|
| 30 |
+
st.write("Current Price: Not available")
|
| 31 |
+
|
| 32 |
+
# Check if other keys exist before accessing them
|
| 33 |
+
if'regularMarketDayRange' in stock_info:
|
| 34 |
+
st.write(f"Day's Range: ${stock_info['regularMarketDayRange']}")
|
| 35 |
+
if 'fiftyTwoWeekRange' in stock_info:
|
| 36 |
+
st.write(f"52-Week Range: ${stock_info['fiftyTwoWeekRange']}")
|
| 37 |
+
if'regularMarketVolume' in stock_info:
|
| 38 |
+
st.write(f"Volume: {stock_info['regularMarketVolume']:,.0f}")
|
| 39 |
+
if'marketCap' in stock_info:
|
| 40 |
+
st.write(f"Market Cap: ${stock_info['marketCap']:,.2f}")
|
| 41 |
+
|
| 42 |
+
# Add a graph
|
| 43 |
+
stock_data = stock.history(period="5y")
|
| 44 |
+
fig, ax = plt.subplots()
|
| 45 |
+
ax.plot(stock_data.index, stock_data["Close"])
|
| 46 |
+
ax.set_title(f"{stock_symbol} Stock Price")
|
| 47 |
+
ax.set_xlabel("Date")
|
| 48 |
+
ax.set_ylabel("Price ($)")
|
| 49 |
+
st.pyplot(fig)
|
| 50 |
+
|
| 51 |
+
# Prepare data for time series model
|
| 52 |
+
stock_data['Date'] = pd.to_datetime(stock_data.index)
|
| 53 |
+
stock_data['Year'] = stock_data['Date'].dt.year
|
| 54 |
+
stock_data['Month'] = stock_data['Date'].dt.month
|
| 55 |
+
stock_data['Day'] = stock_data['Date'].dt.day
|
| 56 |
+
|
| 57 |
+
# Split data into training and testing sets
|
| 58 |
+
X = stock_data[['Year', 'Month', 'Day']]
|
| 59 |
+
y = stock_data['Close']
|
| 60 |
+
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
|
| 61 |
+
|
| 62 |
+
# Train a random forest regressor model
|
| 63 |
+
model = RandomForestRegressor(n_estimators=100, random_state=42)
|
| 64 |
+
model.fit(X_train, y_train)
|
| 65 |
+
|
| 66 |
+
# Make predictions on the test set
|
| 67 |
+
y_pred = model.predict(X_test)
|
| 68 |
+
|
| 69 |
+
# Evaluate the model
|
| 70 |
+
mse = mean_squared_error(y_test, y_pred)
|
| 71 |
+
rmse = mse ** 0.5
|
| 72 |
+
st.write(f"Root Mean Squared Error (RMSE): {rmse:.2f}")
|
| 73 |
+
|
| 74 |
+
# Use the model to predict the stock price 5 years from now
|
| 75 |
+
future_date = pd.to_datetime('2027-12-31')
|
| 76 |
+
future_data = pd.DataFrame({'Year': [future_date.year], 'Month': [future_date.month], 'Day': [future_date.day]})
|
| 77 |
+
future_price = model.predict(future_data)
|
| 78 |
+
st.write(f"Predicted Price 5 Years from Now: ${future_price[0]:.2f}")
|
| 79 |
+
|
| 80 |
+
except Exception as e:
|
| 81 |
+
st.error(f"Error: {e}")
|