nick5363 commited on
Commit
428be93
·
verified ·
1 Parent(s): c0037c1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +71 -90
app.py CHANGED
@@ -38,133 +38,114 @@ def fetch_most_active_stocks():
38
 
39
  return stocks[:100] # 📈 Giới hạn 100 cổ phiếu
40
 
41
- # 📌 Tính RSI (14 kỳ)
42
- def calculate_rsi(ticker):
43
  try:
44
  stock = yf.Ticker(ticker)
45
- hist = stock.history(period="1mo")
46
  if hist.empty:
47
- return "N/A"
48
 
49
- delta = hist['Close'].diff()
 
 
 
 
 
 
 
 
50
  gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
51
  loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
52
  rs = gain / loss
53
  rsi = 100 - (100 / (1 + rs))
54
- return round(rsi.iloc[-1], 2) if not np.isnan(rsi.iloc[-1]) else "N/A"
55
- except:
56
- return "N/A"
57
-
58
- # 📌 Tính MACD (12,26,9)
59
- def calculate_macd(ticker):
60
- try:
61
- stock = yf.Ticker(ticker)
62
- hist = stock.history(period="3mo")
63
- if hist.empty:
64
- return "N/A"
65
 
66
- short_ema = hist['Close'].ewm(span=12, adjust=False).mean()
67
- long_ema = hist['Close'].ewm(span=26, adjust=False).mean()
68
- macd = short_ema - long_ema
 
69
  signal = macd.ewm(span=9, adjust=False).mean()
70
- return round(macd.iloc[-1], 2), round(signal.iloc[-1], 2)
71
- except:
72
- return "N/A", "N/A"
73
-
74
- # 📌 Tính Bollinger Bands (20,2)
75
- def calculate_bollinger_bands(ticker):
76
- try:
77
- stock = yf.Ticker(ticker)
78
- hist = stock.history(period="3mo")
79
- if hist.empty:
80
- return "N/A", "N/A"
81
 
82
- sma = hist['Close'].rolling(window=20).mean()
83
- std = hist['Close'].rolling(window=20).std()
84
- upper_band = sma + (std * 2)
85
- lower_band = sma - (std * 2)
86
- return round(upper_band.iloc[-1], 2), round(lower_band.iloc[-1], 2)
87
  except:
88
- return "N/A", "N/A"
89
 
90
- # 📌 Lấy dữ liệu quyền chọn và tính toán chỉ số
91
  def analyze_stock_options(ticker):
92
  try:
93
  stock = yf.Ticker(ticker)
94
  current_price = stock.history(period="1d")['Close'].iloc[-1]
 
95
 
96
- rsi = calculate_rsi(ticker)
97
- macd, signal = calculate_macd(ticker)
98
- upper_bb, lower_bb = calculate_bollinger_bands(ticker)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
99
 
100
  return {
101
  'Ticker': ticker,
102
  'Current Price': round(current_price, 2),
 
103
  'RSI': rsi,
104
- 'MACD': macd,
105
- 'Signal Line': signal,
106
- 'Upper BB': upper_bb,
107
- 'Lower BB': lower_bb
 
108
  }
109
  except:
110
  return None
111
 
112
- # 📌 Chạy phân tích danh sách cổ phiếu nhập vào hoặc danh sách từ Yahoo
113
- def main(stock_list=None):
114
- if stock_list is None:
115
- stock_list = fetch_most_active_stocks()
116
-
117
- if not stock_list:
118
- return pd.DataFrame()
119
-
120
- analysis_results = []
121
- with ThreadPoolExecutor(max_workers=10) as executor:
122
- results = executor.map(analyze_stock_options, stock_list)
123
-
124
- for result in results:
125
- if result:
126
- analysis_results.append(result)
127
-
128
- df = pd.DataFrame(analysis_results)
129
- if not df.empty:
130
- df.insert(0, "STT", range(1, len(df) + 1))
131
-
132
- return df
133
-
134
- # 📌 Hiển thị kết quả trong Gradio (Hỗ trợ nhập mã cổ phiếu)
135
  def display_results(stock_symbol):
136
- if stock_symbol:
137
- stock_list = [s.strip().upper() for s in stock_symbol.split(",")]
138
- else:
139
- stock_list = fetch_most_active_stocks()
140
 
141
- df = main(stock_list)
 
 
142
 
143
- if df is None or df.empty:
144
- return "❌ Không có dữ liệu!"
145
-
146
- return df
147
 
148
- # 📅 **Lấy ngày hiện tại để đưa vào tiêu đề**
149
  pacific_timezone = pytz.timezone('America/Los_Angeles')
150
- now_pacific = datetime.now(pacific_timezone)
151
- today = now_pacific.strftime('%d/%m/%Y')
152
  title = f"📊 Phân tích xu hướng cổ phiếu ({today})"
153
 
154
- # ✅ **Tạo giao diện Gradio với ô nhập mã cổ phiếu**
 
155
  iface = gr.Interface(
156
  fn=display_results,
157
- inputs=gr.Textbox(placeholder="Nhập mã cổ phiếu cách nhau bằng dấu phẩy (VD: AAPL, TSLA, NVDA)", label="📌 Nhập mã cổ phiếu (Tùy chọn)"),
158
  outputs="dataframe",
159
  title=title,
160
- description="""🔍 **Dự đoán xu hướng 📈 TĂNG / 📉 GIẢM**
161
-
162
- 🚀 Hướng dẫn sử dụng
163
- 1. **Nhập mã cổ phiếu** (VD: `AAPL, TSLA, NVDA`) hoặc **để trống** (hệ thống sẽ tự lấy mã cổ phiếu).
164
- 2. **Nhấn nút "Submit"** để phân tích xu hướng.
165
- 3. **Ứng dụng sẽ tự động phân tích** và dự đoán
166
- 📈 TĂNG hoặc 📉 GIẢM. """)
167
-
168
 
169
- # ✅ **Chạy ứng dụng Gradio**
170
  iface.launch()
 
38
 
39
  return stocks[:100] # 📈 Giới hạn 100 cổ phiếu
40
 
41
+ # 📌 Tính toán Williams %R (14 kỳ), RSI (14), MACD, Bollinger Bands
42
+ def calculate_technical_indicators(ticker):
43
  try:
44
  stock = yf.Ticker(ticker)
45
+ hist = stock.history(period="3mo") # Lấy dữ liệu 3 tháng để tính toán
46
  if hist.empty:
47
+ return "N/A", "N/A", "N/A", "N/A"
48
 
49
+ # Williams %R (14 kỳ)
50
+ high14 = hist['High'].rolling(window=14).max()
51
+ low14 = hist['Low'].rolling(window=14).min()
52
+ close = hist['Close']
53
+ williams_r = -100 * ((high14 - close) / (high14 - low14))
54
+ williams_r = round(williams_r.iloc[-1], 2) if not np.isnan(williams_r.iloc[-1]) else "N/A"
55
+
56
+ # RSI (14 kỳ)
57
+ delta = close.diff(1)
58
  gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()
59
  loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()
60
  rs = gain / loss
61
  rsi = 100 - (100 / (1 + rs))
62
+ rsi = round(rsi.iloc[-1], 2) if not np.isnan(rsi.iloc[-1]) else "N/A"
 
 
 
 
 
 
 
 
 
 
63
 
64
+ # MACD (12,26,9)
65
+ ema12 = close.ewm(span=12, adjust=False).mean()
66
+ ema26 = close.ewm(span=26, adjust=False).mean()
67
+ macd = ema12 - ema26
68
  signal = macd.ewm(span=9, adjust=False).mean()
69
+ macd_signal = round(macd.iloc[-1] - signal.iloc[-1], 2) if not np.isnan(macd.iloc[-1]) else "N/A"
70
+
71
+ # Bollinger Bands (20,2)
72
+ sma20 = close.rolling(window=20).mean()
73
+ stddev = close.rolling(window=20).std()
74
+ upper_band = sma20 + (stddev * 2)
75
+ lower_band = sma20 - (stddev * 2)
76
+ bollinger_signal = "Buy" if close.iloc[-1] <= lower_band.iloc[-1] else "Sell" if close.iloc[-1] >= upper_band.iloc[-1] else "Neutral"
 
 
 
77
 
78
+ return williams_r, rsi, macd_signal, bollinger_signal
 
 
 
 
79
  except:
80
+ return "N/A", "N/A", "N/A", "N/A"
81
 
82
+ # 📌 Phân tích quyền chọn và xu hướng
83
  def analyze_stock_options(ticker):
84
  try:
85
  stock = yf.Ticker(ticker)
86
  current_price = stock.history(period="1d")['Close'].iloc[-1]
87
+ williams_r, rsi, macd_signal, bollinger_signal = calculate_technical_indicators(ticker)
88
 
89
+ try:
90
+ options = stock.option_chain()
91
+ calls = options.calls
92
+ puts = options.puts
93
+ except:
94
+ return None
95
+
96
+ total_call_volume = calls['volume'].sum()
97
+ total_put_volume = puts['volume'].sum()
98
+ pcr = total_put_volume / total_call_volume if total_call_volume > 0 else np.nan
99
+
100
+ try:
101
+ iv_call = calls['impliedVolatility'].mean()
102
+ iv_put = puts['impliedVolatility'].mean()
103
+ iv_skew = round(iv_call - iv_put, 2) if isinstance(iv_call, float) and isinstance(iv_put, float) else "N/A"
104
+ except:
105
+ iv_skew = "N/A"
106
+
107
+ trend = "📈 TĂNG" if pcr < 0.7 else "📉 GIẢM" if pcr > 1.0 else "➖ NEUTRAL"
108
 
109
  return {
110
  'Ticker': ticker,
111
  'Current Price': round(current_price, 2),
112
+ 'Williams %R': williams_r,
113
  'RSI': rsi,
114
+ 'MACD': macd_signal,
115
+ 'Bollinger': bollinger_signal,
116
+ 'PCR': round(pcr, 2) if not np.isnan(pcr) else "N/A",
117
+ 'IV Skew': iv_skew,
118
+ 'Trend': trend
119
  }
120
  except:
121
  return None
122
 
123
+ # 📌 Chạy ứng dụng trên Gradio
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
124
  def display_results(stock_symbol):
125
+ stock_list = [s.strip().upper() for s in stock_symbol.split(",")] if stock_symbol else fetch_most_active_stocks()
 
 
 
126
 
127
+ valid_stocks = [s for s in stock_list if yf.Ticker(s).info.get("symbol")]
128
+ if not valid_stocks:
129
+ return "❌ Không có dữ liệu hợp lệ!"
130
 
131
+ df = pd.DataFrame(map(analyze_stock_options, valid_stocks))
132
+ df.insert(0, "STT", range(1, len(df) + 1))
133
+ return df if not df.empty else "❌ Không có dữ liệu!"
 
134
 
135
+ # Lấy ngày theo múi giờ Mỹ
136
  pacific_timezone = pytz.timezone('America/Los_Angeles')
137
+ today = datetime.now(pacific_timezone).strftime('%d/%m/%Y')
138
+
139
  title = f"📊 Phân tích xu hướng cổ phiếu ({today})"
140
 
141
+ table_columns = ["STT", "Ticker", "Trend", "Current Price", "Williams %R", "RSI", "MACD", "Bollinger", "PCR", "IV Skew"]
142
+
143
  iface = gr.Interface(
144
  fn=display_results,
145
+ inputs=gr.Textbox(placeholder="Nhập mã cổ phiếu (VD: AAPL, TSLA)", label="📌 Nhập mã cổ phiếu (Tùy chọn)"),
146
  outputs="dataframe",
147
  title=title,
148
+ description="Dự đoán xu hướng với Williams %R, RSI, MACD & Bollinger Bands"
149
+ )
 
 
 
 
 
 
150
 
 
151
  iface.launch()