Spaces:
Build error
Build error
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,107 +1,82 @@
|
|
| 1 |
import streamlit as st
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
| 4 |
-
import requests
|
| 5 |
-
from tensorflow.keras.models import load_model
|
| 6 |
-
import tensorflow as tf
|
| 7 |
-
from sklearn.preprocessing import MinMaxScaler
|
| 8 |
-
import joblib
|
| 9 |
-
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer
|
| 10 |
import matplotlib.pyplot as plt
|
| 11 |
import os
|
| 12 |
|
| 13 |
-
#
|
| 14 |
-
# Load Model & Scaler
|
| 15 |
-
# ------------------------------
|
| 16 |
try:
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
|
|
|
| 23 |
|
| 24 |
# ------------------------------
|
| 25 |
-
#
|
| 26 |
# ------------------------------
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
df = df[["4. close"]].rename(columns={"4. close": "Close"})
|
| 39 |
-
return df
|
| 40 |
-
except:
|
| 41 |
-
pass
|
| 42 |
|
| 43 |
-
|
|
|
|
|
|
|
|
|
|
| 44 |
dates = pd.date_range(end=pd.Timestamp.today(), periods=200)
|
| 45 |
prices = np.linspace(100, 150, 200) + np.random.normal(0, 2, 200)
|
| 46 |
df = pd.DataFrame({"Close": prices}, index=dates)
|
| 47 |
return df
|
| 48 |
|
| 49 |
# ------------------------------
|
| 50 |
-
#
|
| 51 |
-
# ------------------------------
|
| 52 |
-
NEWS_KEY = os.getenv("NEWSAPI_KEY", None)
|
| 53 |
-
analyzer = SentimentIntensityAnalyzer()
|
| 54 |
-
|
| 55 |
-
def get_sentiment(stock="HBL"):
|
| 56 |
-
if not NEWS_KEY:
|
| 57 |
-
return 0
|
| 58 |
-
try:
|
| 59 |
-
url = f"https://newsapi.org/v2/everything?q={stock}+Pakistan&apiKey={NEWS_KEY}"
|
| 60 |
-
r = requests.get(url).json()
|
| 61 |
-
if "articles" not in r:
|
| 62 |
-
return 0
|
| 63 |
-
articles = r["articles"][:5]
|
| 64 |
-
scores = [analyzer.polarity_scores(a["title"])['compound'] for a in articles]
|
| 65 |
-
return np.mean(scores) if scores else 0
|
| 66 |
-
except:
|
| 67 |
-
return 0
|
| 68 |
-
|
| 69 |
-
# ------------------------------
|
| 70 |
-
# Predict Next Day
|
| 71 |
# ------------------------------
|
| 72 |
def predict_next(df):
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 78 |
|
| 79 |
# ------------------------------
|
| 80 |
# Streamlit UI
|
| 81 |
# ------------------------------
|
| 82 |
-
st.title("π PSX Stock Predictor β FYP Version")
|
| 83 |
-
st.write("Live PSX price trend + sentiment + ML prediction")
|
| 84 |
-
|
| 85 |
symbol = st.selectbox("Choose PSX Stock:", ["HBL", "UBL", "ENGRO", "PSO", "OGDC"])
|
| 86 |
|
| 87 |
if st.button("Fetch & Predict"):
|
| 88 |
-
with st.spinner("Fetching data..."):
|
| 89 |
-
df =
|
| 90 |
-
sentiment = get_sentiment(symbol)
|
| 91 |
prediction = predict_next(df)
|
| 92 |
|
| 93 |
-
# Adjust prediction with sentiment
|
| 94 |
-
sentiment_adj = prediction + (prediction * sentiment * 0.02)
|
| 95 |
-
|
| 96 |
# Plot historical + predicted
|
| 97 |
fig, ax = plt.subplots()
|
| 98 |
ax.plot(df.index, df["Close"], label="Historical Price")
|
| 99 |
-
ax.axhline(
|
| 100 |
ax.set_title(f"{symbol} Stock Price Prediction")
|
| 101 |
ax.legend()
|
| 102 |
st.pyplot(fig)
|
| 103 |
|
| 104 |
-
# Display
|
| 105 |
st.subheader("Prediction Result")
|
| 106 |
-
st.write(f"**Predicted Price:** Rs {
|
| 107 |
-
st.write(f"**Sentiment Impact:** {sentiment:.3f}")
|
|
|
|
| 1 |
import streamlit as st
|
| 2 |
import numpy as np
|
| 3 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 4 |
import matplotlib.pyplot as plt
|
| 5 |
import os
|
| 6 |
|
| 7 |
+
# Optional imports for ML, but safely handled
|
|
|
|
|
|
|
| 8 |
try:
|
| 9 |
+
import tensorflow as tf
|
| 10 |
+
from tensorflow.keras.models import load_model
|
| 11 |
+
from sklearn.preprocessing import MinMaxScaler
|
| 12 |
+
import joblib
|
| 13 |
+
except ImportError:
|
| 14 |
+
tf = None
|
| 15 |
+
load_model = None
|
| 16 |
+
MinMaxScaler = None
|
| 17 |
+
joblib = None
|
| 18 |
+
|
| 19 |
+
st.set_page_config(page_title="PSX Stock Predictor", layout="wide")
|
| 20 |
|
| 21 |
+
st.title("π PSX Stock Predictor β HF Safe Version")
|
| 22 |
+
st.write("This app works even if model or API is missing.")
|
| 23 |
|
| 24 |
# ------------------------------
|
| 25 |
+
# Load Model & Scaler
|
| 26 |
# ------------------------------
|
| 27 |
+
MODEL_LOADED = False
|
| 28 |
+
if tf and os.path.exists("model.h5"):
|
| 29 |
+
try:
|
| 30 |
+
model = load_model("model.h5", custom_objects={"mse": tf.keras.metrics.MeanSquaredError()})
|
| 31 |
+
scaler = joblib.load("scaler.pkl") if os.path.exists("scaler.pkl") else MinMaxScaler()
|
| 32 |
+
MODEL_LOADED = True
|
| 33 |
+
st.success("Model loaded successfully!")
|
| 34 |
+
except Exception as e:
|
| 35 |
+
st.warning(f"Model found but failed to load: {e}")
|
| 36 |
+
else:
|
| 37 |
+
st.warning("Model not found. Using dummy predictions.")
|
|
|
|
|
|
|
|
|
|
|
|
|
| 38 |
|
| 39 |
+
# ------------------------------
|
| 40 |
+
# Dummy / Fallback Data
|
| 41 |
+
# ------------------------------
|
| 42 |
+
def get_dummy_data():
|
| 43 |
dates = pd.date_range(end=pd.Timestamp.today(), periods=200)
|
| 44 |
prices = np.linspace(100, 150, 200) + np.random.normal(0, 2, 200)
|
| 45 |
df = pd.DataFrame({"Close": prices}, index=dates)
|
| 46 |
return df
|
| 47 |
|
| 48 |
# ------------------------------
|
| 49 |
+
# Prediction function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
# ------------------------------
|
| 51 |
def predict_next(df):
|
| 52 |
+
if MODEL_LOADED:
|
| 53 |
+
data = scaler.fit_transform(df[["Close"]])
|
| 54 |
+
last60 = data[-60:].reshape(1, 60, 1)
|
| 55 |
+
pred = model.predict(last60, verbose=0)[0][0]
|
| 56 |
+
pred_real = scaler.inverse_transform([[pred]])[0][0]
|
| 57 |
+
return pred_real
|
| 58 |
+
else:
|
| 59 |
+
# Dummy prediction: next value + small random change
|
| 60 |
+
return df["Close"].iloc[-1] * (1 + np.random.uniform(-0.01, 0.01))
|
| 61 |
|
| 62 |
# ------------------------------
|
| 63 |
# Streamlit UI
|
| 64 |
# ------------------------------
|
|
|
|
|
|
|
|
|
|
| 65 |
symbol = st.selectbox("Choose PSX Stock:", ["HBL", "UBL", "ENGRO", "PSO", "OGDC"])
|
| 66 |
|
| 67 |
if st.button("Fetch & Predict"):
|
| 68 |
+
with st.spinner("Fetching data and predicting..."):
|
| 69 |
+
df = get_dummy_data()
|
|
|
|
| 70 |
prediction = predict_next(df)
|
| 71 |
|
|
|
|
|
|
|
|
|
|
| 72 |
# Plot historical + predicted
|
| 73 |
fig, ax = plt.subplots()
|
| 74 |
ax.plot(df.index, df["Close"], label="Historical Price")
|
| 75 |
+
ax.axhline(prediction, linestyle="--", color="red", label="Predicted Price")
|
| 76 |
ax.set_title(f"{symbol} Stock Price Prediction")
|
| 77 |
ax.legend()
|
| 78 |
st.pyplot(fig)
|
| 79 |
|
| 80 |
+
# Display result
|
| 81 |
st.subheader("Prediction Result")
|
| 82 |
+
st.write(f"**Predicted Price:** Rs {prediction:.2f}")
|
|
|