File size: 7,149 Bytes
1e2fac3
 
 
 
 
6d46baf
45288b8
 
c28ab9f
45288b8
c28ab9f
45288b8
 
c28ab9f
45288b8
 
d7caadc
45288b8
 
c28ab9f
45288b8
 
3878c34
45288b8
 
 
 
6d46baf
45288b8
d7caadc
1e2fac3
45288b8
1e2fac3
45288b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e46c6e1
158e960
45288b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d7caadc
 
c28ab9f
db41934
 
 
45288b8
 
 
 
 
 
 
 
 
 
 
1e2fac3
45288b8
 
 
1e2fac3
d7caadc
1e2fac3
3878c34
e7030d6
45288b8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c28ab9f
45288b8
b957f44
 
45288b8
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
import yfinance as yf
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import gradio as gr

# 📌 Hàm tính True Range trung bình 5 ngày gần nhất và chia 2
def calculate_true_range_half(ticker_symbol):
    stock = yf.Ticker(ticker_symbol)
    data = stock.history(period="7d", interval="1d")  # Lấy dữ liệu 7 ngày để đảm bảo có đủ 5 ngày giao dịch
    
    if data.empty or len(data) < 5:
        return None, None  # Trả về None nếu không đủ dữ liệu
    
    # 📌 Tính True Range của mỗi ngày
    data["True Range"] = data["High"] - data["Low"]
    
    # 📌 Tổng True Range của 5 ngày
    total_tr_5 = data["True Range"].tail(5).sum()  
    
    # 📌 Tính ATR 5 ngày (TRUNG BÌNH của Tổng TR 5 ngày)
    atr_5 = total_tr_5 / 5  
    
    # 📌 Chia đôi ATR 5
    atr_5_half = atr_5 / 2  

    return atr_5, atr_5_half

# 📌 Hàm phân tích Expected Move và so sánh với True Range
def expected_move_analysis(ticker_symbol):
    try:
        # 🟢 Lấy dữ liệu cổ phiếu
        stock = yf.Ticker(ticker_symbol)
        current_price = stock.fast_info["last_price"]  # Giá mới nhất từ phiên giao dịch chính + ngoài giờ
        options_dates = stock.options

        if not options_dates:
            return f"❌ Không có dữ liệu quyền chọn cho {ticker_symbol}.", None

        nearest_expiry = options_dates[0]  # Ngày hết hạn gần nhất
        options_chain = stock.option_chain(nearest_expiry)
        calls = options_chain.calls
        puts = options_chain.puts

        if calls.empty or puts.empty:
            return f"❌ Không có dữ liệu quyền chọn tại ngày hết hạn {nearest_expiry}.", None

        # 🟢 Xác định giá thực hiện ATM gần nhất
        atm_strike = min(calls["strike"], key=lambda x: abs(x - current_price))

        # 🟢 Lấy giá quyền chọn CALL và PUT tại ATM Strike
        atm_call_price = calls[calls["strike"] == atm_strike]["lastPrice"].values[0]
        atm_put_price = puts[puts["strike"] == atm_strike]["lastPrice"].values[0]

        # 🟢 Tính Expected Move
        expected_move = (atm_call_price + atm_put_price) * 0.85
        upper_price = current_price + expected_move
        lower_price = current_price - expected_move

        # 🟢 Lấy IV của quyền chọn ATM
        atm_call_iv = calls[calls["strike"] == atm_strike]["impliedVolatility"].values[0]
        atm_put_iv = puts[puts["strike"] == atm_strike]["impliedVolatility"].values[0]
        iv_skew = atm_call_iv - atm_put_iv  # Chênh lệch IV

        # 🟢 Tính Put/Call Ratio (PCR)
        total_call_volume = calls["volume"].sum()
        total_put_volume = puts["volume"].sum()
        pcr = total_put_volume / total_call_volume if total_call_volume > 0 else None      
    
        # 🟢 Dự đoán xác suất giá tăng / giảm
        prob_up, prob_down = 50, 50  # Mặc định 50/50
        if pcr is not None:
            if pcr < 0.7:
                prob_up += 20
                prob_down -= 20
            elif pcr > 1.0:
                prob_up -= 20
                prob_down += 20

        if iv_skew > 0:
            prob_up += 10
            prob_down -= 10
        else:
            prob_up -= 10
            prob_down += 10

        prob_up = max(0, min(100, prob_up))
        prob_down = max(0, min(100, prob_down))

        # 📌 Tính True Range trung bình 5 ngày gần nhất và chia 2
        atr_5, atr_5_half = calculate_true_range_half(ticker_symbol)

        # 📌 Tính (Giá hiện tại + ATR 5/2) và (Giá hiện tại - ATR 5/2)
        upper_atr5_2 = current_price + atr_5_half
        lower_atr5_2 = current_price - atr_5_half

        # 📈 Vẽ biểu đồ Expected Move & True Range
        fig, ax = plt.subplots(figsize=(8, 5))
        ax.plot(["Lower Bound", "Current Price", "Upper Bound"], 
                [lower_price, current_price, upper_price], 'ro-', label="Expected Move")
        ax.axhline(y=current_price, color='g', linestyle='--', label="Current Price")

        # 🟢 Vẽ đường ATR 5 ngày và ATR 5/2
        if atr_5:
            ax.axhline(y=current_price + atr_5, color='b', linestyle='-.', label="ATR 5 - Upper")
            ax.axhline(y=current_price - atr_5, color='b', linestyle='-.', label="ATR 5 - Lower")
            ax.axhline(y=upper_atr5_2, color='purple', linestyle='-.', label="ATR 5/2 - Upper")
            ax.axhline(y=lower_atr5_2, color='purple', linestyle='-.', label="ATR 5/2 - Lower")

        ax.set_title(f"Expected Move vs True Range for {ticker_symbol}")
        ax.set_ylabel("Price")
        ax.legend()
        ax.grid()

        # 📊 Kết quả hiển thị
        result_text = f"""
        📊 **Dự đoán giá cho {ticker_symbol}**
        - **Giá hiện tại**: {current_price:.2f} USD
        - **Biên độ**: {expected_move:.2f} USD
        - **Giá dự đoán cao nhất**: {upper_price:.2f} USD
        - **Giá dự đoán thấp nhất**: {lower_price:.2f} USD
        - **ATR 5/2**: {atr_5_half:.2f} USD
        - **(+ ATR 5/2)**: {upper_atr5_2:.2f} USD
        - **(- ATR 5/2)**: {lower_atr5_2:.2f} USD

        🔥 **Put/Call Ratio (PCR)**: {pcr:.2f}
        - **IV Call ATM**: {atm_call_iv:.2%}
        - **IV Put ATM**: {atm_put_iv:.2%}
        - **IV Skew**: {iv_skew:.2%}

        📈 **Xác suất giá tăng phiên kế**: {prob_up}%
        📉 **Xác suất giá giảm phiên kế**: {prob_down}%
        """

        return result_text, fig

    except Exception as e:
        return f"❌ Lỗi: {str(e)}", None

# 🚀 Tạo Web App với Gradio
with gr.Blocks(theme=gr.themes.Base(primary_hue="blue")) as app:
        gr.Markdown(f"📊 **NHAT TRAN - DỰ ĐOÁN GIÁ CỔ PHIẾU**")

        # 🌟 Ghi chú hướng dẫn
        gr.Markdown("""
        
        🔷 **Cách sử dụng:**
        
        1️⃣ Nhập **mã cổ phiếu** vào ô bên dưới.
        
        2️⃣ Nhấn **"Phân Tích"** để xem kết quả.

        🔆 Nếu bạn tra cứu tại thời điểm **Open Market** giá sẽ dự đoán trong phiên.
        
        🔆 Nếu bạn tra cứu tại thời điểm **After Market** giá sẽ dự đoán cho phiên kế tiếp.
        
            
        ⚠️ **Lưu ý:**
        
        ❗️Công cụ này chỉ mang tính chất tham khảo,
        thông số đôi lúc sẽ khác biệt so với thực tế.
        Anh chị em cân nhắc trước khi dùng để giao dịch.
        
        ❗️ Công cụ này chỉ áp dụng cho cổ phiếu có **quyền chọn**,
        nếu cổ phiếu không có dữ liệu quyền chọn, **kết quả** sẽ không hiển thị.""")

        stock_input = gr.Textbox(label="Nhập mã cổ phiếu", value="NVDA")
        run_button = gr.Button("Phân Tích")

        output_text = gr.Textbox(label="Kết quả")
        output_plot = gr.Plot()



        run_button.click(expected_move_analysis, inputs=stock_input, outputs=[output_text, output_plot])


app.launch(share=True)