File size: 3,394 Bytes
540ec54
be1c8d5
 
540ec54
e85546a
be1c8d5
e85546a
be1c8d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1c03d2a
be1c8d5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
import streamlit as st
import plotly.graph_objects as go
from groq import Groq
import numpy as np
import pandas as pd
import yfinance as yf

#  prediction module 
from predict_live import predict_next_price, get_live_data
# Streamlit Setup

st.set_page_config(page_title="πŸ“Š PSX Investment Advisor", layout="wide", page_icon="πŸ“ˆ")
st.title("πŸ“Š PSX Investment Dashboard")
st.write("GenAI-powered stock insights with LIVE LSTM predictions")

# Sidebar Inputs
st.sidebar.header("Investment Options")
investment_type = st.sidebar.radio("Investment Type:", ["Short Term", "Long Term"])
sector = st.sidebar.selectbox("Sector:", ["Banking", "Energy"])
stock = st.sidebar.text_input("Stock Symbol:", "HBL")  # user enters HBL

#PSX ticker format
ticker = stock.upper() + ".KA"
#  LIVE Prediction
try:
    close_prices = get_live_data(ticker)
    predicted_price = predict_next_price(ticker)

except Exception as e:
    st.error(f"Error fetching live data: {e}")
    st.stop()
# Dummy sentiment 
sentiment_score = 0.10 
sentiment_adjusted_pred = predicted_price + (predicted_price * sentiment_score * 0.02)

# Dashboard 
col1, col2, col3 = st.columns(3)
col1.metric("Selected Stock", stock)
col2.metric("Live Last Price", f"Rs {close_prices[-1]:.2f}")
col3.metric("LSTM Prediction", f"Rs {sentiment_adjusted_pred:.2f}")

#Plot
def plot_stock(close_prices, predicted_price):
    fig = go.Figure()

    # Plot live historical
    fig.add_trace(go.Scatter(
        y=close_prices,
        x=list(range(len(close_prices))),
        mode='lines',
        name='Live Prices'
    ))

    # Plot prediction
    fig.add_trace(go.Scatter(
        x=[len(close_prices)],
        y=[predicted_price],
        mode='markers',
        name='Predicted Next Price',
        marker=dict(size=12)
    ))

    fig.update_layout(
        title=f"{stock} Live Price + Prediction",
        xaxis_title="Time",
        yaxis_title="Price (Rs)",
        template="plotly_dark"
    )
    return fig

st.subheader("Live Price Chart")
st.plotly_chart(plot_stock(close_prices, sentiment_adjusted_pred), use_container_width=True)

st.subheader("Prediction Result")
st.write(f"**LSTM Next Price Prediction:** Rs {sentiment_adjusted_pred:.2f}")
st.write(f"**Sentiment Impact:** {sentiment_score:.2f}")

# AI Chatbox via Groq

st.subheader("πŸ’¬ Ask Your Investment Advisor")

user_input = st.text_input(
    "Your question to AI:",
    f"Should I invest in {stock} for {investment_type.lower()}?"
)

if st.button("Ask AI"):
    if user_input:
        with st.spinner("Thinking..."):

            client = Groq(api_key=st.secrets["GROQ_API_KEY"])

            advisor_prompt = f"""
You are a financial advisor AI.

Use the following data:
Current Price: {close_prices[-1]}
Predicted Next Price: {sentiment_adjusted_pred}
User Question: {user_input}

Respond MUST:
- Give a clear BUY / SELL / HOLD
- Explain in 2–3 simple lines
- Mention risk in simple terms
- 1 friendly tip
- No complex financial jargon
"""
            response = client.chat.completions.create(
                model="openai/gpt-oss-120b",
                messages=[
                    {"role": "system", "content": "You are a professional stock advisor."},
                    {"role": "user", "content": advisor_prompt}
                ]
            )

            answer = response.choices[0].message.content
            st.markdown(f"**AI:** {answer}")