import os import streamlit as st from streamlit_autorefresh import st_autorefresh import pandas as pd import gspread from oauth2client.service_account import ServiceAccountCredentials import json from datetime import datetime, timedelta import time # Cấu hình xác thực scope = ["https://spreadsheets.google.com/feeds", "https://www.googleapis.com/auth/drive"] # Sử dụng os.getenv để lấy thông tin xác thực từ Hugging Face Secrets creds_dict = json.loads(os.getenv("GOOGLE_CREDENTIALS", "{}")) creds = ServiceAccountCredentials.from_json_keyfile_dict(creds_dict, scope) client = gspread.authorize(creds) # URL của Google Sheets sheet_url = os.getenv("GOOGLE_LINKS_FLASHDEAL") # Kiểm tra xem sheet_url có phải là một chuỗi hợp lệ không if not isinstance(sheet_url, str) or not sheet_url: st.error("Google Sheets URL is not set properly.") st.stop() # Đọc dữ liệu từ Google Sheets def load_data(): sheet = client.open_by_url(sheet_url).sheet1 data = sheet.get_all_records() df = pd.DataFrame(data) return df # Hiển thị dữ liệu với CSS def display_with_css(df): st.markdown( f""" """, unsafe_allow_html=True ) def format_value(val, class_name): if pd.isna(val): return f'' return f'{val}' def format_row(row): try: percent_value = row["%"] except KeyError: percent_value = 0 # Hoặc giá trị mặc định nào đó gia_hien_tai_color_class = "" if percent_value > 0: gia_hien_tai_color_class = "gia_hien_tai" elif percent_value < 0: gia_hien_tai_color_class = "gia_hien_tai" else: gia_hien_tai_color_class = "gia_hien_tai" return [ f'{row["Mã"]}', format_value(row.get("Tín hiệu", ""), "tin_hieu"), # Sử dụng get để tránh lỗi KeyError f'{row.get("Giá hiện tại", "")}', f'{percent_value}' ] # Lọc dữ liệu để chỉ hiển thị các dòng có giá trị trong cột "Tín hiệu" df_filtered = df[df["Tín hiệu"].notnull() & df["Tín hiệu"].str.strip().ne("")] formatted_rows = [format_row(row) for _, row in df_filtered.iterrows()] html = "
" html += "" html += "" for row in formatted_rows: html += "" + "".join(row) + "" html += "
Tín hiệuGiá hiện tại%
" st.markdown(html, unsafe_allow_html=True) def main(): st.title("FioStock - Cố vấn đầu tư") current_date = datetime.now().strftime("%Y-%m-%d") st.write(f"Khuyến nghị giao dịch cổ phiếu ngày {current_date}") # Thông báo thời gian hoàn tất việc cập nhật update_time = datetime.now() + timedelta(hours=5) update_time_str = update_time.strftime("%Y-%m-%d %H:%M:%S") st.write(f" Cập nhật vào lúc {update_time_str}") data = load_data() display_with_css(data) # Tự động làm mới trang sau mỗi 10 giây st_autorefresh(interval=10 * 1000) if __name__ == "__main__": main()