File size: 7,466 Bytes
7458986
db6d471
65d5f73
7458986
 
 
 
db6d471
7458986
 
65d5f73
7458986
db6d471
 
 
972a547
05c066f
db6d471
7458986
db6d471
 
 
 
 
 
7458986
c54bdd8
05c066f
7458986
db6d471
525527f
65d5f73
 
db6d471
 
972a547
65d5f73
 
db6d471
 
 
 
 
 
972a547
db6d471
 
 
 
 
05c066f
65d5f73
db6d471
 
 
 
 
 
c54bdd8
 
 
 
db6d471
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c54bdd8
 
05c066f
c54bdd8
 
 
db6d471
 
 
05c066f
380e150
c54bdd8
 
 
 
 
 
 
 
dbe373a
65d5f73
db6d471
 
 
c67acf2
c54bdd8
 
 
 
 
 
 
 
 
3686f17
 
 
dbe373a
65d5f73
c54bdd8
 
 
 
 
 
 
 
 
 
 
 
 
db6d471
65d5f73
db6d471
c54bdd8
 
 
db6d471
 
 
 
65d5f73
972a547
db6d471
c54bdd8
db6d471
3686f17
db6d471
c54bdd8
db6d471
c54bdd8
37a2367
c54bdd8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
37a2367
c54bdd8
 
37a2367
c54bdd8
 
 
 
37a2367
c54bdd8
 
65d5f73
db6d471
 
c54bdd8
 
 
 
 
 
 
 
65d5f73
7458986
db6d471
3686f17
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
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
import gradio as gr
import pandas as pd
import yfinance as yf
from utils import (
    calculate_technical_indicators,
    generate_trading_signals,
    get_fundamental_data,
    predict_prices,
    create_price_chart,
    create_technical_chart,
    create_prediction_chart,
)
import warnings

warnings.filterwarnings("ignore")


def analyze_stock(symbol, prediction_days=30):
    try:
        if not symbol.strip():
            raise ValueError("Please enter a valid stock symbol.")

        if not symbol.endswith(".JK"):
            symbol = symbol.upper() + ".JK"

        stock = yf.Ticker(symbol)
        data = stock.history(period="1y", interval="1d") 

        if data.empty:
            raise ValueError("No price data available for this stock.")

        indicators = calculate_technical_indicators(data)
        signals = generate_trading_signals(data, indicators)
        fundamental_info = get_fundamental_data(stock)
        predictions = predict_prices(data, prediction_days=prediction_days)

        fig_price = create_price_chart(data, indicators)
        fig_technical = create_technical_chart(data, indicators)
        fig_prediction = create_prediction_chart(data, predictions)

        last_price = data['Close'].iloc[-1]
        tp1 = last_price * (1 + (predictions.get("change_pct", 0) / 200))
        tp2 = last_price * (1 + (predictions.get("change_pct", 0) / 100))
        sl = last_price * 0.95

        predictions["tp1"] = tp1
        predictions["tp2"] = tp2
        predictions["sl"] = sl

        return fundamental_info, indicators, signals, fig_price, fig_technical, fig_prediction, predictions

    except Exception as e:
        print(f"Error analyzing {symbol}: {e}")
        empty_fig = gr.Plot.update(value=None)
        empty_predictions = {
            "high_30d": 0,
            "low_30d": 0,
            "change_pct": 0,
            "summary": f"Error: {e}",
            "tp1": 0,
            "tp2": 0,
            "sl": 0,
        }
        return {}, {}, {}, empty_fig, empty_fig, empty_fig, empty_predictions


def update_analysis(symbol, prediction_days):
    (
        fundamental_info,
        indicators,
        signals,
        fig_price,
        fig_technical,
        fig_prediction,
        predictions,
    ) = analyze_stock(symbol, prediction_days)

    if not fundamental_info and "Error" in predictions.get("summary", ""):
        error_msg = f"**ERROR:** {predictions.get('summary')}"
        return (
            gr.Markdown.update(value=error_msg),
            gr.Markdown.update(value=error_msg),
            gr.Markdown.update(value=error_msg),
            gr.Plot.update(value=None),
            gr.Plot.update(value=None),
            gr.Plot.update(value=None),
        )

    fundamentals_text = f"""
    ### COMPANY FUNDAMENTALS
    - **Name:** {fundamental_info.get('name', 'N/A')} ({symbol.upper()})
    - **Current Price:** Rp{fundamental_info.get('current_price', 0):,.2f}
    - **Market Cap:** {fundamental_info.get('market_cap', 0):,}
    - **P/E Ratio:** {fundamental_info.get('pe_ratio', 0):.2f}
    - **Dividend Yield:** {fundamental_info.get('dividend_yield', 0):.2f}%
    - **Volume:** {fundamental_info.get('volume', 0):,}
    """

    details_list = "".join(
        [f"<li>{line.strip()}</li>" for line in signals.get("details", "").split("\n") if line.strip()]
    )

    trading_signal_text = f"""
    ### TECHNICAL SIGNAL SUMMARY
    - **Overall Trend:** **{signals.get('overall', 'N/A')}**
    - **Signal Strength:** {signals.get('strength', 0):.2f}%
    - **Support:** Rp{signals.get('support', 0):,.2f}
    - **Resistance:** Rp{signals.get('resistance', 0):,.2f}
    - **Stop Loss:** Rp{signals.get('stop_loss', 0):,.2f}

    #### Detailed Signals:
    <ul style="margin-top: 8px; padding-left: 20px; line-height: 1.6;">
    {details_list}
    </ul>
    """

    prediction_text = f"""
    ### 30-DAY AI FORECAST
    - **Predicted High:** Rp{predictions.get('high_30d', 0):,.2f}
    - **Predicted Low:** Rp{predictions.get('low_30d', 0):,.2f}
    - **Expected Change:** **{predictions.get('change_pct', 0):.2f}%**

    #### Trading Targets
    - **TP1 (Target Price 1):** Rp{predictions.get('tp1', 0):,.2f}
    - **TP2 (Target Price 2):** Rp{predictions.get('tp2', 0):,.2f}
    - **Stop Loss:** Rp{predictions.get('sl', 0):,.2f}

    #### Model Insight
    > {predictions.get('summary', 'No analysis available')}
    """

    return (
        gr.Markdown.update(value=fundamentals_text),
        gr.Markdown.update(value=trading_signal_text),
        gr.Markdown.update(value=prediction_text),
        fig_price,
        fig_technical,
        fig_prediction,
    )


with gr.Blocks(
    title="REXPRO FINANCIAL AI DASHBOARD",
) as app:
    gr.Markdown("# REXPRO FINANCIAL AI DASHBOARD")
    gr.Markdown(
        "Aplikasi Analisis Saham Komprehensif IDX, didukung oleh **Peramalan AI (CHRONOS-BOLT)** dan Analisis Teknikal."
    )
    
    with gr.Row(variant="panel"):
        with gr.Column(scale=1):
            symbol = gr.Textbox(
                label="MASUKKAN SIMBOL SAHAM (IDX)",
                value="BBCA",
                placeholder="Contoh: BBCA, TLKM, ADRO, BMRI",
                interactive=True,
                show_label=True
            )
        with gr.Column(scale=1):
            prediction_days = gr.Slider(
                label="PERIODE PERAMALAN (HARI)",
                minimum=5,
                maximum=60,
                step=5,
                value=30,
                interactive=True,
                show_label=True
            )
        with gr.Column(min_width=150, scale=0):
            analyze_button = gr.Button("RUN ANALYSIS", size="lg")

    with gr.Tabs():
        with gr.TabItem("RINGKASAN & TARGET"):
            with gr.Row():
                with gr.Group():
                    fundamentals_output = gr.Markdown(
                        "Hasil Fundamental akan muncul di sini.", 
                        elem_classes=["card"]
                    )
                with gr.Group():
                    trading_signal_output = gr.Markdown(
                        "Ringkasan Sinyal Teknikal akan muncul di sini.",
                        elem_classes=["card"]
                    )
                with gr.Group():
                    prediction_output = gr.Markdown(
                        "Hasil Peramalan AI & Target Trading akan muncul di sini.",
                        elem_classes=["card"]
                    )
        
        with gr.TabItem("VISUALISASI GRAFIK"):
            gr.Markdown("## Grafik Analisis Saham")
            
            with gr.Row():
                with gr.Column(scale=1):
                    price_chart = gr.Plot(label="1. HARGA & RATA-RATA BERGERAK (MA)")
                
                with gr.Column(scale=1):
                    technical_chart = gr.Plot(label="2. INDIKATOR TEKNIKAL UTAMA (RSI/MACD)")
            
            gr.Markdown("---")
            
            with gr.Row():
                prediction_chart = gr.Plot(label="3. PROYEKSI PERAMALAN AI") 


    analyze_button.click(
        fn=update_analysis,
        inputs=[symbol, prediction_days],
        outputs=[
            fundamentals_output,
            trading_signal_output,
            prediction_output,
            price_chart,
            technical_chart,
            prediction_chart,
        ],
    )

if __name__ == "__main__":
    app.launch(server_name="0.0.0.0", server_port=7860, ssr_mode=True)