Spaces:
Sleeping
Sleeping
Update app.py
Browse files37 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917037 unmodified linesreturn stocks[:100] # 📈 Giới hạn 100 cổ phiếu# 📌 Tính RSI (14 kỳ)def calculate_rsi(ticker):try:stock = yf.Ticker(ticker)hist = stock.history(period="1mo")if hist.empty:return "N/A"delta = hist['Close'].diff()gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()rs = gain / lossrsi = 100 - (100 / (1 + rs))return round(rsi.iloc[-1], 2) if not np.isnan(rsi.iloc[-1]) else "N/A"except:return "N/A"# 📌 Tính MACD (12,26,9)def calculate_macd(ticker):try:stock = yf.Ticker(ticker)hist = stock.history(period="3mo")if hist.empty:return "N/A"short_ema = hist['Close'].ewm(span=12, adjust=False).mean()long_ema = hist['Close'].ewm(span=26, adjust=False).mean()macd = short_ema - long_emasignal = macd.ewm(span=9, adjust=False).mean()return round(macd.iloc[-1], 2), round(signal.iloc[-1], 2)except:return "N/A", "N/A"# 📌 Tính Bollinger Bands (20,2)def calculate_bollinger_bands(ticker):try:stock = yf.Ticker(ticker)hist = stock.history(period="3mo")if hist.empty:return "N/A", "N/A"sma = hist['Close'].rolling(window=20).mean()std = hist['Close'].rolling(window=20).std()upper_band = sma + (std * 2)lower_band = sma - (std * 2)return round(upper_band.iloc[-1], 2), round(lower_band.iloc[-1], 2)except:return "N/A", "N/A"# 📌 Lấy dữ liệu quyền chọn và tính toán chỉ sốdef analyze_stock_options(ticker):try:stock = yf.Ticker(ticker)current_price = stock.history(period="1d")['Close'].iloc[-1]rsi = calculate_rsi(ticker)macd, signal = calculate_macd(ticker)upper_bb, lower_bb = calculate_bollinger_bands(ticker)return {'Ticker': ticker,'Current Price': round(current_price, 2),'RSI': rsi,'MACD': macd,'Signal Line': signal,'Upper BB': upper_bb,'Lower BB': lower_bb}except:return None# 📌 Chạy phân tích danh sách cổ phiếu nhập vào hoặc danh sách từ Yahoodef main(stock_list=None):if stock_list is None:stock_list = fetch_most_active_stocks()if not stock_list:return pd.DataFrame()analysis_results = []with ThreadPoolExecutor(max_workers=10) as executor:results = executor.map(analyze_stock_options, stock_list)for result in results:if result:analysis_results.append(result)df = pd.DataFrame(analysis_results)if not df.empty:df.insert(0, "STT", range(1, len(df) + 1))return df# 📌 Hiển thị kết quả trong Gradio (Hỗ trợ nhập mã cổ phiếu)def display_results(stock_symbol):if stock_symbol:stock_list = [s.strip().upper() for s in stock_symbol.split(",")]else:stock_list = fetch_most_active_stocks()df = main(stock_list)if df is None or df.empty:return "❌ Không có dữ liệu!"return df# 📅 **Lấy ngày hiện tại để đưa vào tiêu đề**pacific_timezone = pytz.timezone('America/Los_Angeles')now_pacific = datetime.now(pacific_timezone)today = now_pacific.strftime('%d/%m/%Y')title = f"📊 Phân tích xu hướng cổ phiếu ({today})"# ✅ **Tạo giao diện Gradio với ô nhập mã cổ phiếu**iface = gr.Interface(fn=display_results,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)"),outputs="dataframe",title=title,description="""🔍 **Dự đoán xu hướng 📈 TĂNG / 📉 GIẢM**🚀 Hướng dẫn sử dụng1. **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).2. **Nhấn nút "Submit"** để phân tích xu hướng.3. **Ứng dụng sẽ tự động phân tích** và dự đoán📈 TĂNG hoặc 📉 GIẢM. """)# ✅ **Chạy ứng dụng Gradio**iface.launch()37 unmodified lines383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015137 unmodified linesreturn stocks[:100] # 📈 Giới hạn 100 cổ phiếu# 📌 Tính toán Williams %R (14 kỳ), RSI (14), MACD, Bollinger Bandsdef calculate_technical_indicators(ticker):try:stock = yf.Ticker(ticker)hist = stock.history(period="3mo") # Lấy dữ liệu 3 tháng để tính toánif hist.empty:return "N/A", "N/A", "N/A", "N/A"# Williams %R (14 kỳ)high14 = hist['High'].rolling(window=14).max()low14 = hist['Low'].rolling(window=14).min()close = hist['Close']williams_r = -100 * ((high14 - close) / (high14 - low14))williams_r = round(williams_r.iloc[-1], 2) if not np.isnan(williams_r.iloc[-1]) else "N/A"# RSI (14 kỳ)delta = close.diff(1)gain = (delta.where(delta > 0, 0)).rolling(window=14).mean()loss = (-delta.where(delta < 0, 0)).rolling(window=14).mean()rs = gain / lossrsi = 100 - (100 / (1 + rs))rsi = round(rsi.iloc[-1], 2) if not np.isnan(rsi.iloc[-1]) else "N/A"# MACD (12,26,9)ema12 = close.ewm(span=12, adjust=False).mean()ema26 = close.ewm(span=26, adjust=False).mean()macd = ema12 - ema26signal = macd.ewm(span=9, adjust=False).mean()macd_signal = round(macd.iloc[-1] - signal.iloc[-1], 2) if not np.isnan(macd.iloc[-1]) else "N/A"# Bollinger Bands (20,2)sma20 = close.rolling(window=20).mean()stddev = close.rolling(window=20).std()upper_band = sma20 + (stddev * 2)lower_band = sma20 - (stddev * 2)bollinger_signal = "Buy" if close.iloc[-1] <= lower_band.iloc[-1] else "Sell" if close.iloc[-1] >= upper_band.iloc[-1] else "Neutral"return williams_r, rsi, macd_signal, bollinger_signalexcept:return "N/A", "N/A", "N/A", "N/A"# 📌 Phân tích quyền chọn và xu hướngdef analyze_stock_options(ticker):try:stock = yf.Ticker(ticker)current_price = stock.history(period="1d")['Close'].iloc[-1]williams_r, rsi, macd_signal, bollinger_signal = calculate_technical_indicators(ticker)try:options = stock.option_chain()calls = options.callsputs = options.putsexcept:return Nonetotal_call_volume = calls['volume'].sum()total_put_volume = puts['volume'].sum()pcr = total_put_volume / total_call_volume if total_call_volume > 0 else np.nantry:iv_call = calls['impliedVolatility'].mean()iv_put = puts['impliedVolatility'].mean()iv_skew = round(iv_call - iv_put, 2) if isinstance(iv_call, float) and isinstance(iv_put, float) else "N/A"except:iv_skew = "N/A"trend = "📈 TĂNG" if pcr < 0.7 else "📉 GIẢM" if pcr > 1.0 else "➖ NEUTRAL"return {'Ticker': ticker,'Current Price': round(current_price, 2),'Williams %R': williams_r,'RSI': rsi,'MACD': macd_signal,'Bollinger': bollinger_signal,'PCR': round(pcr, 2) if not np.isnan(pcr) else "N/A",'IV Skew': iv_skew,'Trend': trend}except:return None# 📌 Chạy ứng dụng trên Gradiodef display_results(stock_symbol):stock_list = [s.strip().upper() for s in stock_symbol.split(",")] if stock_symbol else fetch_most_active_stocks()valid_stocks = [s for s in stock_list if yf.Ticker(s).info.get("symbol")]if not valid_stocks:return "❌ Không có dữ liệu hợp lệ!"df = pd.DataFrame(map(analyze_stock_options, valid_stocks))df.insert(0, "STT", range(1, len(df) + 1))return df if not df.empty else "❌ Không có dữ liệu!"# Lấy ngày theo múi giờ Mỹpacific_timezone = pytz.timezone('America/Los_Angeles')today = datetime.now(pacific_timezone).strftime('%d/%m/%Y')title = f"📊 Phân tích xu hướng cổ phiếu ({today})"table_columns = ["STT", "Ticker", "Trend", "Current Price", "Williams %R", "RSI", "MACD", "Bollinger", "PCR", "IV Skew"]iface = gr.Interface(fn=display_results,inputs=gr.Textbox(placeholder="Nhập mã cổ phiếu (VD: AAPL, TSLA)", label="📌 Nhập mã cổ phiếu (Tùy chọn)"),outputs="dataframe",title=title,description="Dự đoán xu hướng với Williams %R, RSI, MACD & Bollinger Bands")iface.launch()
app.py+71-90