Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -5,26 +5,27 @@ import numpy as np
|
|
| 5 |
from bs4 import BeautifulSoup
|
| 6 |
import gradio as gr
|
| 7 |
from concurrent.futures import ThreadPoolExecutor
|
|
|
|
| 8 |
|
| 9 |
# 🔗 URL Yahoo Finance Most Active Stocks
|
| 10 |
-
YAHOO_FINANCE_URL = "https://finance.yahoo.com/markets/stocks/most-active/"
|
| 11 |
|
| 12 |
-
# 📌 Lấy danh sách
|
| 13 |
def fetch_most_active_stocks():
|
| 14 |
headers = {
|
| 15 |
-
"User-Agent": "Mozilla/5.0
|
| 16 |
}
|
| 17 |
response = requests.get(YAHOO_FINANCE_URL, headers=headers)
|
| 18 |
|
| 19 |
if response.status_code != 200:
|
| 20 |
-
print(f"❌ Lỗi
|
| 21 |
return []
|
| 22 |
|
| 23 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 24 |
table = soup.find('table')
|
| 25 |
|
| 26 |
if not table:
|
| 27 |
-
print("❌ Không tìm thấy bảng dữ liệu!
|
| 28 |
return []
|
| 29 |
|
| 30 |
rows = table.find_all('tr')[1:]
|
|
@@ -36,26 +37,24 @@ def fetch_most_active_stocks():
|
|
| 36 |
ticker = cols[0].text.strip()
|
| 37 |
stocks.append(ticker)
|
| 38 |
|
| 39 |
-
return stocks[:
|
| 40 |
|
| 41 |
# 📌 Lấy dữ liệu quyền chọn và tính toán chỉ số
|
| 42 |
def analyze_stock_options(ticker):
|
| 43 |
try:
|
| 44 |
stock = yf.Ticker(ticker)
|
|
|
|
| 45 |
|
| 46 |
try:
|
| 47 |
options = stock.option_chain()
|
| 48 |
if options is None:
|
| 49 |
-
print(f"⏳ Không có quyền chọn cho {ticker}, bỏ qua.")
|
| 50 |
return None
|
| 51 |
calls = options.calls
|
| 52 |
puts = options.puts
|
| 53 |
except:
|
| 54 |
-
print(f"⏳ Không có quyền chọn cho {ticker}, bỏ qua.")
|
| 55 |
return None
|
| 56 |
|
| 57 |
if calls is None or puts is None or calls.empty or puts.empty:
|
| 58 |
-
print(f"⚠️ Không có dữ liệu quyền chọn cho {ticker}, bỏ qua.")
|
| 59 |
return None
|
| 60 |
|
| 61 |
# 📌 Tính Put/Call Ratio (PCR)
|
|
@@ -68,10 +67,10 @@ def analyze_stock_options(ticker):
|
|
| 68 |
iv_call = calls['impliedVolatility'].mean()
|
| 69 |
iv_put = puts['impliedVolatility'].mean()
|
| 70 |
iv_skew = round(iv_call - iv_put, 2) if isinstance(iv_call, float) and isinstance(iv_put, float) else "N/A"
|
| 71 |
-
except
|
| 72 |
iv_skew = "N/A"
|
| 73 |
|
| 74 |
-
# 📌 Xác định xu hướng
|
| 75 |
if pcr < 0.7:
|
| 76 |
trend = "📈 BULLISH"
|
| 77 |
elif pcr > 1.0:
|
|
@@ -83,19 +82,18 @@ def analyze_stock_options(ticker):
|
|
| 83 |
|
| 84 |
return {
|
| 85 |
'Ticker': ticker,
|
|
|
|
| 86 |
'PCR': round(pcr, 2) if not np.isnan(pcr) else "N/A",
|
| 87 |
'IV Skew': iv_skew,
|
| 88 |
-
'Trend': trend
|
| 89 |
}
|
| 90 |
-
except
|
| 91 |
-
print(f"⚠️ Lỗi khi xử lý {ticker}: {e}")
|
| 92 |
return None
|
| 93 |
|
| 94 |
# 📌 Chạy nhiều cổ phiếu song song
|
| 95 |
def main():
|
| 96 |
most_active_stocks = fetch_most_active_stocks()
|
| 97 |
if not most_active_stocks:
|
| 98 |
-
print("❌ Không có cổ phiếu nào được tìm thấy.")
|
| 99 |
return pd.DataFrame()
|
| 100 |
|
| 101 |
analysis_results = []
|
|
@@ -106,7 +104,11 @@ def main():
|
|
| 106 |
if result:
|
| 107 |
analysis_results.append(result)
|
| 108 |
|
| 109 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
|
| 111 |
# 📌 Hiển thị kết quả trong Gradio
|
| 112 |
def display_results():
|
|
@@ -117,12 +119,16 @@ def display_results():
|
|
| 117 |
|
| 118 |
return df
|
| 119 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 120 |
# ✅ **Tạo giao diện Gradio**
|
| 121 |
iface = gr.Interface(fn=display_results,
|
| 122 |
inputs=[],
|
| 123 |
outputs="dataframe",
|
| 124 |
-
title=
|
| 125 |
-
description="
|
| 126 |
|
| 127 |
# ✅ **Chạy ứng dụng Gradio**
|
| 128 |
iface.launch()
|
|
|
|
| 5 |
from bs4 import BeautifulSoup
|
| 6 |
import gradio as gr
|
| 7 |
from concurrent.futures import ThreadPoolExecutor
|
| 8 |
+
from datetime import datetime
|
| 9 |
|
| 10 |
# 🔗 URL Yahoo Finance Most Active Stocks
|
| 11 |
+
YAHOO_FINANCE_URL = "https://finance.yahoo.com/markets/stocks/most-active/?start=25&count=100"
|
| 12 |
|
| 13 |
+
# 📌 Lấy danh sách 100 cổ phiếu hoạt động mạnh nhất
|
| 14 |
def fetch_most_active_stocks():
|
| 15 |
headers = {
|
| 16 |
+
"User-Agent": "Mozilla/5.0"
|
| 17 |
}
|
| 18 |
response = requests.get(YAHOO_FINANCE_URL, headers=headers)
|
| 19 |
|
| 20 |
if response.status_code != 200:
|
| 21 |
+
print(f"❌ Lỗi HTTP {response.status_code}")
|
| 22 |
return []
|
| 23 |
|
| 24 |
soup = BeautifulSoup(response.text, 'html.parser')
|
| 25 |
table = soup.find('table')
|
| 26 |
|
| 27 |
if not table:
|
| 28 |
+
print("❌ Không tìm thấy bảng dữ liệu!")
|
| 29 |
return []
|
| 30 |
|
| 31 |
rows = table.find_all('tr')[1:]
|
|
|
|
| 37 |
ticker = cols[0].text.strip()
|
| 38 |
stocks.append(ticker)
|
| 39 |
|
| 40 |
+
return stocks[:100] # 📈 Tăng lên 100 cổ phiếu
|
| 41 |
|
| 42 |
# 📌 Lấy dữ liệu quyền chọn và tính toán chỉ số
|
| 43 |
def analyze_stock_options(ticker):
|
| 44 |
try:
|
| 45 |
stock = yf.Ticker(ticker)
|
| 46 |
+
current_price = stock.history(period="1d")["Close"].iloc[-1] # 📌 Lấy giá hiện tại
|
| 47 |
|
| 48 |
try:
|
| 49 |
options = stock.option_chain()
|
| 50 |
if options is None:
|
|
|
|
| 51 |
return None
|
| 52 |
calls = options.calls
|
| 53 |
puts = options.puts
|
| 54 |
except:
|
|
|
|
| 55 |
return None
|
| 56 |
|
| 57 |
if calls is None or puts is None or calls.empty or puts.empty:
|
|
|
|
| 58 |
return None
|
| 59 |
|
| 60 |
# 📌 Tính Put/Call Ratio (PCR)
|
|
|
|
| 67 |
iv_call = calls['impliedVolatility'].mean()
|
| 68 |
iv_put = puts['impliedVolatility'].mean()
|
| 69 |
iv_skew = round(iv_call - iv_put, 2) if isinstance(iv_call, float) and isinstance(iv_put, float) else "N/A"
|
| 70 |
+
except:
|
| 71 |
iv_skew = "N/A"
|
| 72 |
|
| 73 |
+
# 📌 Xác định xu hướng 📈📉
|
| 74 |
if pcr < 0.7:
|
| 75 |
trend = "📈 BULLISH"
|
| 76 |
elif pcr > 1.0:
|
|
|
|
| 82 |
|
| 83 |
return {
|
| 84 |
'Ticker': ticker,
|
| 85 |
+
'Current Price': round(current_price, 2),
|
| 86 |
'PCR': round(pcr, 2) if not np.isnan(pcr) else "N/A",
|
| 87 |
'IV Skew': iv_skew,
|
| 88 |
+
'Trend': trend
|
| 89 |
}
|
| 90 |
+
except:
|
|
|
|
| 91 |
return None
|
| 92 |
|
| 93 |
# 📌 Chạy nhiều cổ phiếu song song
|
| 94 |
def main():
|
| 95 |
most_active_stocks = fetch_most_active_stocks()
|
| 96 |
if not most_active_stocks:
|
|
|
|
| 97 |
return pd.DataFrame()
|
| 98 |
|
| 99 |
analysis_results = []
|
|
|
|
| 104 |
if result:
|
| 105 |
analysis_results.append(result)
|
| 106 |
|
| 107 |
+
df = pd.DataFrame(analysis_results)
|
| 108 |
+
if not df.empty:
|
| 109 |
+
df.insert(0, "STT", range(1, len(df) + 1)) # 📌 Thêm cột Số Thứ Tự (STT)
|
| 110 |
+
|
| 111 |
+
return df
|
| 112 |
|
| 113 |
# 📌 Hiển thị kết quả trong Gradio
|
| 114 |
def display_results():
|
|
|
|
| 119 |
|
| 120 |
return df
|
| 121 |
|
| 122 |
+
# 📅 **Lấy ngày hiện tại để đưa vào tiêu đề**
|
| 123 |
+
today = datetime.today().strftime('%d/%m/%Y')
|
| 124 |
+
title = f"📊 Phân tích xu hướng cổ phiếu ({today})"
|
| 125 |
+
|
| 126 |
# ✅ **Tạo giao diện Gradio**
|
| 127 |
iface = gr.Interface(fn=display_results,
|
| 128 |
inputs=[],
|
| 129 |
outputs="dataframe",
|
| 130 |
+
title=title,
|
| 131 |
+
description="Dự đoán xu hướng 📈 BULLISH / 📉 BEARISH")
|
| 132 |
|
| 133 |
# ✅ **Chạy ứng dụng Gradio**
|
| 134 |
iface.launch()
|