import streamlit as st import pandas as pd import requests from bs4 import BeautifulSoup import json from datetime import timedelta, timezone import datetime from supabase import create_client, Client import time import re import os import extra_streamlit_components as stx import plotly.express as px import streamlit.components.v1 as components # --- 頁面基本設定 --- st.set_page_config(page_title="錢進自由", layout="wide", page_icon="📈", initial_sidebar_state="collapsed") # ========================================== # 📱 🚀 手機版視覺優化 CSS + 👻 隱藏 UI 終極版 # ========================================== st.markdown(""" """, unsafe_allow_html=True) # ========================================== # 💱 即時匯率 API (擷取 USD/TWD) # ========================================== @st.cache_data(ttl=3600) def get_usd_twd_rate(): try: res = requests.get("https://api.exchangerate-api.com/v4/latest/USD", timeout=3) return float(res.json()["rates"]["TWD"]) except: return 32.0 usd_twd_rate = get_usd_twd_rate() # ========================================== # 🍪 系統初始化與登入 # ========================================== cookie_manager = stx.CookieManager(key="my_cookies") @st.cache_resource def init_supabase() -> Client: return create_client(os.environ.get("SUPABASE_URL"), os.environ.get("SUPABASE_KEY")) supabase = init_supabase() def login_ui(): if "user_email" in st.session_state: return True cookies = cookie_manager.get_all() saved_email = cookies.get("user_email") if isinstance(cookies, dict) else None if saved_email: st.session_state["user_email"] = saved_email return True st.markdown("

🛋️ 錢進自由

", unsafe_allow_html=True) # 💡 放大版、高質感的安全聲明與提示方塊 st.markdown("""

💡 為改善登入機制,請老朋友使用您「原本登入的Google信箱」作為帳號進行註冊,系統將自動無縫還原您所有的歷史資產資料!

🔒 所有使用者的密碼均由國際級資料庫 Supabase 進行高強度加密儲存,本網站及系統管理員絕對無法得知您的密碼,請安心設定並使用。

""", unsafe_allow_html=True) # 📝 帳號密碼輸入表單 with st.form("login_form"): email = st.text_input("✉️ 電子信箱 (Email)", placeholder="請輸入信箱") password = st.text_input("🔑 密碼 (Password)", type="password", placeholder="請輸入密碼 (至少 6 位數)") c1, c2 = st.columns(2) btn_login = c1.form_submit_button("🚀 登入", use_container_width=True) btn_signup = c2.form_submit_button("📝 註冊新帳號", use_container_width=True) if btn_login: if not email or not password: st.warning("⚠️ 請輸入信箱與密碼!") else: try: res = supabase.auth.sign_in_with_password({"email": email, "password": password}) st.session_state["user_email"] = res.user.email cookie_manager.set("user_email", res.user.email, max_age=30*24*60*60) st.rerun() except Exception as e: st.error("🛑 登入失敗:請確認信箱與密碼是否正確。若為首次使用,請先點擊「註冊新帳號」。") if btn_signup: if not email or len(password) < 6: st.warning("⚠️ 請輸入信箱,且密碼需至少 6 位數!") else: try: res = supabase.auth.sign_up({"email": email, "password": password}) if res.user: st.success("🎉 註冊成功!系統正在為您登入...") st.session_state["user_email"] = res.user.email cookie_manager.set("user_email", res.user.email, max_age=30*24*60*60) time.sleep(1) st.rerun() except Exception as e: st.error(f"🛑 註冊失敗:此信箱可能已被註冊,或密碼格式不符。({e})") return False if not login_ui(): st.stop() # ========================================== # 🗄️ 資料庫讀寫與自動補齊 # ========================================== user_email = st.session_state["user_email"] def load_data(): try: res = supabase.table("user_data").select("*").eq("email", user_email).execute() except Exception as e: if "JWT expired" in str(e) or "PGRST303" in str(e): try: supabase.auth.sign_out() except: pass cookie_manager.delete("user_email", key="del_load") st.session_state.clear() init_supabase.clear() st.error("🔒 系統安全機制:登入時效已過期,請重新登入!") time.sleep(2) st.rerun() else: raise e defaults = {"fee_discount": 6.0, "us_stock_fee": 0.0, "pledge_amount": 0.0, "account_balance": 0.0, "usd_balance": 0.0, "credit_loan": 0.0, "mortgage_amount": 0.0, "other_assets": 0.0, "buy_records": [], "realized_records": [], "history": {}, "market_data": {}, "futures_capital": 0.0} if len(res.data) == 0: supabase.table("user_data").insert({"email": user_email, "data": defaults}).execute() return defaults data = res.data[0]["data"] updated = False for k, v in defaults.items(): if k not in data: data[k] = v; updated = True if updated: save_data(data) return data def save_data(data): try: supabase.table("user_data").update({"data": data}).eq("email", user_email).execute() except Exception as e: if "JWT expired" in str(e) or "PGRST303" in str(e): try: supabase.auth.sign_out() except: pass cookie_manager.delete("user_email", key="del_save") st.session_state.clear() init_supabase.clear() st.rerun() else: raise e db = load_data() # --- 🚀 爬蟲與精算引擎 --- def fetch_price(ticker): price, name = 0.0, ticker t_l = ticker.lower() for url, tag in [(f"https://www.wantgoo.com/stock/{t_l}", 'span')]: try: resp = requests.get(url, headers={'User-Agent': 'Mozilla/5.0'}, timeout=5) soup = BeautifulSoup(resp.text, 'html.parser') node = soup.find(tag, class_='deal', attrs={'c-model': 'close'}) if node and node.text.strip() != "--": price = float(node.text.replace(',', '')) nh3 = soup.find('h3', attrs={'c-model': 'name'}) if nh3: name = nh3.text.strip() break except: pass if price == 0.0: try: url_y = f"https://tw.stock.yahoo.com/quote/{ticker}" resp_y = requests.get(url_y, headers={'User-Agent': 'Mozilla/5.0'}, timeout=5) soup_y = BeautifulSoup(resp_y.text, 'html.parser') if name == ticker: title_tag = soup_y.find('title') if title_tag: name = title_tag.text.split('(')[0].strip().replace("Yahoo", "").strip() match = re.search(r'"regularMarketPrice":([0-9.]+)', resp_y.text) if match: price = float(match.group(1)) except: pass return price, name def calc_cost_profit(ticker, shares, buy_price, sell_price=None, is_foreign=False): buy_cost = shares * buy_price if is_foreign: us_fee = float(db.get("us_stock_fee", 0.0)) buy_fee = us_fee total_cost = buy_cost + buy_fee if sell_price is not None: sell_rev = shares * sell_price sell_fee = us_fee return round(sell_rev - sell_fee - total_cost) return total_cost else: disc = db.get("fee_discount", 6.0) / 10.0 buy_fee = buy_cost * 0.001425 * disc total_cost = buy_cost + buy_fee if sell_price is not None: sell_rev = shares * sell_price sell_fee = sell_rev * 0.001425 * disc tax_rate = 0.001 if ticker.startswith("00") else 0.003 sell_tax = sell_rev * tax_rate return round(sell_rev - sell_fee - sell_tax - total_cost) return total_cost # ========================================== # 🛑 彈出對話框定義 # ========================================== @st.dialog("🔔 系統提示") def show_success_dialog(): st.markdown(f"
{st.session_state['success_msg']}
", unsafe_allow_html=True) if st.button("確定", type="primary", use_container_width=True): del st.session_state["success_msg"] st.rerun() # 💡 新增:防呆登出確認視窗 @st.dialog("🚪 系統登出") def confirm_logout(): st.markdown("
確定要登出戰情室嗎?
", unsafe_allow_html=True) c1, c2 = st.columns(2) if c1.button("取消", use_container_width=True): st.rerun() if c2.button("確認登出", type="primary", use_container_width=True): try: supabase.auth.sign_out() except: pass cookie_manager.delete("user_email", key="del_logout_confirm") st.session_state.clear() init_supabase.clear() components.html("""""", height=0) st.stop() @st.dialog("⚙️ 設定中心") def show_settings(): new_disc = st.number_input("台股手續費折數", value=float(db.get("fee_discount", 6.0))) new_us_fee = st.number_input("美股手續費 (單筆/美元)", value=float(db.get("us_stock_fee", 0.0))) if st.button("💾 儲存並關閉", type="primary", use_container_width=True): db["fee_discount"] = new_disc db["us_stock_fee"] = new_us_fee save_data(db); st.rerun() @st.dialog("➕ 新增股票") def add_stock(): d = st.date_input("日期") t = st.text_input("股票代號", placeholder="如2330、00631L、VOO、AAPL等代號").upper() s = st.number_input("股數", min_value=1, step=1) p = st.number_input("成交價 (原幣別)", min_value=0.01) if st.button("確認新增", type="primary", use_container_width=True): if t: pr, na = fetch_price(t); db["market_data"][t] = {"price": pr, "name": na} db["buy_records"].append({"id": int(time.time()), "date": str(d), "ticker": t, "shares": s, "price": p}) save_data(db) st.session_state["success_msg"] = "✅ 新增成功,記得去手動更新銀行帳戶餘額哦!" st.rerun() @st.dialog("🔍 股票明細") def show_details(ticker, name): recs = sorted([r for r in db["buy_records"] if r["ticker"] == ticker], key=lambda x: x["date"], reverse=True) for r in recs: c1, c2, c3, c4 = st.columns([2, 2, 2, 1]) c1.write(r["date"]); c2.write(f"{r['shares']:,}"); c3.write(f"${r['price']:.2f}") if c4.button("🗑️", key=f"del_{r['id']}"): db["buy_records"] = [x for x in db["buy_records"] if x["id"] != r["id"]] save_data(db); st.rerun() @st.dialog("🛒 賣出股票") def sell_stock(ticker, name): is_foreign = not ticker[0].isdigit() tot_s = sum(r["shares"] for r in db["buy_records"] if r["ticker"] == ticker) sd, ss = st.date_input("賣出日期"), st.number_input("股數", min_value=1, max_value=tot_s, step=1) sp = st.number_input("單價 (原幣別)", value=float(db["market_data"].get(ticker, {"price": 0.0})["price"])) if st.button("確認賣出", type="primary", use_container_width=True): rem = ss total_net_cash_native = 0 for r in sorted([x for x in db["buy_records"] if x["ticker"] == ticker], key=lambda x: x["date"]): if rem <= 0: break take = min(r["shares"], rem) if is_foreign: sell_rev = take * sp sell_fee = float(db.get("us_stock_fee", 0.0)) sell_tax = 0.0 else: disc = db.get("fee_discount", 6.0) / 10.0 sell_rev = take * sp sell_fee = sell_rev * 0.001425 * disc tax_rate = 0.001 if ticker.startswith("00") else 0.003 sell_tax = sell_rev * tax_rate batch_net_cash = sell_rev - sell_fee - sell_tax total_net_cash_native += batch_net_cash db["realized_records"].append({"sell_date": str(sd), "ticker": ticker, "shares": take, "buy_price": r["price"], "sell_price": sp}) r["shares"] -= take; rem -= take db["buy_records"] = [x for x in db["buy_records"] if x["shares"] > 0] if is_foreign: db["usd_balance"] = float(db.get("usd_balance", 0.0)) + total_net_cash_native st.session_state["success_msg"] = f"✅ 賣出成功!
淨額 ${total_net_cash_native:,.2f} USD (已扣手續費)
已自動加入「美元帳戶餘額」!" else: db["account_balance"] = float(db.get("account_balance", 0.0)) + total_net_cash_native st.session_state["success_msg"] = f"✅ 賣出成功!
淨額 ${total_net_cash_native:,.0f} TWD
已自動加入「台幣帳戶餘額」!" save_data(db) st.rerun() @st.dialog("✏️ 編輯 / 刪除已實現紀錄") def edit_realized(idx): r = db["realized_records"][idx] try: sd_val = datetime.datetime.strptime(r["sell_date"], "%Y-%m-%d").date() except: sd_val = datetime.date.today() new_sd = st.date_input("賣出日期", value=sd_val) new_shares = st.number_input("股數", value=int(r["shares"]), min_value=1, step=1) new_bp = st.number_input("均進單價 (原幣別)", value=float(r["buy_price"]), min_value=0.01) new_sp = st.number_input("賣出單價 (原幣別)", value=float(r["sell_price"]), min_value=0.01) st.markdown("
", unsafe_allow_html=True) c1, c2 = st.columns(2) if c1.button("💾 儲存修改", type="primary", use_container_width=True): db["realized_records"][idx].update({"sell_date": str(new_sd), "shares": new_shares, "buy_price": new_bp, "sell_price": new_sp}) save_data(db); st.rerun() if c2.button("🗑️ 刪除此紀錄", use_container_width=True): db["realized_records"].pop(idx); save_data(db); st.rerun() # ========================================== # ⚡ 開啟網頁 / 重新整理「自動同步股價」機制 # ========================================== if "auto_updated" not in st.session_state: tickers_to_update = {r["ticker"] for r in db.get("buy_records", [])} if tickers_to_update: with st.spinner("🔄 正在為您同步最新股價..."): updated_any = False for t in tickers_to_update: p, n = fetch_price(t) if p > 0: if "market_data" not in db: db["market_data"] = {} if t not in db["market_data"]: db["market_data"][t] = {"price": p, "name": n} updated_any = True elif db["market_data"][t].get("price") != p: db["market_data"][t]["price"] = p if n != t: db["market_data"][t]["name"] = n updated_any = True if updated_any: save_data(db) st.session_state["auto_updated"] = True # --- 核心計算 --- agg = {} for r in db["buy_records"]: t = r["ticker"] if t not in agg: agg[t] = {"shares": 0, "cost": 0} agg[t]["shares"] += r["shares"]; agg[t]["cost"] += r["shares"] * r["price"] tot_exp, tot_mv, stock_unrealized, display_stocks = 0, 0, 0, [] dom_mv, for_mv_twd = 0.0, 0.0 for t, d in agg.items(): shares = d["shares"] info = db["market_data"].get(t, {"price": 0.0, "name": t}) curr_p, name = info["price"], info["name"] is_foreign = not t[0].isdigit() mv_native = shares * curr_p mv_twd = mv_native * usd_twd_rate if is_foreign else mv_native if is_foreign: for_mv_twd += mv_twd else: dom_mv += mv_twd tot_mv += mv_twd tot_exp += (mv_twd * 2 if t.endswith("L") else mv_twd) avg_cost_native = d["cost"] / shares cost_native = calc_cost_profit(t, shares, avg_cost_native, is_foreign=is_foreign) if is_foreign: sell_cost_native = float(db.get("us_stock_fee", 0.0)) else: tax_rate = 0.001 if t.startswith("00") else 0.003 sell_cost_native = (mv_native * 0.001425 * (db["fee_discount"]/10)) + (mv_native * tax_rate) un_p_native = mv_native - sell_cost_native - cost_native un_p_twd = un_p_native * usd_twd_rate if is_foreign else un_p_native stock_unrealized += un_p_twd display_stocks.append({"ticker": t, "name": name, "shares": shares, "avg_cost": avg_cost_native, "curr_p": curr_p, "mv_twd": mv_twd, "un_p_twd": un_p_twd, "ret": (un_p_native/cost_native)*100 if cost_native>0 else 0, "is_foreign": is_foreign}) stock_realized = 0.0 for r in db["realized_records"]: is_f = not r["ticker"][0].isdigit() profit_native = calc_cost_profit(r["ticker"], r["shares"], r["buy_price"], r["sell_price"], is_f) stock_realized += (profit_native * usd_twd_rate if is_f else profit_native) usd_balance_twd = float(db.get("usd_balance", 0.0)) * usd_twd_rate twd_bal = float(db.get("account_balance", 0.0)) other_ast = float(db.get("other_assets", 0.0)) futures_equity = float(db.get("futures_capital", 0.0)) pledge_amt = float(db.get("pledge_amount", 0.0)) credit_amt = float(db.get("credit_loan", 0.0)) mortgage_amt = float(db.get("mortgage_amount", 0.0)) total_assets = twd_bal + usd_balance_twd + tot_mv + other_ast + futures_equity - pledge_amt - credit_amt - mortgage_amt total_profit = stock_unrealized + stock_realized lev_base = twd_bal + usd_balance_twd + tot_mv + futures_equity - pledge_amt - credit_amt lev_pct = (tot_exp / lev_base) * 100 if lev_base > 0 else 0.0 lev_str = f"{lev_pct:.1f}%" # --- 🚀 歷史紀錄自動存檔 --- tz_tw = timezone(timedelta(hours=8)) now_tw = datetime.datetime.now(tz_tw) if now_tw.hour >= 15: t_str = now_tw.strftime('%Y-%m-%d') if db["history"].get(t_str, {}).get("assets") != total_assets: db["history"][t_str] = {"profit": total_profit, "assets": total_assets} save_data(db) help_total_assets = f"""➕ 正資產 (Assets) • 台幣帳戶餘額: ${twd_bal:,.0f} • 美元帳戶餘額: ${usd_balance_twd:,.0f} • 國內股票市值: ${dom_mv:,.0f} • 國外股票市值: ${for_mv_twd:,.0f} • 期貨權益數: ${futures_equity:,.0f} • 其他資產: ${other_ast:,.0f} ➖ 負債 (Liabilities) • 質押金額: ${pledge_amt:,.0f} • 信貸金額: ${credit_amt:,.0f} • 房貸金額: ${mortgage_amt:,.0f}""" help_tot_exp = "所有持股市值總和\n(若持有尾碼為 L 的正2槓桿ETF,市值將自動 × 2 計算真實曝險)" help_dom_mv = "國內台股部位即時現值總和" help_for_mv = f"國外美股部位現值 × 即時匯率 ({usd_twd_rate})" help_lev = "總曝險 ÷ 流動淨資產\n(排除房地產等其他資產與房貸,專注於可動用資金與股市部位)" # ========================================== # 🛑 攔截顯示系統提示 # ========================================== if "success_msg" in st.session_state: show_success_dialog() # --- 🚀 UI 介面 --- st.markdown(f"#### 🗓️ {now_tw.strftime('%Y/%m/%d')}") m1, m2 = st.columns(2) m1.metric("總淨資產", f"${total_assets:,.0f}", help=help_total_assets) m2.metric("總獲利", f"${total_profit:,.0f}") st.divider() c_a, c_set, c_up, c_out = st.columns(4) with c_a: if st.button("➕", help="新增股票", use_container_width=True): add_stock() with c_set: if st.button("⚙️", help="設定", use_container_width=True): show_settings() with c_up: if st.button("🔄", help="強制更新報價", use_container_width=True): if "auto_updated" in st.session_state: del st.session_state["auto_updated"] st.rerun() with c_out: # 💡 這裡改成呼叫防呆確認視窗 if st.button("🚪", help="登出", use_container_width=True): confirm_logout() t1, t2, t3, t4, t5 = st.tabs(["💼庫存", "💰已實現", "📈獲利", "📊資產", "⚖️資金"]) with t1: if display_stocks: df_p = pd.DataFrame(display_stocks) colors_list = px.colors.qualitative.Plotly + px.colors.qualitative.Set1 + px.colors.qualitative.Pastel unique_tickers = df_p['ticker'].unique() # 💡 就在這行!補上 `ticker in` 修復語法錯誤 color_map = {ticker: colors_list[i % len(colors_list)] for i, ticker in enumerate(unique_tickers)} c_pie, c_list = st.columns(2) with c_pie: fig = px.pie(df_p, values='mv_twd', names='ticker', hole=0.6, color='ticker', color_discrete_map=color_map) fig.update_layout(height=200, showlegend=False, margin=dict(t=0, b=0, l=0, r=0)) fig.add_annotation(text=f"TWD
{tot_mv:,.0f}", showarrow=False, font_size=13) st.plotly_chart(fig, use_container_width=True) with c_list: st.markdown("
", unsafe_allow_html=True) st.markdown("
🏆 前五大持股
", unsafe_allow_html=True) top5 = df_p.nlargest(5, 'mv_twd') for _, row in top5.iterrows(): pct = (row['mv_twd'] / tot_mv) * 100 name_short = str(row['name'])[:4] c_code = color_map.get(row['ticker'], '#888') dot_html = f"" st.markdown(f"
" f"{dot_html}{row['ticker']}  {name_short}" f"{pct:.1f}%
", unsafe_allow_html=True) st.markdown("
", unsafe_allow_html=True) for s in display_stocks: cur_sym = "USD" if s["is_foreign"] else "TWD" with st.expander(f"【{s['ticker']}】{s['name']} | {cur_sym} ${s['curr_p']:,.2f}"): c1, c2, c3 = st.columns(3) c1.metric("即時庫存", f"{s['shares']:,}") c2.metric("現值(TWD)", f"${s['mv_twd']:,.0f}") c3.metric(f"均價({cur_sym})", f"${s['avg_cost']:.2f}") c4, c5, c6 = st.columns(3) c4.metric(f"現價({cur_sym})", f"${s['curr_p']:.2f}") c5.metric("損益(TWD)", f"${s['un_p_twd']:,.0f}") c6.metric("獲利率", f"{s['ret']:.2f}%") b1, b2 = st.columns(2) with b1: if st.button("🔍明細", key=f"d_{s['ticker']}", use_container_width=True): show_details(s['ticker'], s['name']) with b2: if st.button("🛒賣出", key=f"s_{s['ticker']}", use_container_width=True): sell_stock(s['ticker'], s['name']) else: st.info("無現貨庫存") with t2: if db.get("realized_records"): records_with_idx = [(i, r) for i, r in enumerate(db["realized_records"])] for idx, r in sorted(records_with_idx, key=lambda x: x[1]["sell_date"], reverse=True): ticker = r["ticker"] shares = r["shares"] bp = r["buy_price"] sp = r["sell_price"] is_f = not ticker[0].isdigit() cur = "USD" if is_f else "TWD" disc = db.get("fee_discount", 6.0) / 10.0 buy_cost = shares * bp if is_f: buy_fee = float(db.get("us_stock_fee", 0.0)) sell_fee = float(db.get("us_stock_fee", 0.0)) sell_tax = 0.0 else: buy_fee = buy_cost * 0.001425 * disc sell_rev_tmp = shares * sp sell_fee = sell_rev_tmp * 0.001425 * disc tax_rate = 0.001 if ticker.startswith("00") else 0.003 sell_tax = sell_rev_tmp * tax_rate sell_rev = shares * sp total_cost = buy_cost + buy_fee net_profit_native = round(sell_rev - sell_fee - sell_tax - total_cost) net_profit_twd = net_profit_native * usd_twd_rate if is_f else net_profit_native roi = (net_profit_native / total_cost) * 100 if total_cost > 0 else 0 with st.expander(f"{r['sell_date']} | {ticker} | 淨利(TWD): ${net_profit_twd:,.0f}"): st.markdown(f"**交易:** {shares:,}股 | **均進:** ${bp:.2f} | **均出:** ${sp:.2f} ({cur})") c1, c2, c3 = st.columns(3) c1.metric("總成本", f"${round(total_cost):,}") c2.metric("手續費", f"${round(buy_fee + sell_fee):,}") c3.metric("交易稅", f"${round(sell_tax):,}") c4, c5, c6 = st.columns(3) c4.metric("賣出總額", f"${round(sell_rev):,}") c5.metric(f"淨損益({cur})", f"${net_profit_native:,}") c6.metric("報酬率", f"{roi:.2f}%") if st.button("✏️ 編輯 / 刪除此紀錄", key=f"edit_real_{idx}", use_container_width=True): edit_realized(idx) else: st.info("無賣出紀錄") with t3: if db["history"]: st.line_chart(pd.DataFrame([{"日期": k, "獲利": v["profit"]} for k, v in db["history"].items()]).set_index("日期")) with t4: if db["history"]: st.line_chart(pd.DataFrame([{"日期": k, "總資產": v["assets"]} for k, v in db["history"].items()]).set_index("日期")) with t5: st.markdown("#### 🛡️ 風險與資產指標") st.metric("總曝險", f"${tot_exp:,.0f}", help=help_tot_exp) st.metric("國內股票市值", f"${dom_mv:,.0f}", help=help_dom_mv) st.metric("國外股票市值", f"${for_mv_twd:,.0f}", help=help_for_mv) st.metric("持股水位", lev_str, help=help_lev) st.divider() st.markdown("#### ⚖️ 資金手動調整") c1, c2 = st.columns(2) nb_twd = c1.number_input("台幣帳戶餘額 (TWD)", value=int(float(db.get("account_balance", 0)))) db_usd = float(db.get("usd_balance", 0.0)) val_usd = db_usd if db_usd != 0 else None nb_usd = c2.number_input("美元帳戶餘額", value=val_usd, placeholder="幣別為美元", step=100.0) nfc = c1.number_input("期貨權益數 (TWD)", value=int(float(db.get("futures_capital", 0)))) np = c2.number_input("質押金額 (TWD)", value=int(float(db.get("pledge_amount", 0)))) ncl = c1.number_input("信貸金額 (TWD)", value=int(float(db.get("credit_loan", 0)))) nma = c2.number_input("房貸金額 (TWD)", value=int(float(db.get("mortgage_amount", 0)))) db_other = float(db.get("other_assets", 0.0)) val_other = int(db_other) if db_other != 0 else None no = st.number_input("其他資產 (TWD)", value=val_other, placeholder="如房地產、黃金、外幣等") if st.button("💾 確認更新資料庫", type="primary", use_container_width=True): db["account_balance"] = float(nb_twd) db["usd_balance"] = float(nb_usd) if nb_usd is not None else 0.0 db["futures_capital"] = float(nfc) db["pledge_amount"] = float(np) db["credit_loan"] = float(ncl) db["mortgage_amount"] = float(nma) db["other_assets"] = float(no) if no is not None else 0.0 save_data(db); st.success("已更新!"); time.sleep(1); st.rerun()