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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# app.py (Groq Version)
|
| 2 |
+
import os, math
|
| 3 |
+
import pandas as pd
|
| 4 |
+
import numpy as np
|
| 5 |
+
import yfinance as yf
|
| 6 |
+
import gradio as gr
|
| 7 |
+
from groq import Groq
|
| 8 |
+
from datetime import datetime
|
| 9 |
+
|
| 10 |
+
# ============================
|
| 11 |
+
# CONFIG
|
| 12 |
+
# ============================
|
| 13 |
+
|
| 14 |
+
LOOKBACK_DAYS = 365
|
| 15 |
+
|
| 16 |
+
# Initialize Groq client
|
| 17 |
+
GROQ_KEY = os.getenv("GROQ_API_KEY")
|
| 18 |
+
client = Groq(api_key=GROQ_KEY)
|
| 19 |
+
|
| 20 |
+
# Example sectors
|
| 21 |
+
SECTORS = {
|
| 22 |
+
"Energy": ["OGDC", "PPL", "POL", "PSO"],
|
| 23 |
+
"Fertilizers": ["ENGRO", "EFERT", "FATIMA"]
|
| 24 |
+
}
|
| 25 |
+
|
| 26 |
+
# ============================
|
| 27 |
+
# Fetch Live Data
|
| 28 |
+
# ============================
|
| 29 |
+
|
| 30 |
+
def fetch_live_prices(ticker):
|
| 31 |
+
variants = [ticker, ticker+".PK", ticker+".KS", ticker+".KA"]
|
| 32 |
+
attempts = []
|
| 33 |
+
|
| 34 |
+
for sym in variants:
|
| 35 |
+
attempts.append(sym)
|
| 36 |
+
try:
|
| 37 |
+
tk = yf.Ticker(sym)
|
| 38 |
+
hist = tk.history(period="1y", interval="1d")
|
| 39 |
+
if hist is not None and not hist.empty:
|
| 40 |
+
hist = hist.reset_index()
|
| 41 |
+
if "Close" not in hist.columns and "Adj Close" in hist.columns:
|
| 42 |
+
hist["Close"] = hist["Adj Close"]
|
| 43 |
+
return hist, sym
|
| 44 |
+
except:
|
| 45 |
+
pass
|
| 46 |
+
|
| 47 |
+
return None, attempts
|
| 48 |
+
|
| 49 |
+
# ============================
|
| 50 |
+
# Metrics
|
| 51 |
+
# ============================
|
| 52 |
+
|
| 53 |
+
def compute_metrics(hist):
|
| 54 |
+
hist = hist.sort_values("Date").reset_index(drop=True)
|
| 55 |
+
metrics = {}
|
| 56 |
+
|
| 57 |
+
metrics["last_close"] = float(hist["Close"].iloc[-1])
|
| 58 |
+
metrics["last_date"] = str(hist["Date"].iloc[-1])[:10]
|
| 59 |
+
|
| 60 |
+
# Moving averages
|
| 61 |
+
for w in [7, 30, 90]:
|
| 62 |
+
if len(hist) >= w:
|
| 63 |
+
metrics[f"MA{w}"] = float(hist["Close"].rolling(w).mean().iloc[-1])
|
| 64 |
+
else:
|
| 65 |
+
metrics[f"MA{w}"] = None
|
| 66 |
+
|
| 67 |
+
# Returns
|
| 68 |
+
def ret(days):
|
| 69 |
+
if len(hist) > days:
|
| 70 |
+
return float(hist["Close"].iloc[-1] / hist["Close"].iloc[-1-days] - 1)
|
| 71 |
+
return None
|
| 72 |
+
|
| 73 |
+
metrics["ret_7"] = ret(7)
|
| 74 |
+
metrics["ret_30"] = ret(30)
|
| 75 |
+
metrics["ret_365"] = ret(365)
|
| 76 |
+
|
| 77 |
+
# Volume spike
|
| 78 |
+
if "Volume" in hist.columns:
|
| 79 |
+
metrics["vol_last"] = float(hist["Volume"].iloc[-1])
|
| 80 |
+
metrics["vol_avg30"] = float(hist["Volume"].tail(30).mean())
|
| 81 |
+
metrics["vol_spike"] = metrics["vol_last"] / (metrics["vol_avg30"] + 1e-9)
|
| 82 |
+
else:
|
| 83 |
+
metrics["vol_spike"] = None
|
| 84 |
+
|
| 85 |
+
return metrics
|
| 86 |
+
|
| 87 |
+
# ============================
|
| 88 |
+
# Scores
|
| 89 |
+
# ============================
|
| 90 |
+
|
| 91 |
+
def norm(x, minv, maxv, default=0.5):
|
| 92 |
+
if x is None:
|
| 93 |
+
return default
|
| 94 |
+
return max(0, min(1, (x-minv)/(maxv-minv)))
|
| 95 |
+
|
| 96 |
+
def score_short(m):
|
| 97 |
+
r7 = m["ret_7"] or 0
|
| 98 |
+
ma7 = m["MA7"] or 0
|
| 99 |
+
ma30 = m["MA30"] or 1
|
| 100 |
+
|
| 101 |
+
mom = (ma7 / ma30) - 1
|
| 102 |
+
vol = min(2, m["vol_spike"] or 1)/2
|
| 103 |
+
|
| 104 |
+
return float(0.5*norm(r7,-0.2,0.2) + 0.3*norm(mom,-0.1,0.1)+0.2*vol)
|
| 105 |
+
|
| 106 |
+
def score_long(m):
|
| 107 |
+
r365 = m["ret_365"] or 0
|
| 108 |
+
ma30 = m["MA30"] or 1
|
| 109 |
+
ma90 = m["MA90"] or 1
|
| 110 |
+
|
| 111 |
+
slope = (ma30/ma90)-1
|
| 112 |
+
return float(0.6*norm(r365,-0.5,1)+0.4*norm(slope,-0.2,0.2))
|
| 113 |
+
|
| 114 |
+
# ============================
|
| 115 |
+
# LLM EXPLANATION (Groq)
|
| 116 |
+
# ============================
|
| 117 |
+
|
| 118 |
+
def generate_llm(ticker, metrics, s_short, s_long, horizon):
|
| 119 |
+
prompt = f"""
|
| 120 |
+
You are a financial advisory assistant. A user asked about {ticker} for {horizon} investment.
|
| 121 |
+
|
| 122 |
+
Provide exactly:
|
| 123 |
+
1. A single recommendation: BUY / SELL / HOLD
|
| 124 |
+
2. A short explanation using the numeric facts
|
| 125 |
+
3. Two bullet points of what the investor should watch next
|
| 126 |
+
|
| 127 |
+
Facts:
|
| 128 |
+
last_close = {metrics['last_close']}
|
| 129 |
+
ret_7 = {metrics['ret_7']}
|
| 130 |
+
ret_30 = {metrics['ret_30']}
|
| 131 |
+
MA7 = {metrics['MA7']}
|
| 132 |
+
MA30 = {metrics['MA30']}
|
| 133 |
+
vol_spike = {metrics['vol_spike']}
|
| 134 |
+
short_score = {s_short}
|
| 135 |
+
long_score = {s_long}
|
| 136 |
+
|
| 137 |
+
Respond in clear text. Do NOT use JSON.
|
| 138 |
+
"""
|
| 139 |
+
|
| 140 |
+
resp = client.chat.completions.create(
|
| 141 |
+
model="llama3-8b-8192",
|
| 142 |
+
messages=[{"role":"user","content":prompt}],
|
| 143 |
+
temperature=0.3,
|
| 144 |
+
max_tokens=250
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
return resp.choices[0].message.content
|
| 148 |
+
|
| 149 |
+
# ============================
|
| 150 |
+
# Main Analysis
|
| 151 |
+
# ============================
|
| 152 |
+
|
| 153 |
+
def analyze_stock(ticker, horizon):
|
| 154 |
+
hist, used_sym = fetch_live_prices(ticker)
|
| 155 |
+
|
| 156 |
+
if hist is None:
|
| 157 |
+
return f"No live data found for {ticker}. Tried: {used_sym}", [["Error", "No data"]]
|
| 158 |
+
|
| 159 |
+
metrics = compute_metrics(hist)
|
| 160 |
+
s_short = score_short(metrics)
|
| 161 |
+
s_long = score_long(metrics)
|
| 162 |
+
|
| 163 |
+
llm_text = generate_llm(ticker, metrics, s_short, s_long, horizon)
|
| 164 |
+
|
| 165 |
+
table = [
|
| 166 |
+
["Ticker used", used_sym],
|
| 167 |
+
["Last date", metrics["last_date"]],
|
| 168 |
+
["Last close", metrics["last_close"]],
|
| 169 |
+
["MA7", metrics["MA7"]],
|
| 170 |
+
["MA30", metrics["MA30"]],
|
| 171 |
+
["7-day return", metrics["ret_7"]],
|
| 172 |
+
["30-day return", metrics["ret_30"]],
|
| 173 |
+
["Volume spike", metrics["vol_spike"]],
|
| 174 |
+
["Short score", s_short],
|
| 175 |
+
["Long score", s_long],
|
| 176 |
+
]
|
| 177 |
+
|
| 178 |
+
return llm_text, table
|
| 179 |
+
|
| 180 |
+
# ============================
|
| 181 |
+
# Gradio UI
|
| 182 |
+
# ============================
|
| 183 |
+
|
| 184 |
+
with gr.Blocks() as demo:
|
| 185 |
+
gr.Markdown("## PSX Real-time GenAI Advisor (Groq LLaMA-3)")
|
| 186 |
+
|
| 187 |
+
with gr.Row():
|
| 188 |
+
horizon = gr.Dropdown(["Short-term","Long-term"], label="Investment Horizon")
|
| 189 |
+
sector = gr.Dropdown(list(SECTORS.keys()), label="Sector")
|
| 190 |
+
ticker = gr.Textbox(label="Enter PSX Ticker", placeholder="OGDC")
|
| 191 |
+
|
| 192 |
+
btn = gr.Button("Analyze")
|
| 193 |
+
output = gr.Textbox(label="Advisor Response")
|
| 194 |
+
table = gr.Dataframe(headers=["Metric","Value"], label="Metrics")
|
| 195 |
+
|
| 196 |
+
def run(t, h, s):
|
| 197 |
+
if not t:
|
| 198 |
+
t = SECTORS[s][0]
|
| 199 |
+
return analyze_stock(t, h)
|
| 200 |
+
|
| 201 |
+
btn.click(run, [ticker, horizon, sector], [output, table])
|
| 202 |
+
|
| 203 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
pandas
|
| 3 |
+
numpy
|
| 4 |
+
yfinance
|
| 5 |
+
groq
|