Delete app2.py
Browse files
app2.py
DELETED
|
@@ -1,193 +0,0 @@
|
|
| 1 |
-
import yfinance as yf
|
| 2 |
-
import pandas as pd
|
| 3 |
-
import streamlit as st
|
| 4 |
-
import requests
|
| 5 |
-
from bs4 import BeautifulSoup
|
| 6 |
-
from datetime import datetime
|
| 7 |
-
|
| 8 |
-
# ==============================
|
| 9 |
-
# 📌 LẤY DỮ LIỆU TỪ YFINANCE
|
| 10 |
-
# ==============================
|
| 11 |
-
def get_stock_data(ticker):
|
| 12 |
-
try:
|
| 13 |
-
stock = yf.Ticker(ticker)
|
| 14 |
-
hist = stock.history(period="11d")
|
| 15 |
-
if len(hist) < 11:
|
| 16 |
-
return None, None, None
|
| 17 |
-
avg_volume = hist["Volume"][:-1].mean()
|
| 18 |
-
today_volume = hist["Volume"][-1]
|
| 19 |
-
price = hist["Close"][-1]
|
| 20 |
-
change = ((hist["Close"][-1] - hist["Close"][-2]) / hist["Close"][-2]) * 100
|
| 21 |
-
vol_ratio = today_volume / avg_volume if avg_volume else None
|
| 22 |
-
return price, change, vol_ratio
|
| 23 |
-
except:
|
| 24 |
-
return None, None, None
|
| 25 |
-
|
| 26 |
-
def get_pcr(ticker):
|
| 27 |
-
try:
|
| 28 |
-
opt = yf.Ticker(ticker).option_chain()
|
| 29 |
-
calls = opt.calls
|
| 30 |
-
puts = opt.puts
|
| 31 |
-
call_volume = calls["volume"].sum()
|
| 32 |
-
put_volume = puts["volume"].sum()
|
| 33 |
-
if call_volume > 0:
|
| 34 |
-
return round(put_volume / call_volume, 2)
|
| 35 |
-
except:
|
| 36 |
-
return None
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
# ==============================
|
| 40 |
-
# 📌 LẤY DỮ LIỆU VIX
|
| 41 |
-
# ==============================
|
| 42 |
-
def get_vix_index():
|
| 43 |
-
vix = yf.Ticker("^VIX")
|
| 44 |
-
df = vix.history(period="1d")
|
| 45 |
-
|
| 46 |
-
if df.empty:
|
| 47 |
-
return None
|
| 48 |
-
|
| 49 |
-
return df["Close"].iloc[-1]
|
| 50 |
-
|
| 51 |
-
# ==============================
|
| 52 |
-
# 📌 LẤY LỢI SUẤT TRÁI PHIẾU 10 NĂM TỪ FRED
|
| 53 |
-
# ==============================
|
| 54 |
-
def get_bond_yield():
|
| 55 |
-
FRED_API_KEY = "f312589066a1d21d3c09fc5cec6d9421"
|
| 56 |
-
url = f"https://api.stlouisfed.org/fred/series/observations?series_id=GS10&api_key={FRED_API_KEY}&file_type=json"
|
| 57 |
-
|
| 58 |
-
response = requests.get(url).json()
|
| 59 |
-
|
| 60 |
-
if "observations" in response:
|
| 61 |
-
return float(response["observations"][-1]["value"])
|
| 62 |
-
|
| 63 |
-
return None
|
| 64 |
-
# ==============================
|
| 65 |
-
# 📌 LẤY DỮ LIỆU VÀNG (GOLD)
|
| 66 |
-
# ==============================
|
| 67 |
-
def get_gold_data():
|
| 68 |
-
gold = yf.Ticker("GC=F") # Gold Futures
|
| 69 |
-
df = gold.history(period="2d")
|
| 70 |
-
|
| 71 |
-
if len(df) < 2:
|
| 72 |
-
return None, None
|
| 73 |
-
|
| 74 |
-
latest = df.iloc[-1]["Close"]
|
| 75 |
-
prev = df.iloc[-2]["Close"]
|
| 76 |
-
change = ((latest - prev) / prev) * 100
|
| 77 |
-
return latest, change
|
| 78 |
-
# ==============================
|
| 79 |
-
# BẢNG LỊCH BÁO CÁO KINH TẾ
|
| 80 |
-
# ==============================
|
| 81 |
-
def get_us_economic_calendar():
|
| 82 |
-
url = "https://wbfintool.com/economic-calendar/"
|
| 83 |
-
headers = {
|
| 84 |
-
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.3"
|
| 85 |
-
}
|
| 86 |
-
response = requests.get(url, headers=headers)
|
| 87 |
-
soup = BeautifulSoup(response.content, "html.parser")
|
| 88 |
-
|
| 89 |
-
# Tìm bảng chứa lịch kinh tế
|
| 90 |
-
table = soup.find("table", {"id": "economic-calendar"})
|
| 91 |
-
if not table:
|
| 92 |
-
return pd.DataFrame() # Trả về DataFrame rỗng nếu không tìm thấy bảng
|
| 93 |
-
|
| 94 |
-
rows = table.find_all("tr")
|
| 95 |
-
data = []
|
| 96 |
-
|
| 97 |
-
for row in rows:
|
| 98 |
-
cols = row.find_all("td")
|
| 99 |
-
if len(cols) == 6: # Giả sử bảng có 6 cột
|
| 100 |
-
time = cols[0].get_text(strip=True)
|
| 101 |
-
currency = cols[1].get_text(strip=True)
|
| 102 |
-
impact = cols[2].get_text(strip=True)
|
| 103 |
-
event = cols[3].get_text(strip=True)
|
| 104 |
-
actual = cols[4].get_text(strip=True)
|
| 105 |
-
forecast = cols[5].get_text(strip=True)
|
| 106 |
-
|
| 107 |
-
# Chỉ lấy các sự kiện của Hoa Kỳ
|
| 108 |
-
if currency == "USD":
|
| 109 |
-
data.append({
|
| 110 |
-
"Thời gian": time,
|
| 111 |
-
"Tiền tệ": currency,
|
| 112 |
-
"Tầm ảnh hưởng": impact,
|
| 113 |
-
"Sự kiện": event,
|
| 114 |
-
"Thực tế": actual,
|
| 115 |
-
"Dự báo": forecast
|
| 116 |
-
})
|
| 117 |
-
|
| 118 |
-
df = pd.DataFrame(data)
|
| 119 |
-
return df
|
| 120 |
-
|
| 121 |
-
# Sử dụng hàm và hiển thị kết quả
|
| 122 |
-
df_calendar = get_us_economic_calendar()
|
| 123 |
-
print(df_calendar)
|
| 124 |
-
# ==============================
|
| 125 |
-
# 📌 PHÂN TÍCH THỊ TRƯỜNG
|
| 126 |
-
# ==============================
|
| 127 |
-
st.title("📉 Bộ Cảnh Báo Rủi Ro Thị Trường & Gợi Ý ETF Nghịch Đảo")
|
| 128 |
-
|
| 129 |
-
tickers = {
|
| 130 |
-
"SPY": "S&P 500",
|
| 131 |
-
"QQQ": "NASDAQ 100",
|
| 132 |
-
"IWM": "Russell 2000"
|
| 133 |
-
}
|
| 134 |
-
|
| 135 |
-
market_data = {}
|
| 136 |
-
|
| 137 |
-
for ticker, name in tickers.items():
|
| 138 |
-
price, change, vol_ratio = get_stock_data(ticker)
|
| 139 |
-
pcr = get_pcr(ticker)
|
| 140 |
-
market_data[ticker] = {
|
| 141 |
-
"change": f"{change:.2f}%" if change is not None else "N/A",
|
| 142 |
-
"price": f"${price:.2f}" if price is not None else "N/A",
|
| 143 |
-
"volume_ratio": f"{vol_ratio:.2f}x" if vol_ratio is not None else "N/A",
|
| 144 |
-
"pcr": f"{pcr}" if pcr is not None else "N/A"
|
| 145 |
-
}
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
# 🔹 **Hiển thị thị trường**
|
| 151 |
-
st.subheader("📊 Thị Trường Chung")
|
| 152 |
-
for ticker, data in market_data.items():
|
| 153 |
-
st.write(f"**{ticker}**: {data['change']} | Giá: {data['price']} | Volume: {data['volume_ratio']} | PCR: {data['pcr']}")
|
| 154 |
-
if 'pcr' in data and data['pcr'] is not None:
|
| 155 |
-
pcr_value = float(data['pcr']) if data['pcr'] != "N/A" else None
|
| 156 |
-
|
| 157 |
-
if pcr_value > 1.2:
|
| 158 |
-
st.warning("PCR cao → Nhiều người mua PUT → Thị trường có thể suy yếu.")
|
| 159 |
-
elif pcr_value < 0.7:
|
| 160 |
-
st.success("PCR thấp → Nhiều người mua CALL → Thị trường có thể tích cực.")
|
| 161 |
-
else:
|
| 162 |
-
st.info("PCR trung bình → Tâm lý thị trường trung lập.")
|
| 163 |
-
|
| 164 |
-
# 🔹 **Lấy dữ liệu VIX**
|
| 165 |
-
vix_index = get_vix_index()
|
| 166 |
-
st.write(f"🛑 **VIX Index**: {vix_index:.1f}" if vix_index else "Không có dữ liệu VIX")
|
| 167 |
-
|
| 168 |
-
# 🔹 **Lấy dữ liệu trái phiếu & lãi suất**
|
| 169 |
-
bond_yield = get_bond_yield()
|
| 170 |
-
st.subheader("📊 Trái Phiếu & Lãi Suất")
|
| 171 |
-
st.write(f"📉 **Lợi suất 10 năm (UST10Y)**: {bond_yield:.2f}%" if bond_yield else "Không có dữ liệu lợi suất")
|
| 172 |
-
|
| 173 |
-
# Thêm sau phần Trái Phiếu
|
| 174 |
-
st.subheader("🏆 Vàng (Gold)")
|
| 175 |
-
|
| 176 |
-
gold_price, gold_change = get_gold_data()
|
| 177 |
-
if gold_price and gold_change is not None:
|
| 178 |
-
st.write(f"Giá vàng: ${gold_price:.2f} | Biến động: {gold_change:.2f}%")
|
| 179 |
-
if gold_change > 0.5:
|
| 180 |
-
st.warning("Vàng tăng mạnh → Cảnh báo tâm lý phòng thủ trên thị trường!")
|
| 181 |
-
elif gold_change < -0.5:
|
| 182 |
-
st.info("Vàng giảm → Nhà đầu tư đang lạc quan.")
|
| 183 |
-
else:
|
| 184 |
-
st.write("Không lấy được dữ liệu vàng.")
|
| 185 |
-
# ==============================
|
| 186 |
-
# 📌 GỢI Ý ETF NGHỊCH ĐẢO
|
| 187 |
-
# ==============================
|
| 188 |
-
st.subheader("🔄 Gợi Ý ETF Nghịch Đảo")
|
| 189 |
-
|
| 190 |
-
if vix_index and vix_index > 20 or market_data["SPY"]["change"].startswith("-"):
|
| 191 |
-
st.error("⚠️ Thị trường có dấu hiệu suy yếu, có thể xem xét ETF nghịch đảo như SQQQ, SPXS, UVXY.")
|
| 192 |
-
else:
|
| 193 |
-
st.success("✅ Thị trường chưa có dấu hiệu suy yếu lớn, chưa cần sử dụng ETF nghịch đảo.")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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