Spaces:
Sleeping
Sleeping
Download app.py from Serena2026/qlib-quant-platform: direct link, hf CLI and curl.
- Browser
- Download file 36.8 kB
-
https://huggingface.co/spaces/Serena2026/qlib-quant-platform/resolve/main/app.py
- Command line
-
hf download hf://spaces/Serena2026/qlib-quant-platform/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Serena2026/qlib-quant-platform/resolve/main/app.py
36.8 kB
| """ | |
| Qlib 量化投资平台 - Web 应用 | |
| 数据来源:Yahoo Finance(实时,覆盖 2010 年至今) | |
| """ | |
| import warnings | |
| warnings.filterwarnings('ignore') | |
| import json | |
| import logging | |
| from datetime import datetime, timedelta | |
| import numpy as np | |
| import pandas as pd | |
| import yfinance as yf | |
| from flask import Flask, jsonify, render_template_string, request | |
| logging.basicConfig(level=logging.INFO) | |
| logger = logging.getLogger(__name__) | |
| app = Flask(__name__) | |
| # ───────────────────────────────────────────── | |
| # 股票列表 | |
| # ───────────────────────────────────────────── | |
| US_STOCK_LIST = [ | |
| {"code": "AAPL", "name": "苹果"}, | |
| {"code": "MSFT", "name": "微软"}, | |
| {"code": "NVDA", "name": "英伟达"}, | |
| {"code": "GOOGL", "name": "谷歌"}, | |
| {"code": "AMZN", "name": "亚马逊"}, | |
| {"code": "META", "name": "Meta"}, | |
| {"code": "TSLA", "name": "特斯拉"}, | |
| {"code": "BRK-B", "name": "伯克希尔"}, | |
| {"code": "JPM", "name": "摩根大通"}, | |
| {"code": "V", "name": "Visa"}, | |
| {"code": "WMT", "name": "沃尔玛"}, | |
| {"code": "XOM", "name": "埃克森美孚"}, | |
| {"code": "BABA", "name": "阿里巴巴"}, | |
| {"code": "PDD", "name": "拼多多"}, | |
| {"code": "JD", "name": "京东"}, | |
| {"code": "BIDU", "name": "百度"}, | |
| {"code": "NIO", "name": "蔚来"}, | |
| {"code": "XPEV", "name": "小鹏"}, | |
| {"code": "LI", "name": "理想"}, | |
| {"code": "SPY", "name": "标普500ETF"}, | |
| {"code": "QQQ", "name": "纳斯达克ETF"}, | |
| {"code": "GLD", "name": "黄金ETF"}, | |
| {"code": "AMD", "name": "AMD"}, | |
| {"code": "INTC", "name": "英特尔"}, | |
| {"code": "NFLX", "name": "奈飞"}, | |
| {"code": "DIS", "name": "迪士尼"}, | |
| {"code": "BA", "name": "波音"}, | |
| {"code": "KO", "name": "可口可乐"}, | |
| {"code": "MCD", "name": "麦当劳"}, | |
| {"code": "COIN", "name": "Coinbase"}, | |
| ] | |
| STOCK_LIST = [ | |
| {"code": "SH600519", "name": "贵州茅台"}, | |
| {"code": "SH600036", "name": "招商银行"}, | |
| {"code": "SH601318", "name": "中国平安"}, | |
| {"code": "SH600276", "name": "恒瑞医药"}, | |
| {"code": "SH600000", "name": "浦发银行"}, | |
| {"code": "SH601166", "name": "兴业银行"}, | |
| {"code": "SH600887", "name": "伊利股份"}, | |
| {"code": "SH601012", "name": "隆基绿能"}, | |
| {"code": "SH600030", "name": "中信证券"}, | |
| {"code": "SH600900", "name": "长江电力"}, | |
| {"code": "SZ000001", "name": "平安银行"}, | |
| {"code": "SZ000858", "name": "五粮液"}, | |
| {"code": "SZ000333", "name": "美的集团"}, | |
| {"code": "SZ300750", "name": "宁德时代"}, | |
| {"code": "SZ002415", "name": "海康威视"}, | |
| {"code": "SZ000002", "name": "万科A"}, | |
| {"code": "SZ000651", "name": "格力电器"}, | |
| {"code": "SZ002594", "name": "比亚迪"}, | |
| {"code": "SZ000568", "name": "泸州老窖"}, | |
| {"code": "SZ000725", "name": "京东方A"}, | |
| ] | |
| def is_us_stock(code: str) -> bool: | |
| """判断是否为美股代码(不含 SH/SZ 前缀)""" | |
| return not (code.startswith("SH") or code.startswith("SZ")) | |
| def to_yahoo_code(qlib_code: str) -> str: | |
| """将 Qlib 格式股票代码转为 Yahoo Finance 格式""" | |
| if qlib_code.startswith("SH"): | |
| return qlib_code[2:] + ".SS" | |
| elif qlib_code.startswith("SZ"): | |
| return qlib_code[2:] + ".SZ" | |
| # 美股直接使用原始代码 | |
| return qlib_code | |
| def fetch_stock_data(stock_code: str, start_date: str, end_date: str) -> pd.DataFrame: | |
| """从 Yahoo Finance 获取股票数据""" | |
| yahoo_code = to_yahoo_code(stock_code) | |
| try: | |
| df = yf.download( | |
| yahoo_code, | |
| start=start_date, | |
| end=end_date, | |
| auto_adjust=True, | |
| progress=False, | |
| timeout=30 | |
| ) | |
| if df.empty: | |
| return pd.DataFrame() | |
| # 展平多级列名 | |
| if isinstance(df.columns, pd.MultiIndex): | |
| df.columns = [col[0].lower() for col in df.columns] | |
| else: | |
| df.columns = [col.lower() for col in df.columns] | |
| df.index = pd.to_datetime(df.index).tz_localize(None) | |
| df = df.dropna(subset=['close']) | |
| return df | |
| except Exception as e: | |
| logger.error(f"获取 {stock_code} 数据失败: {e}") | |
| return pd.DataFrame() | |
| def compute_indicators(df: pd.DataFrame) -> dict: | |
| """计算技术指标""" | |
| close = df['close'] | |
| volume = df.get('volume', pd.Series(dtype=float)) | |
| # MA | |
| ma5 = close.rolling(5).mean() | |
| ma10 = close.rolling(10).mean() | |
| ma20 = close.rolling(20).mean() | |
| ma60 = close.rolling(60).mean() | |
| # RSI | |
| delta = close.diff() | |
| gain = delta.clip(lower=0).rolling(14).mean() | |
| loss = (-delta.clip(upper=0)).rolling(14).mean() | |
| rs = gain / loss.replace(0, np.nan) | |
| rsi = 100 - (100 / (1 + rs)) | |
| # MACD | |
| ema12 = close.ewm(span=12, adjust=False).mean() | |
| ema26 = close.ewm(span=26, adjust=False).mean() | |
| macd = ema12 - ema26 | |
| signal = macd.ewm(span=9, adjust=False).mean() | |
| hist = macd - signal | |
| def safe_list(s): | |
| return [round(v, 4) if pd.notna(v) else None for v in s] | |
| dates = [d.strftime('%Y-%m-%d') for d in df.index] | |
| return { | |
| "dates": dates, | |
| "close": safe_list(close), | |
| "open": safe_list(df.get('open', pd.Series(dtype=float))), | |
| "high": safe_list(df.get('high', pd.Series(dtype=float))), | |
| "low": safe_list(df.get('low', pd.Series(dtype=float))), | |
| "volume": safe_list(volume), | |
| "ma5": safe_list(ma5), | |
| "ma10": safe_list(ma10), | |
| "ma20": safe_list(ma20), | |
| "ma60": safe_list(ma60), | |
| "rsi": safe_list(rsi), | |
| "macd": safe_list(macd), | |
| "macd_signal": safe_list(signal), | |
| "macd_hist": safe_list(hist), | |
| } | |
| def run_backtest(df: pd.DataFrame, fast: int, slow: int, capital: float) -> dict: | |
| """运行双均线策略回测""" | |
| if df.empty or len(df) < slow + 10: | |
| return {"error": "数据不足,无法回测"} | |
| close = df['close'].values | |
| dates = [d.strftime('%Y-%m-%d') for d in df.index] | |
| ma_fast = pd.Series(close).rolling(fast).mean().values | |
| ma_slow = pd.Series(close).rolling(slow).mean().values | |
| cash = capital | |
| shares = 0.0 | |
| equity_curve = [] | |
| trades = [] | |
| position = False | |
| for i in range(len(close)): | |
| if np.isnan(ma_fast[i]) or np.isnan(ma_slow[i]): | |
| equity_curve.append(round(cash, 2)) | |
| continue | |
| # 金叉买入 | |
| if not position and i > 0 and ma_fast[i] > ma_slow[i] and ma_fast[i-1] <= ma_slow[i-1]: | |
| shares = cash / close[i] | |
| cash = 0.0 | |
| position = True | |
| trades.append({"date": dates[i], "action": "买入", "price": round(float(close[i]), 2), | |
| "shares": round(shares, 2)}) | |
| # 死叉卖出 | |
| elif position and i > 0 and ma_fast[i] < ma_slow[i] and ma_fast[i-1] >= ma_slow[i-1]: | |
| cash = shares * close[i] | |
| shares = 0.0 | |
| position = False | |
| trades.append({"date": dates[i], "action": "卖出", "price": round(float(close[i]), 2), | |
| "amount": round(cash, 2)}) | |
| total = cash + shares * close[i] | |
| equity_curve.append(round(total, 2)) | |
| # 最终平仓 | |
| final_value = cash + shares * close[-1] | |
| # 买入持有 | |
| bh_return = (close[-1] - close[0]) / close[0] * 100 | |
| # 最大回撤 | |
| eq = pd.Series(equity_curve) | |
| rolling_max = eq.cummax() | |
| drawdown = (eq - rolling_max) / rolling_max * 100 | |
| max_drawdown = drawdown.min() | |
| strategy_return = (final_value - capital) / capital * 100 | |
| return { | |
| "dates": dates, | |
| "equity_curve": equity_curve, | |
| "buy_hold_curve": [round(capital * float(close[i]) / float(close[0]), 2) for i in range(len(close))], | |
| "strategy_return": round(strategy_return, 2), | |
| "buy_hold_return": round(bh_return, 2), | |
| "max_drawdown": round(float(max_drawdown), 2), | |
| "trade_count": len(trades), | |
| "final_value": round(final_value, 2), | |
| "initial_capital": capital, | |
| "trades": trades[-20:], | |
| "start_price": round(float(close[0]), 2), | |
| "end_price": round(float(close[-1]), 2), | |
| } | |
| # ───────────────────────────────────────────── | |
| # API 路由 | |
| # ───────────────────────────────────────────── | |
| def api_stocks(): | |
| return jsonify({"stocks": STOCK_LIST}) | |
| def api_us_stocks(): | |
| return jsonify({"stocks": US_STOCK_LIST}) | |
| def api_stock_data(): | |
| code = request.args.get('stock_code', 'SH600519') | |
| start = request.args.get('start_date', '2020-01-01') | |
| end = request.args.get('end_date', datetime.today().strftime('%Y-%m-%d')) | |
| df = fetch_stock_data(code, start, end) | |
| if df.empty: | |
| return jsonify({"error": f"无法获取 {code} 的数据,请检查股票代码或网络连接"}) | |
| result = compute_indicators(df) | |
| result["stock_code"] = code | |
| all_stocks = STOCK_LIST + US_STOCK_LIST | |
| result["stock_name"] = next((s["name"] for s in all_stocks if s["code"] == code), code) | |
| result["market"] = "US" if is_us_stock(code) else "CN" | |
| return jsonify(result) | |
| def api_backtest(): | |
| data = request.get_json() or {} | |
| code = data.get('stock_code', 'SH600519') | |
| start = data.get('start_date', '2015-01-01') | |
| end = data.get('end_date', datetime.today().strftime('%Y-%m-%d')) | |
| fast = int(data.get('fast_ma', 5)) | |
| slow = int(data.get('slow_ma', 20)) | |
| capital = float(data.get('capital', 100000)) | |
| df = fetch_stock_data(code, start, end) | |
| if df.empty: | |
| return jsonify({"error": f"无法获取 {code} 的数据"}) | |
| result = run_backtest(df, fast, slow, capital) | |
| result["stock_code"] = code | |
| all_stocks = STOCK_LIST + US_STOCK_LIST | |
| result["stock_name"] = next((s["name"] for s in all_stocks if s["code"] == code), code) | |
| return jsonify(result) | |
| def api_portfolio(): | |
| data = request.get_json() or {} | |
| codes = data.get('stocks', ['SH600519', 'SH600036']) | |
| start = data.get('start_date', '2020-01-01') | |
| end = data.get('end_date', datetime.today().strftime('%Y-%m-%d')) | |
| results = {} | |
| for code in codes[:5]: | |
| df = fetch_stock_data(code, start, end) | |
| if df.empty: | |
| continue | |
| close = df['close'] | |
| all_stocks = STOCK_LIST + US_STOCK_LIST | |
| name = next((s["name"] for s in all_stocks if s["code"] == code), code) | |
| norm = (close / close.iloc[0] * 100).round(2).tolist() | |
| dates = [d.strftime('%Y-%m-%d') for d in df.index] | |
| total_ret = (close.iloc[-1] - close.iloc[0]) / close.iloc[0] * 100 | |
| days = (df.index[-1] - df.index[0]).days | |
| ann_ret = ((1 + total_ret / 100) ** (365 / max(days, 1)) - 1) * 100 | |
| ann_vol = close.pct_change().std() * np.sqrt(252) * 100 | |
| sharpe = ann_ret / ann_vol if ann_vol > 0 else 0 | |
| results[code] = { | |
| "name": name, | |
| "dates": dates, | |
| "normalized": norm, | |
| "total_return": round(float(total_ret), 2), | |
| "annual_return": round(float(ann_ret), 2), | |
| "annual_vol": round(float(ann_vol), 2), | |
| "sharpe": round(float(sharpe), 2), | |
| } | |
| return jsonify(results) | |
| # ───────────────────────────────────────────── | |
| # 前端页面 | |
| # ───────────────────────────────────────────── | |
| HTML_TEMPLATE = """<!DOCTYPE html> | |
| <html lang="zh-CN"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>Qlib 量化投资平台</title> | |
| <script src="https://cdn.jsdelivr.net/npm/chart.js@4.4.0/dist/chart.umd.min.js"></script> | |
| <style> | |
| * { box-sizing: border-box; margin: 0; padding: 0; } | |
| body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif; | |
| background: #0d1117; color: #e6edf3; min-height: 100vh; } | |
| nav { background: #161b22; border-bottom: 1px solid #30363d; padding: 0 24px; | |
| display: flex; align-items: center; gap: 8px; height: 56px; position: sticky; top: 0; z-index: 100; } | |
| nav .logo { font-size: 18px; font-weight: 700; color: #58a6ff; margin-right: 16px; } | |
| nav button { background: none; border: none; color: #8b949e; padding: 8px 16px; | |
| border-radius: 6px; cursor: pointer; font-size: 14px; transition: all .2s; } | |
| nav button:hover, nav button.active { background: #21262d; color: #e6edf3; } | |
| nav .data-range { margin-left: auto; font-size: 12px; color: #8b949e; } | |
| .page { display: none; padding: 24px; max-width: 1200px; margin: 0 auto; } | |
| .page.active { display: block; } | |
| .hero { text-align: center; padding: 60px 20px; } | |
| .hero h1 { font-size: 48px; font-weight: 800; background: linear-gradient(135deg, #58a6ff, #bc8cff); | |
| -webkit-background-clip: text; -webkit-text-fill-color: transparent; margin-bottom: 16px; } | |
| .hero p { font-size: 18px; color: #8b949e; margin-bottom: 40px; } | |
| .cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(280px, 1fr)); gap: 20px; } | |
| .card { background: #161b22; border: 1px solid #30363d; border-radius: 12px; padding: 28px; | |
| cursor: pointer; transition: all .2s; } | |
| .card:hover { border-color: #58a6ff; transform: translateY(-2px); box-shadow: 0 8px 24px rgba(88,166,255,.15); } | |
| .card-icon { font-size: 36px; margin-bottom: 16px; } | |
| .card h3 { font-size: 18px; margin-bottom: 8px; color: #e6edf3; } | |
| .card p { font-size: 14px; color: #8b949e; line-height: 1.6; } | |
| .panel { background: #161b22; border: 1px solid #30363d; border-radius: 12px; padding: 20px; margin-bottom: 20px; } | |
| .panel h3 { font-size: 16px; font-weight: 600; margin-bottom: 16px; color: #58a6ff; } | |
| .form-row { display: flex; flex-wrap: wrap; gap: 12px; align-items: flex-end; } | |
| .form-group { display: flex; flex-direction: column; gap: 6px; } | |
| .form-group label { font-size: 12px; color: #8b949e; } | |
| .form-group input, .form-group select { background: #0d1117; border: 1px solid #30363d; | |
| border-radius: 6px; color: #e6edf3; padding: 8px 12px; font-size: 14px; outline: none; } | |
| .form-group input:focus, .form-group select:focus { border-color: #58a6ff; } | |
| .btn { background: #238636; border: none; border-radius: 6px; color: #fff; | |
| padding: 9px 20px; font-size: 14px; cursor: pointer; transition: background .2s; } | |
| .btn:hover { background: #2ea043; } | |
| .btn-blue { background: #1f6feb; } | |
| .btn-blue:hover { background: #388bfd; } | |
| .stock-tags { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; } | |
| .stock-tag { background: #21262d; border: 1px solid #30363d; border-radius: 20px; | |
| padding: 4px 12px; font-size: 12px; cursor: pointer; transition: all .2s; } | |
| .stock-tag:hover, .stock-tag.selected { background: #1f6feb; border-color: #1f6feb; color: #fff; } | |
| .chart-wrap { position: relative; height: 300px; } | |
| .chart-wrap-sm { position: relative; height: 180px; } | |
| .metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin: 16px 0; } | |
| .metric { background: #0d1117; border: 1px solid #30363d; border-radius: 8px; padding: 16px; text-align: center; } | |
| .metric .val { font-size: 24px; font-weight: 700; margin-bottom: 4px; } | |
| .metric .lbl { font-size: 12px; color: #8b949e; } | |
| .green { color: #3fb950; } | |
| .red { color: #f85149; } | |
| .blue { color: #58a6ff; } | |
| .trades-table { width: 100%; border-collapse: collapse; font-size: 13px; } | |
| .trades-table th { background: #21262d; padding: 10px 12px; text-align: left; color: #8b949e; } | |
| .trades-table td { padding: 8px 12px; border-bottom: 1px solid #21262d; } | |
| .loading { text-align: center; padding: 40px; color: #8b949e; } | |
| .error-msg { background: #3d1f1f; border: 1px solid #f85149; border-radius: 8px; | |
| padding: 12px 16px; color: #f85149; font-size: 14px; margin: 12px 0; } | |
| .portfolio-stocks { display: flex; flex-wrap: wrap; gap: 8px; margin-bottom: 12px; } | |
| .portfolio-stock { background: #21262d; border: 1px solid #30363d; border-radius: 20px; | |
| padding: 4px 12px; font-size: 12px; cursor: pointer; transition: all .2s; } | |
| .portfolio-stock.selected { background: #1f6feb; border-color: #1f6feb; color: #fff; } | |
| .portfolio-metrics { display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); gap: 12px; } | |
| .portfolio-item { background: #0d1117; border: 1px solid #30363d; border-radius: 8px; padding: 16px; } | |
| .portfolio-item h4 { font-size: 14px; margin-bottom: 12px; color: #e6edf3; } | |
| .portfolio-item .stat { display: flex; justify-content: space-between; margin-bottom: 6px; font-size: 13px; } | |
| .portfolio-item .stat .k { color: #8b949e; } | |
| </style> | |
| </head> | |
| <body> | |
| <nav> | |
| <span class="logo">📊 Qlib 量化平台</span> | |
| <button class="active" onclick="showPage('home', this)">首页</button> | |
| <button onclick="showPage('market', this)">行情分析</button> | |
| <button onclick="showPage('backtest', this)">策略回测</button> | |
| <button onclick="showPage('portfolio', this)">投资组合</button> | |
| <span class="data-range">A股 + 美股 | Yahoo Finance 实时数据</span> | |
| </nav> | |
| <!-- 首页 --> | |
| <div id="home" class="page active"> | |
| <div class="hero"> | |
| <h1>Qlib 量化投资平台</h1> | |
| <p>基于 Microsoft Qlib 框架 · Yahoo Finance 实时数据 · 覆盖 A股 + 美股 2010 年至今</p> | |
| <div class="cards"> | |
| <div class="card" onclick="showPage('market', document.querySelectorAll('nav button')[1])"> | |
| <div class="card-icon">📈</div> | |
| <h3>行情分析</h3> | |
| <p>K线图、均线、MACD、RSI 等技术指标,支持 A股 + 美股,数据实时更新</p> | |
| </div> | |
| <div class="card" onclick="showPage('backtest', document.querySelectorAll('nav button')[2])"> | |
| <div class="card-icon">🔄</div> | |
| <h3>策略回测</h3> | |
| <p>双均线策略回测,资金曲线、最大回撤、夏普比率全面评估</p> | |
| </div> | |
| <div class="card" onclick="showPage('portfolio', document.querySelectorAll('nav button')[3])"> | |
| <div class="card-icon">💼</div> | |
| <h3>投资组合</h3> | |
| <p>多股票归一化收益对比,风险收益指标综合分析</p> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- 行情分析 --> | |
| <div id="market" class="page"> | |
| <div class="panel"> | |
| <h3>📈 行情分析</h3> | |
| <div style="display:flex;gap:8px;margin-bottom:8px"> | |
| <button class="btn btn-blue" style="padding:4px 12px;font-size:12px" onclick="switchMarket('cn','market-tags','m-code')">🇨🇳 A股</button> | |
| <button class="btn" style="padding:4px 12px;font-size:12px;background:#6e40c9" onclick="switchMarket('us','market-tags','m-code')">🇺🇸 美股</button> | |
| </div> | |
| <div class="stock-tags" id="market-tags"></div> | |
| <div class="form-row"> | |
| <div class="form-group"> | |
| <label>股票代码</label> | |
| <input id="m-code" value="SH600519" placeholder="如 SH600519" style="width:130px"> | |
| </div> | |
| <div class="form-group"> | |
| <label>开始日期</label> | |
| <input id="m-start" type="date" value="2023-01-01"> | |
| </div> | |
| <div class="form-group"> | |
| <label>结束日期</label> | |
| <input id="m-end" type="date"> | |
| </div> | |
| <button class="btn btn-blue" onclick="loadMarket()">查询数据</button> | |
| </div> | |
| </div> | |
| <div id="market-result"></div> | |
| </div> | |
| <!-- 策略回测 --> | |
| <div id="backtest" class="page"> | |
| <div class="panel"> | |
| <h3>🔄 均线策略回测</h3> | |
| <div style="display:flex;gap:8px;margin-bottom:8px"> | |
| <button class="btn btn-blue" style="padding:4px 12px;font-size:12px" onclick="switchMarket('cn','bt-tags','bt-code')">🇨🇳 A股</button> | |
| <button class="btn" style="padding:4px 12px;font-size:12px;background:#6e40c9" onclick="switchMarket('us','bt-tags','bt-code')">🇺🇸 美股</button> | |
| </div> | |
| <div class="stock-tags" id="bt-tags"></div> | |
| <div class="form-row"> | |
| <div class="form-group"> | |
| <label>股票代码</label> | |
| <input id="bt-code" value="SH600519" style="width:130px"> | |
| </div> | |
| <div class="form-group"> | |
| <label>开始日期</label> | |
| <input id="bt-start" type="date" value="2018-01-01"> | |
| </div> | |
| <div class="form-group"> | |
| <label>结束日期</label> | |
| <input id="bt-end" type="date"> | |
| </div> | |
| <div class="form-group"> | |
| <label>快速均线</label> | |
| <input id="bt-fast" type="number" value="5" min="2" max="60" style="width:80px"> | |
| </div> | |
| <div class="form-group"> | |
| <label>慢速均线</label> | |
| <input id="bt-slow" type="number" value="20" min="5" max="200" style="width:80px"> | |
| </div> | |
| <div class="form-group"> | |
| <label>初始资金(元)</label> | |
| <input id="bt-capital" type="number" value="100000" style="width:120px"> | |
| </div> | |
| <button class="btn" onclick="loadBacktest()">开始回测</button> | |
| </div> | |
| </div> | |
| <div id="bt-result"></div> | |
| </div> | |
| <!-- 投资组合 --> | |
| <div id="portfolio" class="page"> | |
| <div class="panel"> | |
| <h3>💼 投资组合分析</h3> | |
| <p style="font-size:13px;color:#8b949e;margin-bottom:8px">选择 2-5 只股票进行对比分析</p> | |
| <div style="display:flex;gap:8px;margin-bottom:8px"> | |
| <button class="btn btn-blue" style="padding:4px 12px;font-size:12px" onclick="switchPfMarket('cn')">🇨🇳 A股</button> | |
| <button class="btn" style="padding:4px 12px;font-size:12px;background:#6e40c9" onclick="switchPfMarket('us')">🇺🇸 美股</button> | |
| </div> | |
| <div class="portfolio-stocks" id="pf-stocks"></div> | |
| <div class="form-row"> | |
| <div class="form-group"> | |
| <label>开始日期</label> | |
| <input id="pf-start" type="date" value="2022-01-01"> | |
| </div> | |
| <div class="form-group"> | |
| <label>结束日期</label> | |
| <input id="pf-end" type="date"> | |
| </div> | |
| <button class="btn btn-blue" onclick="loadPortfolio()">分析投资组合</button> | |
| </div> | |
| </div> | |
| <div id="pf-result"></div> | |
| </div> | |
| <script> | |
| const STOCKS = {{ stocks | tojson }}; | |
| const US_STOCKS = {{ us_stocks | tojson }}; | |
| let currentTagMarket = {"market-tags": "cn", "bt-tags": "cn", "pf-stocks": "cn"}; | |
| const TODAY = new Date().toISOString().split('T')[0]; | |
| // 初始化日期 | |
| document.querySelectorAll('input[type=date]').forEach(el => { | |
| if (!el.value || el.id.includes('end')) el.value = TODAY; | |
| }); | |
| // 切换市场 | |
| function switchMarket(market, containerId, inputId) { | |
| currentTagMarket[containerId] = market; | |
| const c = document.getElementById(containerId); | |
| c.innerHTML = ''; | |
| const stockList = market === 'us' ? US_STOCKS : STOCKS; | |
| const selected = new Set(); | |
| stockList.slice(0, 15).forEach(s => { | |
| const tag = document.createElement('span'); | |
| tag.className = 'stock-tag'; | |
| tag.textContent = s.name; | |
| tag.onclick = () => { | |
| c.querySelectorAll('.stock-tag').forEach(t => t.classList.remove('selected')); | |
| tag.classList.add('selected'); | |
| document.getElementById(inputId).value = s.code; | |
| }; | |
| c.appendChild(tag); | |
| }); | |
| } | |
| // 初始化股票标签 | |
| function initTags(containerId, inputId, multi) { | |
| const c = document.getElementById(containerId); | |
| const selected = new Set(); | |
| STOCKS.slice(0, 12).forEach(s => { | |
| const tag = document.createElement('span'); | |
| tag.className = multi ? 'portfolio-stock' : 'stock-tag'; | |
| tag.textContent = s.name; | |
| tag.onclick = () => { | |
| if (multi) { | |
| if (selected.has(s.code)) { selected.delete(s.code); tag.classList.remove('selected'); } | |
| else if (selected.size < 5) { selected.add(s.code); tag.classList.add('selected'); } | |
| } else { | |
| c.querySelectorAll('.stock-tag').forEach(t => t.classList.remove('selected')); | |
| tag.classList.add('selected'); | |
| document.getElementById(inputId).value = s.code; | |
| } | |
| }; | |
| c.appendChild(tag); | |
| }); | |
| if (multi) c._getSelected = () => [...selected]; | |
| } | |
| initTags('market-tags', 'm-code', false); | |
| initTags('bt-tags', 'bt-code', false); | |
| initTags('pf-stocks', null, true); | |
| // 投资组合市场切换 | |
| function switchPfMarket(market) { | |
| const c = document.getElementById('pf-stocks'); | |
| c.innerHTML = ''; | |
| const stockList = market === 'us' ? US_STOCKS : STOCKS; | |
| const selected = new Set(); | |
| stockList.slice(0, 15).forEach(s => { | |
| const tag = document.createElement('span'); | |
| tag.className = 'portfolio-stock'; | |
| tag.textContent = s.name; | |
| tag.onclick = () => { | |
| if (selected.has(s.code)) { selected.delete(s.code); tag.classList.remove('selected'); } | |
| else if (selected.size < 5) { selected.add(s.code); tag.classList.add('selected'); } | |
| }; | |
| c.appendChild(tag); | |
| }); | |
| c._getSelected = () => [...selected]; | |
| } | |
| function showPage(id, btn) { | |
| document.querySelectorAll('.page').forEach(p => p.classList.remove('active')); | |
| document.querySelectorAll('nav button').forEach(b => b.classList.remove('active')); | |
| document.getElementById(id).classList.add('active'); | |
| if (btn) btn.classList.add('active'); | |
| } | |
| function showLoading(id) { | |
| document.getElementById(id).innerHTML = '<div class="loading">⏳ 正在从 Yahoo Finance 获取最新数据,请稍候(约 5-10 秒)...</div>'; | |
| } | |
| function showError(id, msg) { | |
| document.getElementById(id).innerHTML = '<div class="error-msg">❌ ' + msg + '</div>'; | |
| } | |
| // ── 行情分析 ── | |
| async function loadMarket() { | |
| const code = document.getElementById('m-code').value.trim().toUpperCase(); | |
| const start = document.getElementById('m-start').value; | |
| const end = document.getElementById('m-end').value; | |
| showLoading('market-result'); | |
| try { | |
| const r = await fetch('/api/stock_data?stock_code=' + code + '&start_date=' + start + '&end_date=' + end); | |
| const d = await r.json(); | |
| if (d.error) { showError('market-result', d.error); return; } | |
| renderMarket(d); | |
| } catch(e) { showError('market-result', '网络请求失败: ' + e.message); } | |
| } | |
| function renderMarket(d) { | |
| const el = document.getElementById('market-result'); | |
| const validClose = d.close.filter(v => v !== null); | |
| const latestClose = validClose[validClose.length - 1]; | |
| const firstClose = validClose[0]; | |
| const chg = ((latestClose - firstClose) / firstClose * 100).toFixed(2); | |
| const clsColor = chg >= 0 ? 'green' : 'red'; | |
| el.innerHTML = | |
| '<div class="panel">' + | |
| '<div style="display:flex;justify-content:space-between;align-items:center;margin-bottom:16px">' + | |
| '<h3 style="color:#e6edf3">' + d.stock_name + ' (' + d.stock_code + ')</h3>' + | |
| '<div>' + | |
| '<span style="font-size:24px;font-weight:700;color:#e6edf3">¥' + latestClose.toFixed(2) + '</span>' + | |
| '<span class="' + clsColor + '" style="margin-left:12px;font-size:16px">' + (chg >= 0 ? '+' : '') + chg + '%</span>' + | |
| '</div>' + | |
| '</div>' + | |
| '<div class="chart-wrap"><canvas id="price-chart"></canvas></div>' + | |
| '</div>' + | |
| '<div style="display:grid;grid-template-columns:1fr 1fr;gap:20px">' + | |
| '<div class="panel"><h3>RSI (14)</h3><div class="chart-wrap-sm"><canvas id="rsi-chart"></canvas></div></div>' + | |
| '<div class="panel"><h3>MACD</h3><div class="chart-wrap-sm"><canvas id="macd-chart"></canvas></div></div>' + | |
| '</div>'; | |
| new Chart(document.getElementById('price-chart'), { | |
| type: 'line', | |
| data: { labels: d.dates, datasets: [ | |
| { label: '收盘价', data: d.close, borderColor: '#e6edf3', borderWidth: 1.5, pointRadius: 0, tension: 0.1 }, | |
| { label: 'MA5', data: d.ma5, borderColor: '#58a6ff', borderWidth: 1, pointRadius: 0, tension: 0.1 }, | |
| { label: 'MA20', data: d.ma20, borderColor: '#f0883e', borderWidth: 1, pointRadius: 0, tension: 0.1 }, | |
| { label: 'MA60', data: d.ma60, borderColor: '#bc8cff', borderWidth: 1, pointRadius: 0, tension: 0.1 }, | |
| ]}, | |
| options: { responsive: true, maintainAspectRatio: false, | |
| plugins: { legend: { labels: { color: '#8b949e', boxWidth: 20 } } }, | |
| scales: { x: { ticks: { color: '#8b949e', maxTicksLimit: 8 }, grid: { color: '#21262d' } }, | |
| y: { ticks: { color: '#8b949e' }, grid: { color: '#21262d' } } } } | |
| }); | |
| new Chart(document.getElementById('rsi-chart'), { | |
| type: 'line', | |
| data: { labels: d.dates, datasets: [ | |
| { label: 'RSI', data: d.rsi, borderColor: '#bc8cff', borderWidth: 1.5, pointRadius: 0, fill: false } | |
| ]}, | |
| options: { responsive: true, maintainAspectRatio: false, | |
| plugins: { legend: { display: false } }, | |
| scales: { x: { ticks: { color: '#8b949e', maxTicksLimit: 6 }, grid: { color: '#21262d' } }, | |
| y: { min: 0, max: 100, ticks: { color: '#8b949e' }, grid: { color: '#21262d' } } } } | |
| }); | |
| new Chart(document.getElementById('macd-chart'), { | |
| type: 'bar', | |
| data: { labels: d.dates, datasets: [ | |
| { label: 'MACD柱', data: d.macd_hist, backgroundColor: d.macd_hist.map(v => v >= 0 ? 'rgba(63,185,80,.6)' : 'rgba(248,81,73,.6)') }, | |
| { label: 'MACD', data: d.macd, type: 'line', borderColor: '#58a6ff', borderWidth: 1, pointRadius: 0 }, | |
| { label: 'Signal', data: d.macd_signal, type: 'line', borderColor: '#f0883e', borderWidth: 1, pointRadius: 0 }, | |
| ]}, | |
| options: { responsive: true, maintainAspectRatio: false, | |
| plugins: { legend: { display: false } }, | |
| scales: { x: { ticks: { color: '#8b949e', maxTicksLimit: 6 }, grid: { color: '#21262d' } }, | |
| y: { ticks: { color: '#8b949e' }, grid: { color: '#21262d' } } } } | |
| }); | |
| } | |
| // ── 策略回测 ── | |
| async function loadBacktest() { | |
| const payload = { | |
| stock_code: document.getElementById('bt-code').value.trim().toUpperCase(), | |
| start_date: document.getElementById('bt-start').value, | |
| end_date: document.getElementById('bt-end').value, | |
| fast_ma: parseInt(document.getElementById('bt-fast').value), | |
| slow_ma: parseInt(document.getElementById('bt-slow').value), | |
| capital: parseFloat(document.getElementById('bt-capital').value), | |
| }; | |
| showLoading('bt-result'); | |
| try { | |
| const r = await fetch('/api/backtest', { | |
| method: 'POST', | |
| headers: {'Content-Type': 'application/json'}, | |
| body: JSON.stringify(payload) | |
| }); | |
| const d = await r.json(); | |
| if (d.error) { showError('bt-result', d.error); return; } | |
| renderBacktest(d, payload); | |
| } catch(e) { showError('bt-result', '请求失败: ' + e.message); } | |
| } | |
| function renderBacktest(d, p) { | |
| const el = document.getElementById('bt-result'); | |
| const retColor = d.strategy_return >= 0 ? 'green' : 'red'; | |
| const bhColor = d.buy_hold_return >= 0 ? 'green' : 'red'; | |
| const tradesRows = d.trades.map(t => | |
| '<tr><td>' + t.date + '</td>' + | |
| '<td style="color:' + (t.action === '买入' ? '#3fb950' : '#f85149') + '">' + t.action + '</td>' + | |
| '<td>¥' + t.price + '</td>' + | |
| '<td>' + (t.action === '买入' ? t.shares + '股' : '¥' + (t.amount || 0).toLocaleString()) + '</td></tr>' | |
| ).join(''); | |
| el.innerHTML = | |
| '<div class="panel">' + | |
| '<h3>' + d.stock_name + ' — MA' + p.fast_ma + '/MA' + p.slow_ma + ' 均线策略回测</h3>' + | |
| '<div class="metrics">' + | |
| '<div class="metric"><div class="val ' + retColor + '">' + (d.strategy_return >= 0 ? '+' : '') + d.strategy_return + '%</div><div class="lbl">策略总收益</div></div>' + | |
| '<div class="metric"><div class="val ' + bhColor + '">' + (d.buy_hold_return >= 0 ? '+' : '') + d.buy_hold_return + '%</div><div class="lbl">买入持有收益</div></div>' + | |
| '<div class="metric"><div class="val red">' + d.max_drawdown + '%</div><div class="lbl">最大回撤</div></div>' + | |
| '<div class="metric"><div class="val blue">' + d.trade_count + '</div><div class="lbl">总交易次数</div></div>' + | |
| '<div class="metric"><div class="val">¥' + d.final_value.toLocaleString() + '</div><div class="lbl">最终资金</div></div>' + | |
| '<div class="metric"><div class="val">¥' + d.start_price + ' → ¥' + d.end_price + '</div><div class="lbl">股价变化</div></div>' + | |
| '</div>' + | |
| '<div class="chart-wrap"><canvas id="bt-chart"></canvas></div>' + | |
| '</div>' + | |
| '<div class="panel">' + | |
| '<h3>交易记录(最近20笔)</h3>' + | |
| '<table class="trades-table"><thead><tr><th>日期</th><th>操作</th><th>价格</th><th>数量/金额</th></tr></thead>' + | |
| '<tbody>' + tradesRows + '</tbody></table>' + | |
| '</div>'; | |
| new Chart(document.getElementById('bt-chart'), { | |
| type: 'line', | |
| data: { labels: d.dates, datasets: [ | |
| { label: '策略资金曲线', data: d.equity_curve, borderColor: '#58a6ff', borderWidth: 2, pointRadius: 0, fill: false }, | |
| { label: '买入持有', data: d.buy_hold_curve, borderColor: '#3fb950', borderWidth: 1.5, pointRadius: 0, borderDash: [4,4], fill: false }, | |
| ]}, | |
| options: { responsive: true, maintainAspectRatio: false, | |
| plugins: { legend: { labels: { color: '#8b949e' } } }, | |
| scales: { x: { ticks: { color: '#8b949e', maxTicksLimit: 8 }, grid: { color: '#21262d' } }, | |
| y: { ticks: { color: '#8b949e', callback: v => '¥' + v.toLocaleString() }, grid: { color: '#21262d' } } } } | |
| }); | |
| } | |
| // ── 投资组合 ── | |
| async function loadPortfolio() { | |
| const stocks = document.getElementById('pf-stocks')._getSelected(); | |
| if (stocks.length < 2) { showError('pf-result', '请至少选择 2 只股票'); return; } | |
| const payload = { | |
| stocks: stocks, | |
| start_date: document.getElementById('pf-start').value, | |
| end_date: document.getElementById('pf-end').value, | |
| }; | |
| showLoading('pf-result'); | |
| try { | |
| const r = await fetch('/api/portfolio', { | |
| method: 'POST', | |
| headers: {'Content-Type': 'application/json'}, | |
| body: JSON.stringify(payload) | |
| }); | |
| const d = await r.json(); | |
| if (Object.keys(d).length === 0) { showError('pf-result', '无法获取数据'); return; } | |
| renderPortfolio(d); | |
| } catch(e) { showError('pf-result', '请求失败: ' + e.message); } | |
| } | |
| function renderPortfolio(d) { | |
| const el = document.getElementById('pf-result'); | |
| const colors = ['#58a6ff', '#3fb950', '#f0883e', '#bc8cff', '#ffa657']; | |
| const entries = Object.entries(d); | |
| const metricsHtml = entries.map(([code, s], i) => | |
| '<div class="portfolio-item">' + | |
| '<h4 style="color:' + colors[i] + '">' + s.name + ' (' + code + ')</h4>' + | |
| '<div class="stat"><span class="k">总收益率</span><span class="' + (s.total_return >= 0 ? 'green' : 'red') + '">' + (s.total_return >= 0 ? '+' : '') + s.total_return + '%</span></div>' + | |
| '<div class="stat"><span class="k">年化收益</span><span class="' + (s.annual_return >= 0 ? 'green' : 'red') + '">' + (s.annual_return >= 0 ? '+' : '') + s.annual_return + '%</span></div>' + | |
| '<div class="stat"><span class="k">年化波动</span><span>' + s.annual_vol + '%</span></div>' + | |
| '<div class="stat"><span class="k">夏普比率</span><span class="' + (s.sharpe >= 1 ? 'green' : s.sharpe >= 0 ? 'blue' : 'red') + '">' + s.sharpe + '</span></div>' + | |
| '</div>' | |
| ).join(''); | |
| el.innerHTML = | |
| '<div class="panel">' + | |
| '<h3>归一化收益对比(基准=100)</h3>' + | |
| '<div class="chart-wrap"><canvas id="pf-chart"></canvas></div>' + | |
| '</div>' + | |
| '<div class="panel">' + | |
| '<h3>各股票绩效指标</h3>' + | |
| '<div class="portfolio-metrics">' + metricsHtml + '</div>' + | |
| '</div>'; | |
| new Chart(document.getElementById('pf-chart'), { | |
| type: 'line', | |
| data: { | |
| labels: entries[0][1].dates, | |
| datasets: entries.map(([code, s], i) => ({ | |
| label: s.name, | |
| data: s.normalized, | |
| borderColor: colors[i], | |
| borderWidth: 2, | |
| pointRadius: 0, | |
| fill: false, | |
| tension: 0.1, | |
| })) | |
| }, | |
| options: { responsive: true, maintainAspectRatio: false, | |
| plugins: { legend: { labels: { color: '#8b949e' } } }, | |
| scales: { x: { ticks: { color: '#8b949e', maxTicksLimit: 8 }, grid: { color: '#21262d' } }, | |
| y: { ticks: { color: '#8b949e' }, grid: { color: '#21262d' } } } } | |
| }); | |
| } | |
| </script> | |
| </body> | |
| </html>""" | |
| def index(): | |
| return render_template_string(HTML_TEMPLATE, stocks=STOCK_LIST, us_stocks=US_STOCK_LIST) | |
| if __name__ == '__main__': | |
| app.run(host='0.0.0.0', port=7860, debug=False) | |