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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import io
|
| 3 |
+
import requests
|
| 4 |
+
import joblib
|
| 5 |
+
import pandas as pd
|
| 6 |
+
import streamlit as st
|
| 7 |
+
import plotly.graph_objects as go
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
from supabase import create_client, Client
|
| 10 |
+
import yfinance as yf
|
| 11 |
+
|
| 12 |
+
# =====================================
|
| 13 |
+
# β
CONFIGURATION
|
| 14 |
+
# =====================================
|
| 15 |
+
MODEL_URL = "https://huggingface.co/shaikfakruddin18/stock-predictor-model/resolve/main/rf_model.joblib"
|
| 16 |
+
|
| 17 |
+
ALPHA_VANTAGE_API_KEY = " IY2HMVXFHXE83LB5" # Replace with your API key
|
| 18 |
+
SUPABASE_URL = "https://rrvsbizwikocatkdhyfs.supabase.co"
|
| 19 |
+
SUPABASE_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJydnNiaXp3aWtvY2F0a2RoeWZzIiwicm9sZSI6ImFub24iLCJpYXQiOjE3NTI5NjExNDAsImV4cCI6MjA2ODUzNzE0MH0.YWP65KQvwna1yQlhjksyT9Rhpyn5bBw5MDlMVHTF62Q"
|
| 20 |
+
|
| 21 |
+
supabase: Client = create_client(SUPABASE_URL, SUPABASE_KEY)
|
| 22 |
+
|
| 23 |
+
# Cache model so it's loaded only once
|
| 24 |
+
@st.cache_resource
|
| 25 |
+
def load_model_from_hf():
|
| 26 |
+
"""Download model from Hugging Face and load it"""
|
| 27 |
+
model_path = "rf_model.joblib"
|
| 28 |
+
if not os.path.exists(model_path):
|
| 29 |
+
st.info("π₯ Downloading ML model from Hugging Face...")
|
| 30 |
+
r = requests.get(MODEL_URL)
|
| 31 |
+
with open(model_path, "wb") as f:
|
| 32 |
+
f.write(r.content)
|
| 33 |
+
return joblib.load(model_path)
|
| 34 |
+
|
| 35 |
+
model = load_model_from_hf()
|
| 36 |
+
|
| 37 |
+
# =====================================
|
| 38 |
+
# β
FETCH STOCK DATA
|
| 39 |
+
# =====================================
|
| 40 |
+
|
| 41 |
+
def fetch_yahoo_data(ticker, period="3mo"):
|
| 42 |
+
"""Fetch historical daily data from Yahoo Finance"""
|
| 43 |
+
df = yf.download(ticker, period=period, interval="1d")
|
| 44 |
+
if df.empty:
|
| 45 |
+
return None
|
| 46 |
+
df.reset_index(inplace=True)
|
| 47 |
+
return df
|
| 48 |
+
|
| 49 |
+
def fetch_alpha_vantage_intraday(ticker, interval="5min"):
|
| 50 |
+
"""Fetch intraday data from Alpha Vantage"""
|
| 51 |
+
url = (
|
| 52 |
+
f"https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY"
|
| 53 |
+
f"&symbol={ticker}&interval={interval}&apikey={ALPHA_VANTAGE_API_KEY}&datatype=json"
|
| 54 |
+
)
|
| 55 |
+
r = requests.get(url).json()
|
| 56 |
+
key = f"Time Series ({interval})"
|
| 57 |
+
if key not in r:
|
| 58 |
+
return None
|
| 59 |
+
df = pd.DataFrame(r[key]).T
|
| 60 |
+
df.columns = ["Open", "High", "Low", "Close", "Volume"]
|
| 61 |
+
df.index = pd.to_datetime(df.index)
|
| 62 |
+
df = df.sort_index()
|
| 63 |
+
df.reset_index(inplace=True)
|
| 64 |
+
df.rename(columns={"index": "Datetime"}, inplace=True)
|
| 65 |
+
df[["Open", "High", "Low", "Close", "Volume"]] = df[["Open", "High", "Low", "Close", "Volume"]].astype(float)
|
| 66 |
+
return df
|
| 67 |
+
|
| 68 |
+
def fetch_supabase_csv(ticker):
|
| 69 |
+
"""Fetch saved stock CSV from Supabase storage"""
|
| 70 |
+
try:
|
| 71 |
+
base_url = "https://rrvsbizwikocatkdhyfs.supabase.co/storage/v1/object/public/prediction/stock_data_with_indicators"
|
| 72 |
+
csv_url = f"{base_url}/{ticker}.csv"
|
| 73 |
+
df = pd.read_csv(csv_url)
|
| 74 |
+
return df
|
| 75 |
+
except:
|
| 76 |
+
return None
|
| 77 |
+
|
| 78 |
+
# =====================================
|
| 79 |
+
# β
PREDICTION + CHARTS
|
| 80 |
+
# =====================================
|
| 81 |
+
|
| 82 |
+
def predict_stock(df):
|
| 83 |
+
"""Predict UP/DOWN using the loaded ML model"""
|
| 84 |
+
if df is None or df.empty:
|
| 85 |
+
return None, None
|
| 86 |
+
|
| 87 |
+
features = df[["Open", "High", "Low", "Close", "Volume"]].tail(1) # Last row
|
| 88 |
+
pred = model.predict(features)[0]
|
| 89 |
+
confidence = model.predict_proba(features).max() * 100
|
| 90 |
+
prediction = "UP" if pred == 1 else "DOWN"
|
| 91 |
+
return prediction, confidence
|
| 92 |
+
|
| 93 |
+
def plot_candlestick(df, title="Stock Price"):
|
| 94 |
+
fig = go.Figure(
|
| 95 |
+
data=[
|
| 96 |
+
go.Candlestick(
|
| 97 |
+
x=df[df.columns[0]],
|
| 98 |
+
open=df["Open"],
|
| 99 |
+
high=df["High"],
|
| 100 |
+
low=df["Low"],
|
| 101 |
+
close=df["Close"],
|
| 102 |
+
)
|
| 103 |
+
]
|
| 104 |
+
)
|
| 105 |
+
fig.update_layout(title=title, xaxis_rangeslider_visible=False, height=400)
|
| 106 |
+
return fig
|
| 107 |
+
|
| 108 |
+
def save_prediction_to_supabase(stock, prediction, confidence, source):
|
| 109 |
+
"""Save prediction to Supabase DB"""
|
| 110 |
+
try:
|
| 111 |
+
created_at = datetime.utcnow().isoformat()
|
| 112 |
+
data = {
|
| 113 |
+
"created_at": created_at,
|
| 114 |
+
"stock": stock,
|
| 115 |
+
"prediction": prediction,
|
| 116 |
+
"confidence": f"{confidence:.2f}%",
|
| 117 |
+
"source": source
|
| 118 |
+
}
|
| 119 |
+
response = supabase.table("predictions").insert(data).execute()
|
| 120 |
+
if response.data:
|
| 121 |
+
st.success("β
Prediction saved to Supabase!")
|
| 122 |
+
else:
|
| 123 |
+
st.error(f"β Failed to save prediction: {response}")
|
| 124 |
+
except Exception as e:
|
| 125 |
+
st.error(f"β Supabase error: {e}")
|
| 126 |
+
|
| 127 |
+
def load_prediction_history_supabase():
|
| 128 |
+
"""Load previous predictions"""
|
| 129 |
+
try:
|
| 130 |
+
response = supabase.table("predictions").select("*").order("created_at", desc=True).execute()
|
| 131 |
+
return pd.DataFrame(response.data) if response.data else pd.DataFrame()
|
| 132 |
+
except Exception as e:
|
| 133 |
+
st.error(f"β Failed to load history: {e}")
|
| 134 |
+
return pd.DataFrame()
|
| 135 |
+
|
| 136 |
+
# =====================================
|
| 137 |
+
# β
STREAMLIT UI
|
| 138 |
+
# =====================================
|
| 139 |
+
|
| 140 |
+
st.set_page_config(page_title="AI Stock Predictor", layout="wide")
|
| 141 |
+
st.sidebar.title("π Navigation")
|
| 142 |
+
|
| 143 |
+
st.sidebar.subheader("Select Data Source")
|
| 144 |
+
data_source = st.sidebar.radio(
|
| 145 |
+
"Fetch data from:",
|
| 146 |
+
["Yahoo Finance (Daily)", "Alpha Vantage (Intraday)", "Supabase CSV"]
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
ticker = st.sidebar.text_input("Enter Stock Ticker (e.g. AAPL, RELIANCE.BSE)", "AAPL")
|
| 150 |
+
|
| 151 |
+
if data_source == "Yahoo Finance (Daily)":
|
| 152 |
+
period = st.sidebar.selectbox("Select Period", ["1mo", "3mo", "6mo", "1y", "2y"], index=1)
|
| 153 |
+
elif data_source == "Alpha Vantage (Intraday)":
|
| 154 |
+
interval = st.sidebar.selectbox("Intraday Interval", ["1min", "5min", "15min", "30min", "60min"], index=1)
|
| 155 |
+
|
| 156 |
+
st.title("π AI Stock Predictor Dashboard")
|
| 157 |
+
|
| 158 |
+
if st.sidebar.button("Fetch Data & Predict"):
|
| 159 |
+
if data_source == "Yahoo Finance (Daily)":
|
| 160 |
+
df = fetch_yahoo_data(ticker, period)
|
| 161 |
+
source_name = "YahooFinance"
|
| 162 |
+
elif data_source == "Alpha Vantage (Intraday)":
|
| 163 |
+
df = fetch_alpha_vantage_intraday(ticker, interval)
|
| 164 |
+
source_name = "AlphaVantage"
|
| 165 |
+
else:
|
| 166 |
+
df = fetch_supabase_csv(ticker)
|
| 167 |
+
source_name = "Supabase CSV"
|
| 168 |
+
|
| 169 |
+
if df is None or df.empty:
|
| 170 |
+
st.error("β No data returned. Check ticker or date range.")
|
| 171 |
+
else:
|
| 172 |
+
st.subheader(f"Stock Data: {ticker} ({source_name})")
|
| 173 |
+
st.plotly_chart(plot_candlestick(df, f"{ticker} Price Chart"), use_container_width=True)
|
| 174 |
+
|
| 175 |
+
prediction, confidence = predict_stock(df)
|
| 176 |
+
if prediction:
|
| 177 |
+
st.markdown(f"### Prediction: **{prediction}**")
|
| 178 |
+
st.markdown(f"### Confidence: **{confidence:.2f}%**")
|
| 179 |
+
save_prediction_to_supabase(ticker, prediction, confidence, source_name)
|
| 180 |
+
else:
|
| 181 |
+
st.warning("β οΈ Could not generate prediction.")
|
| 182 |
+
|
| 183 |
+
# Show Prediction History
|
| 184 |
+
st.subheader("π Prediction History (Cloud)")
|
| 185 |
+
history_df = load_prediction_history_supabase()
|
| 186 |
+
if not history_df.empty:
|
| 187 |
+
st.dataframe(history_df[["created_at", "stock", "prediction", "confidence", "source"]])
|
| 188 |
+
else:
|
| 189 |
+
st.info("No prediction history yet.")
|