diff --git a/Dockerfile b/Dockerfile index 2b267c91e28009458766205a4ff560540a0811fe..f033dfec108370db80b6a0b3d53c26cec8ac9932 100644 --- a/Dockerfile +++ b/Dockerfile @@ -4,7 +4,7 @@ FROM python:3.12-slim # Set environment variables ENV PYTHONUNBUFFERED=1 \ PYTHONDONTWRITEBYTECODE=1 \ - PORT=8080 \ + PORT=7860 \ DATABASE_URL=sqlite+aiosqlite:////app/inferroute.db \ MOCK_OPENAI=true \ MOCK_GEMINI=true \ @@ -29,9 +29,10 @@ RUN pip install --no-cache-dir -r requirements.txt COPY inferroute/ ./inferroute/ COPY docs/ ./docs/ COPY benchmarks/ ./benchmarks/ +COPY external/ ./external/ -# Expose default port -EXPOSE 8080 +# Expose default port (7860 for Hugging Face Spaces) +EXPOSE 7860 # Command to run uvicorn dynamically binding to PORT environment variable (for Render/Hugging Face compatibility) -CMD ["sh", "-c", "python -m uvicorn inferroute.main:app --host 0.0.0.0 --port ${PORT:-8080}"] +CMD ["sh", "-c", "python -m uvicorn inferroute.main:app --host 0.0.0.0 --port ${PORT:-7860}"] diff --git a/external/Quant.ai/.gitignore b/external/Quant.ai/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..6a62034cffc7f941c705b88f368e46c4fc5ae1f7 --- /dev/null +++ b/external/Quant.ai/.gitignore @@ -0,0 +1,31 @@ +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# OS Files +.DS_Store +Thumbs.db + +# Virtual Environments +venv/ +.venv/ +env/ +.env + +# PDF and documentation binaries (exclude reading packages) +*.pdf + +# IDE and model temp directories +.gemini/ +.idea/ +.vscode/ +node_modules/ +dist/ +build/ + +# Local cache and databases +backend/data_cache/ +backend/app/experiments.db +*.db + diff --git a/external/Quant.ai/README.md b/external/Quant.ai/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1bebd813689db35e7cbbee2da635f1fd975831ad --- /dev/null +++ b/external/Quant.ai/README.md @@ -0,0 +1,132 @@ +# Quant.ai - Advanced Quant Trading Engine & Backtest Simulator + +

+ Python Version + FastAPI + React + Vite + License +

+ +Quant.ai is a production-ready, fully-automated stock trading engine and interactive backtest simulator. Built with a Python FastAPI backend and a React (Vite) frontend, it features real-time K-line pattern recognition, dynamic market regime routing, ATR-based risk sizing, and out-of-sample walk-forward optimization. + +

+ Quant.ai Desktop Trading Terminal +

+ +--- + +## 🚀 Key Features + +### 1. 📊 Advanced K-Line Feature & Pattern Recognition +- **12 K-Line Numerical Features**: Computes body ratio, upper/lower shadow ratios, gaps, relative volume (RVOL), and trend context dynamically. +- **22 Quantifiable Candlestick Patterns**: Vectorized detection for patterns like Hammer, Shooting Star, Bullish/Bearish Engulfing, Piercing, Dark Cloud Cover, Morning/Evening Star, Three White Soldiers, Rising/Falling Three Methods, Gap Breakout, Exhaustion Gaps, and Neckline breakouts for W-Bottoms and M-Tops. + +### 2. 🚦 Dynamic Market Regime Router +- Dynamically classifies the market into four regimes: + - `trend_up`: Strong bullish trend. Activates trend-following strategies (Donchian breakout, EMA crossover). + - `trend_down`: Bearish trend. Suspends buy operations and goes into defense. + - `high_volatility`: Extreme volatility (ATR/Close in top 10%). Enforces cash preservation. + - `range_bound`: Oscillating market. Activates mean reversion (Bollinger Bands oversold) and candlestick reversals. + +### 3. 🛡️ Institutional-Grade Multi-Layer Risk Control +- **ATR-Based Sizing**: Calculates trade size based on account equity, ATR stop-distance, and risk percentage. +- **Soft Drawdown Limit (7%) & Consecutive Losses (5)**: Triggers a 50% reduction in position size. +- **Hard Drawdown Limit (12%)**: Temporarily locks the trading engine (risk multiplier goes to 0) to prevent capital blowups. + +### 4. 🔄 Walk-Forward Parameter Optimization +- Features a rolling optimization pipeline (`walk_forward.py`) that divides history into training and test intervals. +- Optimizes parameters (strategy mode, ATR multiplier, RSI) by maximizing the drawdown-penalized net profit (Calmar-like metric) and validates performance out-of-sample. + +### 5. 🌅 Market Open Focus & Opening Range Breakout (ORB) Strategy +- **Market Open Focus Mode**: Targets the high-volatility market opening (09:30 - 10:15 EST). Restricts buying to this high-momentum window and performs a force liquidation at 10:30 EST to protect capital from the midday choppy sideways trend. +- **Opening Range Breakout (ORB)**: Precomputes the opening high and low from the first 5 minutes of regular hours (09:30 - 09:35 EST) and triggers high-probability breakout buys on high volume (RVOL > 1.2), using the opening range low as a hard failure stop-loss. + +### 6. 🤖 AI Auto-Pilot Parameter Tuning (智能托管) +- Dynamically grid-searches strategy settings over the recent 5 days of 1-minute bar data for the selected ticker. +- Optimizes for the best risk-adjusted performance (Sharpe ratio and max drawdown mitigation) and automatically applies parameters to the active trading dashboard. + +### 7. 🎬 Historical Replay Mode (历史开盘复盘模拟器) +- **Granular 1m Simulation**: Allows developers and traders to replay the market open sequence step-by-step for any trading day within the last 5 days. +- **Interactive Controls**: Supports Play, Pause, Single-Step tick progression, Reset, and speed tuning (with simulated intervals down to 50ms per bar). +- **Synchronized Portfolio updates**: Portfolio equity, cash, holdings, and transactions update dynamically on each step to observe execution points. + +### 8. 🔍 Intraday Trade Inspector (日内成交精细化透视) +- **High-Frequency Audit**: In daily backtests, clicking any ledger row fetches the 1-minute candlestick data for the execution date and overlays the exact BUY/SELL orders at the market open (9:30 AM EST). +- **Auto-scroll focus**: In intraday/1m backtests, clicking any ledger row centers the main chart's time axis precisely on the selected transaction bar. + +--- + +## 📁 Project Structure + +```text +├── backend/ +│ ├── app/ +│ │ ├── config.py # Trade and risk configurations +│ │ ├── data_manager.py # YFinance data loading, technical indicators, and regimes +│ │ ├── patterns.py # 22 K-line patterns and W-Bottom/M-Top detection +│ │ ├── strategy.py # Strategy routing and evaluation +│ │ ├── simulator.py # Universal backtesting simulator +│ │ └── trading_engine.py # Portfolio ledger, execution, and risk gates +│ ├── main.py # CLI Backtest interface +│ ├── main_api.py # FastAPI REST Server +│ └── walk_forward.py # Walk-Forward rolling optimization engine +├── frontend/ # React Vite dashboard with TradingView charts +└── README.md +``` + +--- + +## 🛠️ Installation & Getting Started + +### Prerequisites +- Python 3.8+ +- Node.js 16+ + +### 1. Backend Setup +Navigate to the root directory and install dependencies: +```bash +pip install pandas numpy yfinance fastapi uvicorn pydantic +``` + +Run a CLI backtest simulation: +```bash +# Run minute-level day trading simulation for TSLA +python backend/main.py --ticker TSLA --period 5d --interval 1m + +# Run daily-level swing trading simulation for TSLA +python backend/main.py --ticker TSLA --period 1y --interval 1d +``` + +Run Walk-Forward rolling parameter optimization: +```bash +python backend/walk_forward.py --ticker TSLA --period 1y --interval 1d +``` + +Start the FastAPI API server: +```bash +python backend/main_api.py +``` + +### 2. Frontend Setup +Navigate to the frontend folder, install dependencies, and start the development server: +```bash +cd frontend +npm install +npm run dev +``` + +--- + +## 📊 Backtest Indicators & Performance +Our universal backtest simulator calculates standard trading metrics including: +- **Net PnL & Return Percentage** +- **Max Account Equity Drawdown** +- **Win Rate & Round Trip Trade Count** +- **Transaction Commission and Slippage Friction Cost** +- **Market Regime Distributions** + +--- + +## 📝 License & Disclaimer +This software is provided for educational and research purposes only. Algorithmic trading carries substantial risk, and past performance is not indicative of future results. diff --git a/external/Quant.ai/assets/desktop_terminal.png b/external/Quant.ai/assets/desktop_terminal.png new file mode 100644 index 0000000000000000000000000000000000000000..3ef3b7057a7e5d17c79cfe596931c7b36ac23a0d --- /dev/null +++ b/external/Quant.ai/assets/desktop_terminal.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:635fb9475df21edb58e19d00255cf1f13b41e31e46a5735c0a5812066456c5db +size 411219 diff --git a/external/Quant.ai/backend/app/__init__.py b/external/Quant.ai/backend/app/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..02d81f23cc52a731f9d2bda0a004501084ed431e --- /dev/null +++ b/external/Quant.ai/backend/app/__init__.py @@ -0,0 +1,2 @@ +# backend/app/__init__.py +# Initialize app package diff --git a/external/Quant.ai/backend/app/agent.py b/external/Quant.ai/backend/app/agent.py new file mode 100644 index 0000000000000000000000000000000000000000..279f1cc655f2f25bd12a2d6d0340b4e8228a4882 --- /dev/null +++ b/external/Quant.ai/backend/app/agent.py @@ -0,0 +1,423 @@ +# backend/app/agent.py +""" +AI Agent Core Module — Natural Language → Strategy Config +Supports OpenAI-compatible APIs and Gemini API. Falls back to template-based parsing when no API key is available. +""" + +import json +import os +import re +from app.llm_client import chat_completion, get_usage_stats + +# Default strategy config template +DEFAULT_STRATEGY_CONFIG = { + "ticker": "TSLA", + "interval": "1d", + "strategy_mode": "dynamic", + "stop_loss_pct": 0.015, + "profit_target_pct": 0.030, + "trailing_stop_mode": "atr", + "trailing_stop_atr_mult": 2.0, + "rsi_threshold_buy": 65.0, + "risk_per_trade_pct": 0.01, + "max_position_size_pct": 0.50, + "position_sizing_mode": "atr", + "commission_per_share": 0.005, + "slippage_rate": 0.0003 +} + +# Mapping of common natural language terms → strategy parameters +TICKER_ALIASES = { + "tesla": "TSLA", "tsla": "TSLA", + "nvidia": "NVDA", "nvda": "NVDA", + "apple": "AAPL", "aapl": "AAPL", + "microsoft": "MSFT", "msft": "MSFT", + "amd": "AMD", + "google": "GOOGL", "googl": "GOOGL", "alphabet": "GOOGL", + "amazon": "AMZN", "amzn": "AMZN", + "meta": "META", "facebook": "META", + "spy": "SPY", "qqq": "QQQ", +} + +STRATEGY_ALIASES = { + "donchian": "dynamic", "breakout": "breakout", "突破": "breakout", + "ema": "ema_cross", "均线": "ema_cross", "金叉": "ema_cross", + "pattern": "patterns", "形态": "patterns", "k线": "patterns", + "consensus": "consensus", "共振": "consensus", + "dynamic": "dynamic", "动态": "dynamic", "自适应": "dynamic", + "mean reversion": "dynamic", "均值回归": "dynamic", + "trend": "dynamic", "趋势": "dynamic", +} + +INTERVAL_ALIASES = { + "1分钟": "1m", "1min": "1m", "1minute": "1m", "1m": "1m", + "5分钟": "5m", "5min": "5m", "5minute": "5m", "5m": "5m", + "15分钟": "15m", "15min": "15m", "15m": "15m", + "30分钟": "30m", "30min": "30m", "30m": "30m", + "1小时": "1h", "1hour": "1h", "1h": "1h", "hourly": "1h", + "日线": "1d", "daily": "1d", "1d": "1d", "1day": "1d", + "day": "1d", "天": "1d", +} + +# Available backend tools (for LLM function calling) +BACKEND_TOOLS = [ + { + "name": "fetch_market_data", + "description": "Fetch historical OHLCV market data for a given ticker and time range", + "parameters": {"ticker": "str", "period": "str", "interval": "str"} + }, + { + "name": "compute_indicators", + "description": "Compute technical indicators (EMA, RSI, ATR, MACD, ADX, Bollinger Bands, etc.) on market data", + "parameters": {"ticker": "str", "interval": "str"} + }, + { + "name": "run_backtest", + "description": "Run a backtest simulation with given strategy and risk parameters", + "parameters": {"strategy_config": "dict"} + }, + { + "name": "generate_risk_report", + "description": "Generate AI risk analysis report from backtest results", + "parameters": {"backtest_id": "str"} + } +] + +EXAMPLE_PROMPTS = [ + "Backtest TSLA with Donchian breakout strategy over the past year using daily bars", + "Test NVDA with EMA crossover strategy on 5-minute bars, use 1.5x ATR trailing stop", + "Run a mean reversion backtest on SPY with RSI oversold at 10 and Bollinger Bands", + "Compare dynamic routing vs consensus strategy on AAPL daily data", + "用日线级别回测 MSFT 的动态路由策略,ATR 止损倍数设为 2.5" +] + +SYSTEM_PROMPT = """You are the AI Strategy Parser engine for Quant.ai. +Your task is to analyze the user's trading strategy description in natural language and extract a precise, valid strategy configuration in JSON format. + +You must output a JSON object containing the following keys (you can leave out keys to use defaults, but you must ensure any provided keys have valid types and ranges): +- ticker (string, uppercase, e.g., "TSLA") +- interval (string, e.g., "1m", "5m", "15m", "30m", "1h", "1d") +- strategy_mode (string, choice of: "dynamic", "ema_cross", "breakout", "patterns", "consensus") +- stop_loss_pct (float, range 0.001 to 0.20, e.g., 0.015) +- profit_target_pct (float, range 0.001 to 0.50, e.g., 0.030) +- trailing_stop_mode (string, choice of: "atr", "fixed", "none") +- trailing_stop_atr_mult (float, range 0.5 to 5.0, e.g., 2.0) +- rsi_threshold_buy (float, range 10.0 to 90.0, e.g., 65.0) +- risk_per_trade_pct (float, range 0.001 to 0.10, e.g., 0.01) +- max_position_size_pct (float, range 0.05 to 1.00, e.g., 0.50) +- position_sizing_mode (string, choice of: "atr", "fixed") +- commission_per_share (float, range 0.0 to 0.10, e.g., 0.005) +- slippage_rate (float, range 0.0 to 0.01, e.g., 0.0003) + +If the user wants a SMA or EMA cross strategy, set strategy_mode to "ema_cross". +If the user wants candle patterns, breakout, consensus, etc., set strategy_mode to "patterns", "breakout", "consensus" or "dynamic". +If the user's description is vague, merge your extractions with the default config: +{default_config} + +CRITICAL: Return ONLY a valid JSON block enclosed in ```json ... ``` code blocks. Do not add conversational text around it when generating strategy_config. +""" + +CHAT_SYSTEM_PROMPT = """You are Quant.ai's Quantitative Research Assistant. +You help users design, refine, and backtest quantitative trading strategies. +When the user describes a trading strategy or asks questions: +1. Provide a professional, helpful, and natural language explanation/response. +2. If the user's message contains a trading strategy or a change to an existing strategy, you MUST ALSO generate a JSON strategy configuration block inside ```json ... ```. + The JSON config must match the following format and merge with the current config: + {default_config} + +Valid fields: +- ticker (string, uppercase) +- interval ("1m", "5m", "15m", "30m", "1h", "1d") +- strategy_mode ("dynamic", "ema_cross", "breakout", "patterns", "consensus") +- stop_loss_pct (float, 0.001-0.20) +- profit_target_pct (float, 0.001-0.50) +- trailing_stop_mode ("atr", "fixed", "none") +- trailing_stop_atr_mult (float, 0.5-5.0) +- rsi_threshold_buy (float, 10-90) +- risk_per_trade_pct (float, 0.001-0.10) +- max_position_size_pct (float, 0.05-1.00) +- position_sizing_mode ("atr", "fixed") +- commission_per_share (float) +- slippage_rate (float) + +Response format: +Write your professional suggestions or chat response, followed by the ```json ... ``` block containing the extracted strategy_config (only if a strategy description is present). +""" + +def parse_research_prompt(prompt: str, use_llm: bool = True) -> dict: + """ + Parse a natural language research prompt into a strategy_config JSON. + First tries LLM parsing if use_llm is True and keys exist, otherwise falls back to template. + """ + if use_llm: + openai_key = os.environ.get("OPENAI_API_KEY") + gemini_key = os.environ.get("GEMINI_API_KEY") + if openai_key or gemini_key: + res = parse_with_llm(prompt) + if res: + return res + + # Fallback template parsing + prompt_lower = prompt.lower().strip() + config = DEFAULT_STRATEGY_CONFIG.copy() + parsed_parts = [] + + # 1. Extract ticker + ticker_found = False + for alias, ticker in TICKER_ALIASES.items(): + if alias in prompt_lower: + config["ticker"] = ticker + parsed_parts.append(f"Ticker: {ticker}") + ticker_found = True + break + + if not ticker_found: + ticker_match = re.findall(r'\b([A-Z]{1,5})\b', prompt) + if ticker_match: + config["ticker"] = ticker_match[0] + parsed_parts.append(f"Ticker: {ticker_match[0]}") + + # 2. Extract strategy mode + for alias, mode in STRATEGY_ALIASES.items(): + if alias in prompt_lower: + config["strategy_mode"] = mode + parsed_parts.append(f"Strategy: {mode}") + break + + # 3. Extract interval + for alias, interval in INTERVAL_ALIASES.items(): + if alias in prompt_lower: + config["interval"] = interval + parsed_parts.append(f"Interval: {interval}") + break + + # 4. Extract ATR multiplier + atr_match = re.search(r'atr.*?(\d+\.?\d*)', prompt_lower) + if atr_match: + atr_val = float(atr_match.group(1)) + if 0.5 <= atr_val <= 5.0: + config["trailing_stop_atr_mult"] = atr_val + parsed_parts.append(f"ATR Multiplier: {atr_val}") + + # 5. Extract RSI threshold + rsi_match = re.search(r'rsi.*?(\d+)', prompt_lower) + if rsi_match: + rsi_val = float(rsi_match.group(1)) + if 5 <= rsi_val <= 90: + config["rsi_threshold_buy"] = rsi_val + parsed_parts.append(f"RSI Threshold: {rsi_val}") + + # 6. Extract risk percentage + risk_match = re.search(r'risk.*?(\d+\.?\d*)%', prompt_lower) + if risk_match: + risk_val = float(risk_match.group(1)) / 100 + if 0.001 <= risk_val <= 0.05: + config["risk_per_trade_pct"] = risk_val + parsed_parts.append(f"Risk Per Trade: {risk_val*100}%") + + execution_plan = [ + {"step": 1, "tool": "fetch_market_data", "desc": f"Fetch {config['interval']} OHLCV data for {config['ticker']}"}, + {"step": 2, "tool": "compute_indicators", "desc": "Calculate technical indicators (EMA, RSI, ATR, MACD, ADX, Bollinger Bands, Donchian)"}, + {"step": 3, "tool": "run_backtest", "desc": f"Run {config['strategy_mode']} strategy backtest with ATR={config['trailing_stop_atr_mult']}x trailing stop"}, + {"step": 4, "tool": "generate_risk_report", "desc": "Analyze results: drawdown, regime performance, parameter sensitivity, overfitting risk"} + ] + + parsed_intent = f"Backtest {config['ticker']} using {config['strategy_mode']} strategy on {config['interval']} bars" + if parsed_parts: + parsed_intent += f" (Parsed: {', '.join(parsed_parts)})" + + return { + "strategy_config": config, + "execution_plan": execution_plan, + "parsed_intent": parsed_intent, + "source": "template", + "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "cost_usd": 0.0} + } + + +def parse_with_llm(prompt: str, history: list = None) -> dict: + """ + Call LLM to parse a natural language prompt into a strategy configuration. + """ + sys_prompt = SYSTEM_PROMPT.format(default_config=json.dumps(DEFAULT_STRATEGY_CONFIG, indent=2)) + messages = [ + {"role": "system", "content": sys_prompt} + ] + if history: + for h in history: + messages.append(h) + messages.append({"role": "user", "content": prompt}) + + res = chat_completion(messages) + if not res or not res.get("available"): + return None + + content = res["content"] + + try: + config_data = json.loads(content) + except Exception: + match = re.search(r'\{.*\}', content, re.DOTALL) + if match: + try: + config_data = json.loads(match.group(0)) + except Exception: + return None + else: + return None + + final_config = DEFAULT_STRATEGY_CONFIG.copy() + + for k, v in config_data.items(): + if k in DEFAULT_STRATEGY_CONFIG: + try: + if k == "ticker": + final_config[k] = str(v).upper() + elif k == "interval" and str(v) in ["1m", "5m", "15m", "30m", "1h", "1d"]: + final_config[k] = str(v) + elif k == "strategy_mode" and str(v) in ["dynamic", "ema_cross", "breakout", "patterns", "consensus"]: + final_config[k] = str(v) + elif k == "stop_loss_pct": + final_config[k] = max(0.001, min(0.20, float(v))) + elif k == "profit_target_pct": + final_config[k] = max(0.001, min(0.50, float(v))) + elif k == "trailing_stop_mode" and str(v) in ["atr", "fixed", "none"]: + final_config[k] = str(v) + elif k == "trailing_stop_atr_mult": + final_config[k] = max(0.5, min(5.0, float(v))) + elif k == "rsi_threshold_buy": + final_config[k] = max(10.0, min(90.0, float(v))) + elif k == "risk_per_trade_pct": + final_config[k] = max(0.001, min(0.10, float(v))) + elif k == "max_position_size_pct": + final_config[k] = max(0.05, min(1.00, float(v))) + elif k == "position_sizing_mode" and str(v) in ["atr", "fixed"]: + final_config[k] = str(v) + elif k == "commission_per_share": + final_config[k] = max(0.0, min(0.10, float(v))) + elif k == "slippage_rate": + final_config[k] = max(0.0, min(0.01, float(v))) + except Exception: + pass + + execution_plan = [ + {"step": 1, "tool": "fetch_market_data", "desc": f"Fetch {final_config['interval']} OHLCV data for {final_config['ticker']}"}, + {"step": 2, "tool": "compute_indicators", "desc": "Calculate technical indicators (EMA, RSI, ATR, MACD, ADX, Bollinger Bands, Donchian)"}, + {"step": 3, "tool": "run_backtest", "desc": f"Run {final_config['strategy_mode']} strategy backtest with ATR={final_config['trailing_stop_atr_mult']}x trailing stop"}, + {"step": 4, "tool": "generate_risk_report", "desc": "Analyze results: drawdown, regime performance, parameter sensitivity, overfitting risk"} + ] + + parsed_intent = f"Backtest {final_config['ticker']} using {final_config['strategy_mode']} strategy on {final_config['interval']} bars" + + return { + "strategy_config": final_config, + "execution_plan": execution_plan, + "parsed_intent": parsed_intent, + "source": "llm", + "usage": res["usage"] + } + + +def get_chat_response(prompt: str, history: list = None) -> dict: + """ + Generate chatbot strategy recommendations and natural language explanations. + """ + sys_prompt = CHAT_SYSTEM_PROMPT.format(default_config=json.dumps(DEFAULT_STRATEGY_CONFIG, indent=2)) + messages = [ + {"role": "system", "content": sys_prompt} + ] + if history: + for h in history: + messages.append(h) + messages.append({"role": "user", "content": prompt}) + + res = chat_completion(messages) + + # Fallback to templates if LLM has no key + if not res or not res.get("available"): + parsed = parse_research_prompt(prompt, use_llm=False) + msg = f"你好!我是 Quant.ai 策略研究助手。由于目前未检测到可用的大模型 API 密钥(OPENAI_API_KEY 或 GEMINI_API_KEY),我已使用系统规则模板将您的策略解析为:{parsed['parsed_intent']}。您可以在控制面板中查看详细参数并点击执行回测。" + return { + "message": msg, + "strategy_config": parsed["strategy_config"], + "execution_plan": parsed["execution_plan"], + "usage": {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0, "cost_usd": 0.0} + } + + content = res["content"] + strategy_config = None + clean_msg = content + + # Try parsing json out + match = re.search(r'```json\s*(\{.*?\})\s*```', content, re.DOTALL) + if not match: + match = re.search(r'(\{.*?\})', content, re.DOTALL) + + if match: + try: + config_data = json.loads(match.group(1)) + strategy_config = DEFAULT_STRATEGY_CONFIG.copy() + for k, v in config_data.items(): + if k in DEFAULT_STRATEGY_CONFIG: + try: + if k == "ticker": + strategy_config[k] = str(v).upper() + elif k == "interval" and str(v) in ["1m", "5m", "15m", "30m", "1h", "1d"]: + strategy_config[k] = str(v) + elif k == "strategy_mode" and str(v) in ["dynamic", "ema_cross", "breakout", "patterns", "consensus"]: + strategy_config[k] = str(v) + elif k == "stop_loss_pct": + strategy_config[k] = max(0.001, min(0.20, float(v))) + elif k == "profit_target_pct": + strategy_config[k] = max(0.001, min(0.50, float(v))) + elif k == "trailing_stop_mode" and str(v) in ["atr", "fixed", "none"]: + strategy_config[k] = str(v) + elif k == "trailing_stop_atr_mult": + strategy_config[k] = max(0.5, min(5.0, float(v))) + elif k == "rsi_threshold_buy": + strategy_config[k] = max(10.0, min(90.0, float(v))) + elif k == "risk_per_trade_pct": + strategy_config[k] = max(0.001, min(0.10, float(v))) + elif k == "max_position_size_pct": + strategy_config[k] = max(0.05, min(1.00, float(v))) + elif k == "position_sizing_mode" and str(v) in ["atr", "fixed"]: + strategy_config[k] = str(v) + elif k == "commission_per_share": + strategy_config[k] = max(0.0, min(0.10, float(v))) + elif k == "slippage_rate": + strategy_config[k] = max(0.0, min(0.01, float(v))) + except Exception: + pass + + clean_msg = content.replace(match.group(0), "").strip() + if not clean_msg: + clean_msg = f"我已为您生成了策略配置:{strategy_config['ticker']} ({strategy_config['strategy_mode']})。" + except Exception: + pass + + if not strategy_config: + strategy_config = DEFAULT_STRATEGY_CONFIG.copy() + + execution_plan = [ + {"step": 1, "tool": "fetch_market_data", "desc": f"Fetch {strategy_config['interval']} OHLCV data for {strategy_config['ticker']}"}, + {"step": 2, "tool": "compute_indicators", "desc": "Calculate technical indicators (EMA, RSI, ATR, MACD, ADX, Bollinger Bands, Donchian)"}, + {"step": 3, "tool": "run_backtest", "desc": f"Run {strategy_config['strategy_mode']} strategy backtest with ATR={strategy_config['trailing_stop_atr_mult']}x trailing stop"}, + {"step": 4, "tool": "generate_risk_report", "desc": "Analyze results: drawdown, regime performance, parameter sensitivity, overfitting risk"} + ] + + return { + "message": clean_msg, + "strategy_config": strategy_config, + "execution_plan": execution_plan, + "usage": res["usage"] + } + + +def get_example_prompts() -> list: + """Return example research prompts for the frontend""" + return EXAMPLE_PROMPTS + + +def get_backend_tools() -> list: + """Return available backend tools for documentation""" + return BACKEND_TOOLS diff --git a/external/Quant.ai/backend/app/broker/alpaca_adapter.py b/external/Quant.ai/backend/app/broker/alpaca_adapter.py new file mode 100644 index 0000000000000000000000000000000000000000..f894606383d3ffcfdbb15e5751f1e88a16672e98 --- /dev/null +++ b/external/Quant.ai/backend/app/broker/alpaca_adapter.py @@ -0,0 +1,154 @@ +# backend/app/broker/alpaca_adapter.py +""" +Alpaca Broker Adapter Module +Wraps official alpaca-py SDK for paper/live trading commands. +""" + +import os +from typing import Dict, List, Optional +from alpaca.trading.client import TradingClient +from alpaca.trading.requests import MarketOrderRequest, LimitOrderRequest +from alpaca.trading.enums import OrderSide, TimeInForce, OrderStatus + +class AlpacaAdapter: + def __init__(self, api_key: Optional[str] = None, api_secret: Optional[str] = None, base_url: Optional[str] = None): + # Load from arguments or fallback to env variables + self.api_key = api_key or os.environ.get("ALPACA_API_KEY") + self.api_secret = api_secret or os.environ.get("ALPACA_SECRET_KEY") or os.environ.get("ALPACA_API_SECRET") + self.base_url = base_url or os.environ.get("ALPACA_BASE_URL", "https://paper-api.alpaca.markets") + + # Determine if paper trading based on URL + self.is_paper = "paper-api" in self.base_url + + if not self.api_key or not self.api_secret: + raise ValueError("Alpaca API Credentials (Key and Secret) must be set in env or passed during initialization.") + + # Initialize Trading Client + # Note: TradingClient takes api_key, api_secret, and paper parameter. + # It handles paper vs live URL internally or respects custom URL if configured. + self.client = TradingClient(self.api_key, self.api_secret, paper=self.is_paper) + + def get_account_summary(self) -> Dict: + """ + Fetch broker account details. + Returns: + Dict containing cash, equity, buying power, and account status. + """ + account = self.client.get_account() + return { + "success": True, + "account_number": account.account_number, + "status": account.status, + "currency": account.currency, + "cash": float(account.cash), + "portfolio_value": float(account.portfolio_value), + "buying_power": float(account.buying_power), + "multiplier": float(account.multiplier), + "shorting_enabled": account.shorting_enabled, + "equity": float(account.equity), + "initial_margin": float(account.initial_margin), + "maintenance_margin": float(account.maintenance_margin), + } + + def get_open_positions(self) -> List[Dict]: + """ + Fetch all active positions. + """ + positions = self.client.get_all_positions() + parsed_positions = [] + for pos in positions: + parsed_positions.append({ + "ticker": pos.symbol, + "shares": int(pos.qty), + "avg_entry_price": float(pos.avg_entry_price), + "market_value": float(pos.market_value), + "current_price": float(pos.current_price), + "unrealized_pnl": float(pos.unrealized_pl), + "unrealized_pnl_pct": float(pos.unrealized_plpc) * 100, # Convert to % + }) + return parsed_positions + + def get_position(self, symbol: str) -> Optional[Dict]: + """ + Get position for a specific symbol. Returns None if not held. + """ + try: + pos = self.client.get_open_position(symbol.upper()) + return { + "ticker": pos.symbol, + "shares": int(pos.qty), + "avg_entry_price": float(pos.avg_entry_price), + "market_value": float(pos.market_value), + "current_price": float(pos.current_price), + "unrealized_pnl": float(pos.unrealized_pl), + "unrealized_pnl_pct": float(pos.unrealized_plpc) * 100, + } + except Exception: + return None + + def submit_market_order(self, symbol: str, qty: int, side: str) -> Dict: + """ + Submit a market order to Alpaca. + Args: + symbol: Ticker symbol (e.g. 'TSLA') + qty: Quantity of shares to buy/sell + side: 'buy' or 'sell' + """ + order_side = OrderSide.BUY if side.lower() == "buy" else OrderSide.SELL + + try: + order_request = MarketOrderRequest( + symbol=symbol.upper(), + qty=qty, + side=order_side, + time_in_force=TimeInForce.DAY + ) + order = self.client.submit_order(order_data=order_request) + return { + "success": True, + "order_id": str(order.id), + "client_order_id": str(order.client_order_id), + "status": str(order.status.value), + "filled_qty": int(order.filled_qty or 0), + "filled_avg_price": float(order.filled_avg_price or 0.0), + "message": f"Successfully submitted {side.upper()} order for {qty} shares of {symbol}." + } + except Exception as e: + return { + "success": False, + "error": str(e), + "message": f"Failed to submit market order: {str(e)}" + } + + def cancel_all_orders(self) -> Dict: + """ + Cancel all open/pending orders. + """ + try: + cancel_statuses = self.client.cancel_orders() + return { + "success": True, + "message": f"Submitted cancellation requests for all open orders. Statuses: {len(cancel_statuses)} orders canceled." + } + except Exception as e: + return { + "success": False, + "error": str(e) + } + + def close_all_positions(self) -> Dict: + """ + Close all active positions (force liquidation). + """ + try: + # close_all_positions returns a list of orders submitted to close positions + close_orders = self.client.close_all_positions(cancel_orders=True) + return { + "success": True, + "message": f"Submitted orders to close all positions. Initiated {len(close_orders)} closing orders." + } + except Exception as e: + return { + "success": False, + "error": str(e) + } diff --git a/external/Quant.ai/backend/app/broker/live_runner.py b/external/Quant.ai/backend/app/broker/live_runner.py new file mode 100644 index 0000000000000000000000000000000000000000..82a4269922cc7b703560d0c25a8f96a43e066f90 --- /dev/null +++ b/external/Quant.ai/backend/app/broker/live_runner.py @@ -0,0 +1,254 @@ +# backend/app/broker/live_runner.py +""" +Live Trading Runner Background Service +Polls real-time quotes, evaluates signals, executes trades on Alpaca, and logs decisions. +""" + +import asyncio +import datetime +import os +import pytz +from typing import Dict, List, Optional +from app.broker.alpaca_adapter import AlpacaAdapter +from app.config import ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_BASE_URL, WATCHLIST +from app.data_manager import fetch_and_prepare_data +from app.data_cache import invalidate_cache +from app.strategy import evaluate_market_state + +class LiveTradingRunner: + def __init__(self): + self.is_running = False + self.logs = [] + self.active_tickers = WATCHLIST.copy() + self.highest_prices = {} + self.loop_task = None + self.strategy_params = { + "strategy_mode": "dynamic", + "stop_loss_pct": 0.015, + "profit_target_pct": 0.030, + "trailing_stop_mode": "atr", + "trailing_stop_atr_mult": 2.0, + "rsi_threshold_buy": 65.0, + "risk_per_trade_pct": 0.01, + "max_position_size_pct": 0.50, + "position_sizing_mode": "atr", + "market_open_focus": True + } + self.ignore_market_hours = True # Set to True by default to allow testing anytime + self.adapter = None + + def add_log(self, msg: str): + timestamp = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") + full_msg = f"[{timestamp}] {msg}" + print(full_msg) # Print to server console + self.logs.append(full_msg) + if len(self.logs) > 200: # Restrict log size + self.logs.pop(0) + + def start(self, strategy_params: Optional[Dict] = None, ignore_market_hours: bool = True): + if self.is_running: + self.add_log("【警告】量化交易机器人已在运行中。") + return False + + if strategy_params: + self.strategy_params.update(strategy_params) + + self.ignore_market_hours = ignore_market_hours + + # Initialize Adapter + try: + self.adapter = AlpacaAdapter( + api_key=ALPACA_API_KEY, + api_secret=ALPACA_SECRET_KEY, + base_url=ALPACA_BASE_URL + ) + # Test connection + self.adapter.get_account_summary() + except Exception as e: + self.add_log(f"【错误】无法启动机器人:连接 Alpaca 失败。详情: {str(e)}") + return False + + self.is_running = True + self.add_log(f"🚀 量化交易机器人已启动!监控列表: {self.active_tickers} | 策略模式: {self.strategy_params['strategy_mode']}") + + # Spawn async loop task + self.loop_task = asyncio.create_task(self._run_loop()) + return True + + def stop(self): + if not self.is_running: + self.add_log("【通知】量化交易机器人未处于运行状态。") + return False + + self.is_running = False + if self.loop_task: + self.loop_task.cancel() + self.loop_task = None + + self.add_log("🛑 量化交易机器人已暂停运行。") + return True + + def get_status(self) -> Dict: + return { + "is_running": self.is_running, + "ignore_market_hours": self.ignore_market_hours, + "monitored_tickers": self.active_tickers, + "strategy_params": self.strategy_params, + "logs_count": len(self.logs) + } + + def is_market_open(self) -> bool: + """ + Check if US market is currently open (9:30 - 16:00 EST, Mon-Fri) + """ + if self.ignore_market_hours: + return True + + est = pytz.timezone('US/Eastern') + now = datetime.datetime.now(est) + + # Check weekday (0-4 is Mon-Fri) + if now.weekday() > 4: + return False + + market_open = now.replace(hour=9, minute=30, second=0, microsecond=0) + market_close = now.replace(hour=16, minute=0, second=0, microsecond=0) + + return market_open <= now <= market_close + + async def _run_loop(self): + while self.is_running: + try: + # 1. Check if market is open + if not self.is_market_open(): + self.add_log("💤 当前处于非交易时段,机器人处于休眠待机状态...") + await asyncio.sleep(60) + continue + + self.add_log("🔄 开始新一轮行情扫描与策略评估...") + + # 2. Get active positions from Alpaca to sync state + try: + positions_list = self.adapter.get_open_positions() + positions_by_ticker = {pos['ticker']: pos for pos in positions_list} + except Exception as e: + self.add_log(f"⚠️ 无法从 Alpaca 获取当前持仓:{str(e)},跳过本轮。") + await asyncio.sleep(20) + continue + + # 3. Poll and evaluate each stock in our watchlist + for ticker in self.active_tickers: + if not self.is_running: + break + + try: + # Invalidate cache to force yfinance to fetch fresh prices + invalidate_cache(ticker) + + # Fetch the last few days of 1-minute bars + df = fetch_and_prepare_data(ticker, period="3d", interval="1m") + + if df.empty or len(df) < 2: + continue + + # Use the last bar as current state, second-to-last as prev + row = df.iloc[-1] + prev_row = df.iloc[-2] + close_price = float(row['Close']) + + # Get broker position details + alpaca_pos = positions_by_ticker.get(ticker) + current_shares = alpaca_pos['shares'] if alpaca_pos else 0 + avg_cost = alpaca_pos['avg_entry_price'] if alpaca_pos else 0.0 + + # Track highest price achieved while holding for trailing stop-loss + if current_shares > 0: + # Initialize or update peak price + highest_price = max( + self.highest_prices.get(ticker, avg_cost), + close_price + ) + self.highest_prices[ticker] = highest_price + else: + highest_price = 0.0 + if ticker in self.highest_prices: + del self.highest_prices[ticker] + + # 4. Evaluate strategy actions + action, reason = evaluate_market_state( + row=row, + prev_row=prev_row, + current_shares=current_shares, + avg_cost=avg_cost, + ticker=ticker, + highest_price=highest_price, + params=self.strategy_params + ) + + # Log status + regime_name = row.get('Regime', 'range_bound') + self.add_log(f"📊 [{ticker}] 当前价格: ${close_price:.2f} | 市场状态: {regime_name} | 持仓: {current_shares}股 | 决策: {action} ({reason})") + + # 5. Execute action on Alpaca + if action == "BUY" and current_shares == 0: + # Fetch account value for position sizing + account = self.adapter.get_account_summary() + total_equity = account['equity'] + cash = account['cash'] + + # Size using ATR logic + risk_pct = self.strategy_params.get("risk_per_trade_pct", 0.01) + atr_mult = self.strategy_params.get("trailing_stop_atr_mult", 2.0) + max_pct = self.strategy_params.get("max_position_size_pct", 0.50) + atr = float(row['ATR']) + + dollar_risk = total_equity * risk_pct + stop_distance = atr * atr_mult + + if stop_distance > 0: + shares = int(dollar_risk / stop_distance) + else: + shares = int((total_equity * max_pct) / close_price) + + # Apply sizing caps + max_alloc = total_equity * max_pct + max_shares = int(max_alloc / close_price) + shares = min(shares, max_shares) + + # Ensure we don't buy more than we have cash for + cash_shares = int((cash * 0.95) / close_price) # leave 5% buffer + shares = min(shares, cash_shares) + + if shares > 0: + self.add_log(f"🛒 [{ticker}] 触发买入信号!发送买单:以市价买入 {shares} 股...") + order_res = self.adapter.submit_market_order(ticker, shares, "buy") + if order_res.get("success"): + self.add_log(f"✅ [{ticker}] 买单提交成功!Alpaca 订单号: {order_res['order_id']}") + self.highest_prices[ticker] = close_price + else: + self.add_log(f"❌ [{ticker}] 买单提交失败。原因: {order_res.get('error')}") + else: + self.add_log(f"⚠️ [{ticker}] 资金不足或计算股数为0,无法下单。") + + elif action == "SELL" and current_shares > 0: + self.add_log(f"🔔 [{ticker}] 触发卖出信号!发送平仓卖单:以市价卖出 {current_shares} 股...") + order_res = self.adapter.submit_market_order(ticker, current_shares, "sell") + if order_res.get("success"): + self.add_log(f"✅ [{ticker}] 平仓单提交成功!Alpaca 订单号: {order_res['order_id']}") + if ticker in self.highest_prices: + del self.highest_prices[ticker] + else: + self.add_log(f"❌ [{ticker}] 平仓单提交失败。原因: {order_res.get('error')}") + + except Exception as ex: + self.add_log(f"⚠️ 扫描 {ticker} 发生错误: {str(ex)}") + + # Wait for next minute (60 seconds) + await asyncio.sleep(60) + + except asyncio.CancelledError: + self.add_log("Background trading loop task cancelled.") + break + except Exception as e: + self.add_log(f"⚠️ 交易主循环异常: {str(e)}") + await asyncio.sleep(30) diff --git a/external/Quant.ai/backend/app/config.py b/external/Quant.ai/backend/app/config.py new file mode 100644 index 0000000000000000000000000000000000000000..3512e6d7a526d41b39dc447c947775231914988d --- /dev/null +++ b/external/Quant.ai/backend/app/config.py @@ -0,0 +1,47 @@ +# backend/app/config.py +import os +from dotenv import load_dotenv + +# Load env variables from backend/.env +current_dir = os.path.dirname(os.path.abspath(__file__)) +dotenv_path = os.path.join(os.path.dirname(current_dir), '.env') +load_dotenv(dotenv_path) + +# Alpaca API 配置 +ALPACA_API_KEY = os.getenv("ALPACA_API_KEY") +ALPACA_SECRET_KEY = os.getenv("ALPACA_SECRET_KEY") or os.getenv("ALPACA_API_SECRET") +ALPACA_BASE_URL = os.getenv("ALPACA_BASE_URL", "https://paper-api.alpaca.markets") + +# 模拟账户初始资金 +INITIAL_CASH = 30000.0 # 初始本金:3万美金 +DAILY_PROFIT_TARGET = 500.0 # 每日止盈目标:500刀,达到立刻强制平仓收工 +DAILY_LOSS_LIMIT = 300.0 # 每日最大亏损额度:300刀,达到强制平仓收工防爆仓 + +# 单笔交易风险控制 +RISK_PER_TRADE_PCT = 0.01 # 单笔交易最大允许亏损:总本金的 1% ($300) +MAX_POSITION_SIZE_PCT = 0.50 # 单只股票最大持仓比例:不超过账户总资产的 50% + +# 账户级高级风控 +SOFT_DRAWDOWN_LIMIT = 0.07 # 软回撤降险线:自权益高峰回撤达 7%,单笔交易风险减半 +HARD_DRAWDOWN_LIMIT = 0.12 # 硬回撤熔断线:自权益高峰回撤达 12%,停止新开仓 +MAX_CONSECUTIVE_LOSSES = 5 # 连续亏损上限:连亏 5 笔触发降险,单笔交易风险减半 + + +# 真实交易损耗模拟 (防守佣金与滑点) +SLIPPAGE_RATE = 0.0003 # 滑点率:万分之三(买入加价 0.03%,卖出减价 0.03%) +COMMISSION_PER_SHARE = 0.005 # 每股交易佣金:0.005 美元 +MIN_COMMISSION_PER_ORDER = 1.0 # 单笔交易最低收取佣金:1.0 美元 (即使只买1股也收1刀,惩罚频繁极小单交易) + +# 交易时间控制 (美东时间 EST) +MARKET_OPEN_TIME = "09:30" +MARKET_CLOSE_TIME = "16:00" +FORCE_LIQUIDATION_TIME = "15:55" # 日内清仓时间:下午 3:55 强制无条件市价清仓,不持股过夜 + +# 开盘突击模式配置 +MARKET_OPEN_FOCUS_DEFAULT = True # 是否默认开启开盘突击模式 +MARKET_OPEN_FOCUS_START = "09:30" # 开盘开始时间 +MARKET_OPEN_FOCUS_END = "10:15" # 开盘结束时间 (前 45 分钟) +FORCE_LIQUIDATION_OPEN_FOCUS = "10:30" # 开盘突击模式下,10:30 强制清仓出场,防午盘横盘震荡损耗 + +# 默认监控的高流动性股票池 +WATCHLIST = ["TSLA", "NVDA", "AAPL", "MSFT", "AMD"] diff --git a/external/Quant.ai/backend/app/data_cache.py b/external/Quant.ai/backend/app/data_cache.py new file mode 100644 index 0000000000000000000000000000000000000000..98db73840710eea2b2e54aff5117f7124ee03a54 --- /dev/null +++ b/external/Quant.ai/backend/app/data_cache.py @@ -0,0 +1,92 @@ +# backend/app/data_cache.py +""" +本地 Parquet 数据缓存层 — 减少 yfinance 重复下载,提升回测响应速度 +""" +import os +import pandas as pd +import hashlib +from datetime import datetime, timedelta + +CACHE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "data_cache") +os.makedirs(CACHE_DIR, exist_ok=True) + +# 缓存 TTL 配置(秒) +CACHE_TTL = { + "1m": 60 * 30, # 30分钟 + "5m": 60 * 60, # 1小时 + "15m": 60 * 60 * 2, # 2小时 + "30m": 60 * 60 * 4, # 4小时 + "1h": 60 * 60 * 8, # 8小时 + "1d": 60 * 60 * 24, # 24小时 +} + +def _cache_key(ticker: str, period: str, interval: str) -> str: + raw = f"{ticker}_{period}_{interval}" + return hashlib.md5(raw.encode()).hexdigest()[:12] + +def _cache_path(key: str) -> str: + return os.path.join(CACHE_DIR, f"{key}.parquet") + +def _meta_path(key: str) -> str: + return os.path.join(CACHE_DIR, f"{key}.meta") + +def get_cached(ticker: str, period: str, interval: str): + """读取缓存,过期或不存在返回 None""" + key = _cache_key(ticker, period, interval) + parquet_file = _cache_path(key) + meta_file = _meta_path(key) + + if not os.path.exists(parquet_file) or not os.path.exists(meta_file): + return None + + # 检查过期时间 + try: + with open(meta_file, 'r') as f: + saved_time = float(f.read().strip()) + except Exception: + return None + + ttl = CACHE_TTL.get(interval, 3600) + if datetime.now().timestamp() - saved_time > ttl: + return None # 已过期 + + try: + df = pd.read_parquet(parquet_file) + return df + except Exception: + return None + +def save_cache(ticker: str, period: str, interval: str, df: pd.DataFrame): + """保存数据到 Parquet 缓存""" + if df is None or df.empty: + return + key = _cache_key(ticker, period, interval) + try: + df.to_parquet(_cache_path(key)) + with open(_meta_path(key), 'w') as f: + f.write(str(datetime.now().timestamp())) + except Exception as e: + print(f"缓存写入失败: {e}") + +def invalidate_cache(ticker: str = None): + """清除缓存,ticker=None 时清除全部""" + for fname in os.listdir(CACHE_DIR): + fpath = os.path.join(CACHE_DIR, fname) + try: + os.remove(fpath) + except Exception: + pass + +def get_cache_stats() -> dict: + """返回缓存使用统计""" + try: + files = [f for f in os.listdir(CACHE_DIR) if f.endswith('.parquet')] + total_size = sum(os.path.getsize(os.path.join(CACHE_DIR, f)) for f in os.listdir(CACHE_DIR)) + except Exception: + files = [] + total_size = 0 + return { + "cached_datasets": len(files), + "total_size_mb": round(total_size / 1024 / 1024, 2), + "cache_dir": CACHE_DIR + } diff --git a/external/Quant.ai/backend/app/data_manager.py b/external/Quant.ai/backend/app/data_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..e3cfc95b9a4f6e550159c398a65aae78a86fbdd3 --- /dev/null +++ b/external/Quant.ai/backend/app/data_manager.py @@ -0,0 +1,364 @@ +# backend/app/data_manager.py + +import yfinance as yf +import pandas as pd +import numpy as np +import datetime +from app.data_cache import get_cached, save_cache + +# 默认时间间隔对应的回测历史区间 +INTERVAL_TO_PERIOD = { + "1m": "5d", + "5m": "1mo", + "15m": "1mo", + "30m": "1mo", + "1h": "3mo", + "1d": "1y" +} + +# 缓存公司基本信息,避免频繁网络请求导致缓慢 +COMPANY_INFO_CACHE = {} + +def get_company_info(ticker): + """ + 获取公司名、板块、行业、市值和业务描述,带有缓存与默认兜底,保证极速响应。 + """ + ticker = ticker.upper() + if ticker in COMPANY_INFO_CACHE: + return COMPANY_INFO_CACHE[ticker] + + # 常用股票静态数据库,优先返回以保证零延迟 + static_db = { + "TSLA": { + "name": "Tesla, Inc.", + "sector": "Consumer Cyclical (消费周期性)", + "industry": "Auto Manufacturers (汽车制造商)", + "market_cap": 820000000000, + "description": "Tesla Inc. 是一家设计、开发、制造和销售电动汽车、能源生成和存储系统的美国跨国公司。它是全球最受关注的高波动率日内交易标的。" + }, + "NVDA": { + "name": "NVIDIA Corporation", + "sector": "Technology (科技)", + "industry": "Semiconductors (半导体)", + "market_cap": 3150000000000, + "description": "NVIDIA Corporation 是一家设计图形处理器(GPU)的半导体跨国科技公司,在人工智能芯片、数据中心和高性能计算领域处于绝对垄断地位。" + }, + "AAPL": { + "name": "Apple Inc.", + "sector": "Technology (科技)", + "industry": "Consumer Electronics (消费电子)", + "market_cap": 3320000000000, + "description": "Apple Inc. 是全球最具价值的电子科技公司,主营 iPhone、Mac、iPad 等消费终端设备以及各种云端订阅软件服务,现金流充裕,波动相对稳健。" + }, + "MSFT": { + "name": "Microsoft Corporation", + "sector": "Technology (科技)", + "industry": "Software—Infrastructure (基础软件)", + "market_cap": 3250000000000, + "description": "Microsoft Corporation 是全球软件与云服务的龙头企业。旗下拥有 Windows 系统、Azure 云平台、Office 软件,并通过 OpenAI 领跑生成式 AI 时代。" + }, + "AMD": { + "name": "Advanced Micro Devices, Inc.", + "sector": "Technology (科技)", + "industry": "Semiconductors (半导体)", + "market_cap": 260000000000, + "description": "Advanced Micro Devices, Inc. 是一家全球半导体公司,主营微处理器(CPU)、显卡(GPU)以及游戏主机定制芯片,与英特尔和英伟达呈竞争关系。" + } + } + + if ticker in static_db: + COMPANY_INFO_CACHE[ticker] = static_db[ticker] + return static_db[ticker] + + try: + stock = yf.Ticker(ticker) + info = stock.info + name = info.get("longName", info.get("shortName", ticker)) + sector = info.get("sector", "General Sector") + industry = info.get("industry", "General Industry") + market_cap = info.get("marketCap", 0) + description = info.get("longBusinessSummary", "No details available.") + + data = { + "name": name, + "sector": sector, + "industry": industry, + "market_cap": market_cap, + "description": description + } + COMPANY_INFO_CACHE[ticker] = data + return data + except Exception as e: + # 如果 yfinance 接口请求出错/被限制,使用兜底值 + fallback = { + "name": f"{ticker} Corporation", + "sector": "General Sector (常规板块)", + "industry": "General Industry (常规行业)", + "market_cap": 0, + "description": f"未能获取到 {ticker} 的网络实时介绍,已自动生成默认档案。该标的目前可参与量化行情回测。" + } + COMPANY_INFO_CACHE[ticker] = fallback + return fallback + +def calculate_rsi(series, period=14): + """ + 计算 RSI (相对强弱指标) + """ + delta = series.diff() + gain = (delta.where(delta > 0, 0)).rolling(window=period).mean() + loss = (-delta.where(delta < 0, 0)).rolling(window=period).mean() + + rs = gain / loss + rsi = 100 - (100 / (1 + rs)) + return rsi + +def calculate_atr(df, period=14): + """ + 计算 ATR (真实波幅) + """ + high_low = df['High'] - df['Low'] + high_close = np.abs(df['High'] - df['Close'].shift()) + low_close = np.abs(df['Low'] - df['Close'].shift()) + + ranges = pd.concat([high_low, high_close, low_close], axis=1) + true_range = np.max(ranges, axis=1) + return true_range.rolling(window=period).mean() + +def calculate_adx(df, period=14): + """ + 计算 ADX (平均趋向指数),衡量趋势强度 + """ + df = df.copy() + high = df['High'] + low = df['Low'] + close = df['Close'] + + # True Range + tr1 = high - low + tr2 = (high - close.shift(1)).abs() + tr3 = (low - close.shift(1)).abs() + tr = pd.concat([tr1, tr2, tr3], axis=1).max(axis=1) + + # Directional Movement + up_move = high.diff(1) + down_move = -low.diff(1) + + plus_dm = np.where((up_move > down_move) & (up_move > 0), up_move, 0.0) + minus_dm = np.where((down_move > up_move) & (down_move > 0), down_move, 0.0) + + # Smoothed Wilder's MA + tr_smooth = pd.Series(tr).ewm(alpha=1/period, adjust=False).mean() + plus_dm_smooth = pd.Series(plus_dm, index=df.index).ewm(alpha=1/period, adjust=False).mean() + minus_dm_smooth = pd.Series(minus_dm, index=df.index).ewm(alpha=1/period, adjust=False).mean() + + plus_di = 100 * (plus_dm_smooth / np.maximum(tr_smooth, 1e-8)) + minus_di = 100 * (minus_dm_smooth / np.maximum(tr_smooth, 1e-8)) + + dx = 100 * (plus_di - minus_di).abs() / np.maximum(plus_di + minus_di, 1e-8) + adx = dx.ewm(alpha=1/period, adjust=False).mean() + + return plus_di, minus_di, adx + +def get_yesterday_levels(ticker): + """ + 获取昨日的最高价(PDH)、最低价(PDL)、收盘价(PDC) + 使用日线级别数据,确保绝对准确 + """ + try: + stock = yf.Ticker(ticker) + df_daily = stock.history(period="5d") + if len(df_daily) >= 2: + yesterday = df_daily.iloc[-2] # -1 是今天,-2 是昨天 + return { + "PDH": float(yesterday['High']), + "PDL": float(yesterday['Low']), + "PDC": float(yesterday['Close']) + } + except Exception as e: + print(f"获取昨日关键位置失败 ({ticker}): {str(e)}") + + return {"PDH": 0.0, "PDL": 0.0, "PDC": 0.0} + +def compute_candle_features(df): + """ + 计算K线形态特征向量:实体比例、上影线比例、下影线比例、跳空比例 + """ + df = df.copy() + diff = df['High'] - df['Low'] + denom = np.where(diff == 0, 1e-8, diff) + + df['body_ratio'] = np.abs(df['Close'] - df['Open']) / denom + df['upper_shadow_ratio'] = (df['High'] - np.maximum(df['Close'], df['Open'])) / denom + df['lower_shadow_ratio'] = (np.minimum(df['Close'], df['Open']) - df['Low']) / denom + df['gap_flag'] = (df['Open'] - df['Close'].shift(1)) / (df['Close'].shift(1) + 1e-8) + + df['body_ratio'] = df['body_ratio'].fillna(0.0) + df['upper_shadow_ratio'] = df['upper_shadow_ratio'].fillna(0.0) + df['lower_shadow_ratio'] = df['lower_shadow_ratio'].fillna(0.0) + df['gap_flag'] = df['gap_flag'].fillna(0.0) + return df + +def fetch_and_prepare_data(ticker, period=None, interval="1m"): + """ + 获取股票行情并计算量化指标,支持多时间周期。 + """ + ticker = ticker.upper() + if period is None: + period = INTERVAL_TO_PERIOD.get(interval, "5d") + + # 优先尝试从本地缓存读取 + cached_df = get_cached(ticker, period, interval) + if cached_df is not None: + return cached_df + + # 抓取包含盘前盘后的 K线数据 + stock = yf.Ticker(ticker) + + # 只有分钟级别 (1m, 5m, 15m, 30m, 1h) 支持盘前盘后 prepost + is_intraday = interval in ["1m", "5m", "15m", "30m", "1h"] + + df = stock.history(period=period, interval=interval, prepost=is_intraday) + + if df.empty: + raise ValueError(f"未能获取到 {ticker} 的 {interval} 行情数据。") + + # 确保时间戳已转换为本地时区 (美东时间) + if df.index.tz is None: + df = df.tz_localize('UTC').tz_convert('US/Eastern') + else: + df = df.tz_convert('US/Eastern') + + df['Date'] = df.index.date + + # 计算 VWAP (日内均线按交易日独立累计,如果是日线级别,VWAP 退化为典型价) + df['Typical_Price'] = (df['High'] + df['Low'] + df['Close']) / 3 + df['TP_Volume'] = df['Typical_Price'] * df['Volume'] + + if is_intraday: + df['Cum_TP_Vol'] = df.groupby('Date')['TP_Volume'].cumsum() + df['Cum_Vol'] = df.groupby('Date')['Volume'].cumsum() + # 避免除以 0 + df['Cum_Vol'] = df['Cum_Vol'].replace(0, 1) + df['VWAP'] = df['Cum_TP_Vol'] / df['Cum_Vol'] + else: + df['VWAP'] = df['Typical_Price'] + + # 计算 9 / 21 / 50 EMA 和 RSI + df['EMA_9'] = df['Close'].ewm(span=9, adjust=False).mean() + df['EMA_21'] = df['Close'].ewm(span=21, adjust=False).mean() + df['EMA_50'] = df['Close'].ewm(span=50, adjust=False).mean() + df['RSI'] = calculate_rsi(df['Close'], period=14) + df['ATR'] = calculate_atr(df, period=14) + + # 补充指标:ADX, MACD, Donchian, OBV, ROC, RVOL + df['Plus_DI'], df['Minus_DI'], df['ADX'] = calculate_adx(df, period=14) + + # MACD + ema12 = df['Close'].ewm(span=12, adjust=False).mean() + ema26 = df['Close'].ewm(span=26, adjust=False).mean() + df['MACD'] = ema12 - ema26 + df['MACD_Signal'] = df['MACD'].ewm(span=9, adjust=False).mean() + df['MACD_Hist'] = df['MACD'] - df['MACD_Signal'] + + # 唐奇安通道 + df['Donchian_High'] = df['High'].rolling(window=20).max() + df['Donchian_Low'] = df['Low'].rolling(window=20).min() + df['Donchian_High_55'] = df['High'].rolling(window=55).max() + df['Donchian_Low_55'] = df['Low'].rolling(window=55).min() + + # 能量潮指标 (OBV) + df['OBV'] = (np.sign(df['Close'].diff()).fillna(0.0) * df['Volume']).cumsum() + + # 动量 ROC + df['ROC'] = df['Close'].pct_change(periods=20) * 100 + + # 相对成交量 RVOL + df['RVOL'] = df['Volume'] / np.maximum(df['Volume'].rolling(window=20).mean(), 1e-8) + + # 计算 TTM Squeeze 挤压状态 + df['BB_Basis'] = df['Close'].rolling(window=20).mean() + df['BB_Std'] = df['Close'].rolling(window=20).std() + df['BB_Upper'] = df['BB_Basis'] + (2 * df['BB_Std']) + df['BB_Lower'] = df['BB_Basis'] - (2 * df['BB_Std']) + + # 肯特纳通道 (标准:基于 20 EMA 和 2.0 ATR) + df['KC_Basis'] = df['Close'].ewm(span=20, adjust=False).mean() + df['KC_Upper'] = df['KC_Basis'] + (2.0 * df['ATR']) + df['KC_Lower'] = df['KC_Basis'] - (2.0 * df['ATR']) + + df['Squeeze_On'] = (df['BB_Upper'] < df['KC_Upper']) & (df['BB_Lower'] > df['KC_Lower']) + + # 状态路由判定 (Regime Classification) + df['ATR_Ratio'] = df['ATR'] / df['Close'] + high_vol_th = df['ATR_Ratio'].rolling(252, min_periods=20).quantile(0.90).fillna(0.05) + + regimes = np.array(["range_bound"] * len(df), dtype=object) + + is_high_vol = df['ATR_Ratio'] > high_vol_th + is_trend_up = (df['ADX'] > 20) & (df['EMA_9'] > df['EMA_21']) & (df['EMA_21'] > df['EMA_50']) + is_trend_down = (df['ADX'] > 20) & (df['EMA_9'] < df['EMA_21']) & (df['EMA_21'] < df['EMA_50']) + + # 优先级别:高波动 -> 下跌趋势 -> 上涨趋势 -> 震荡 + regimes[is_trend_down] = "trend_down" + regimes[is_trend_up] = "trend_up" + regimes[is_high_vol] = "high_volatility" + + df['Regime'] = regimes + + # 盘前与昨日关键位 + if is_intraday: + df['Time'] = df.index.time + market_open = datetime.time(9, 30) + market_close = datetime.time(16, 0) + + df['Is_Regular_Hours'] = df['Time'].apply(lambda t: market_open <= t <= market_close) + df['Is_Pre_Market'] = df['Time'].apply(lambda t: datetime.time(4, 0) <= t < market_open) + + # 每日计算 PMH / PML 盘前最值 + pm_data = df[df['Is_Pre_Market']] + if not pm_data.empty: + pmh_dict = pm_data.groupby('Date')['High'].max().to_dict() + pml_dict = pm_data.groupby('Date')['Low'].min().to_dict() + df['PMH'] = df['Date'].map(pmh_dict).fillna(0.0) + df['PML'] = df['Date'].map(pml_dict).fillna(0.0) + else: + df['PMH'] = 0.0 + df['PML'] = 0.0 + + regular_hours_df = df[df['Is_Regular_Hours']].copy() + else: + # 日线级别数据全部视为常规时段 + regular_hours_df = df.copy() + regular_hours_df['Is_Regular_Hours'] = True + regular_hours_df['Is_Pre_Market'] = False + regular_hours_df['PMH'] = 0.0 + regular_hours_df['PML'] = 0.0 + + # 获取昨日关键位 + yesterday_levels = get_yesterday_levels(ticker) + regular_hours_df['PDH'] = yesterday_levels['PDH'] + regular_hours_df['PDL'] = yesterday_levels['PDL'] + regular_hours_df['PDC'] = yesterday_levels['PDC'] + + # 清除临时列 + regular_hours_df.drop(columns=['Typical_Price', 'TP_Volume', 'Cum_TP_Vol', 'Cum_Vol'], inplace=True, errors='ignore') + + # 计算 K线形态特征向量 + regular_hours_df = compute_candle_features(regular_hours_df) + + # 填充缺失值,避免初期的 NaN 导致崩溃 + regular_hours_df.ffill(inplace=True) + regular_hours_df.bfill(inplace=True) + + # 保存数据到 Parquet 本地缓存 + save_cache(ticker, period, interval, regular_hours_df) + + return regular_hours_df + +if __name__ == "__main__": + print("测试多周期获取数据...") + for iv in ["5m", "1d"]: + data = fetch_and_prepare_data("AAPL", interval=iv) + print(f"周期 {iv}: 获取到 {len(data)} 行数据") + info = get_company_info("AAPL") + print(f"公司名: {info['name']}, 行业: {info['industry']}") diff --git a/external/Quant.ai/backend/app/experiment_manager.py b/external/Quant.ai/backend/app/experiment_manager.py new file mode 100644 index 0000000000000000000000000000000000000000..b9960cb3caff6b85aa871527a92589eb03671b33 --- /dev/null +++ b/external/Quant.ai/backend/app/experiment_manager.py @@ -0,0 +1,185 @@ +# backend/app/experiment_manager.py +""" +Experiment Manager — Saves and manages backtest experiments in an SQLite database. +""" + +import os +import sqlite3 +import json +from datetime import datetime + +# Database path relative to this file +DB_PATH = os.path.join(os.path.dirname(os.path.abspath(__file__)), "experiments.db") + +def get_connection(): + """ + Get a connection to the SQLite database. + """ + conn = sqlite3.connect(DB_PATH) + conn.row_factory = sqlite3.Row + return conn + +def init_db(): + """ + Initialize the experiments table. + """ + conn = get_connection() + cursor = conn.cursor() + cursor.execute(""" + CREATE TABLE IF NOT EXISTS experiments ( + id INTEGER PRIMARY KEY AUTOINCREMENT, + name TEXT NOT NULL, + timestamp TEXT NOT NULL, + ticker TEXT NOT NULL, + interval TEXT NOT NULL, + strategy_mode TEXT NOT NULL, + config_json TEXT NOT NULL, + metrics_json TEXT NOT NULL, + equity_curve_json TEXT NOT NULL, + drawdown_curve_json TEXT NOT NULL, + regime_breakdown_json TEXT NOT NULL, + ai_report TEXT + ) + """) + conn.commit() + conn.close() + +# Auto-initialize DB on import +init_db() + +def save_experiment(name, ticker, interval, strategy_mode, config, metrics, equity_curve, drawdown_curve, regime_breakdown, ai_report=None): + """ + Save a new backtest experiment to the database. + """ + conn = get_connection() + cursor = conn.cursor() + timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") + + cursor.execute(""" + INSERT INTO experiments ( + name, timestamp, ticker, interval, strategy_mode, + config_json, metrics_json, equity_curve_json, + drawdown_curve_json, regime_breakdown_json, ai_report + ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) + """, ( + name, + timestamp, + ticker.upper(), + interval, + strategy_mode, + json.dumps(config), + json.dumps(metrics), + json.dumps(equity_curve), + json.dumps(drawdown_curve), + json.dumps(regime_breakdown), + ai_report + )) + + new_id = cursor.lastrowid + conn.commit() + conn.close() + return new_id + +def list_experiments(): + """ + List all saved experiments (returns summary information for list view). + """ + conn = get_connection() + cursor = conn.cursor() + cursor.execute(""" + SELECT id, name, timestamp, ticker, interval, strategy_mode, metrics_json, config_json + FROM experiments + ORDER BY id DESC + """) + rows = cursor.fetchall() + conn.close() + + results = [] + for r in rows: + results.append({ + "id": r["id"], + "name": r["name"], + "timestamp": r["timestamp"], + "ticker": r["ticker"], + "interval": r["interval"], + "strategy_mode": r["strategy_mode"], + "metrics": json.loads(r["metrics_json"]), + "config": json.loads(r["config_json"]) + }) + return results + +def get_experiment(exp_id): + """ + Retrieve full details of a specific experiment. + """ + conn = get_connection() + cursor = conn.cursor() + cursor.execute(""" + SELECT * FROM experiments WHERE id = ? + """, (exp_id,)) + row = cursor.fetchone() + conn.close() + + if not row: + return None + + return { + "id": row["id"], + "name": row["name"], + "timestamp": row["timestamp"], + "ticker": row["ticker"], + "interval": row["interval"], + "strategy_mode": row["strategy_mode"], + "config": json.loads(row["config_json"]), + "metrics": json.loads(row["metrics_json"]), + "equity_curve": json.loads(row["equity_curve_json"]), + "drawdown_curve": json.loads(row["drawdown_curve_json"]), + "regime_breakdown": json.loads(row["regime_breakdown_json"]), + "ai_report": row["ai_report"] + } + +def delete_experiment(exp_id): + """ + Delete a specific experiment. + """ + conn = get_connection() + cursor = conn.cursor() + cursor.execute("DELETE FROM experiments WHERE id = ?", (exp_id,)) + conn.commit() + deleted_rows = cursor.rowcount + conn.close() + return deleted_rows > 0 + +def compare_experiments(exp_ids): + """ + Compare multiple experiments by retrieving their config & metrics. + """ + if not exp_ids: + return [] + + conn = get_connection() + cursor = conn.cursor() + placeholders = ",".join(["?"] * len(exp_ids)) + query = f""" + SELECT id, name, timestamp, ticker, interval, strategy_mode, metrics_json, config_json, equity_curve_json + FROM experiments + WHERE id IN ({placeholders}) + """ + cursor.execute(query, tuple(exp_ids)) + rows = cursor.fetchall() + conn.close() + + results = [] + for r in rows: + results.append({ + "id": r["id"], + "name": r["name"], + "timestamp": r["timestamp"], + "ticker": r["ticker"], + "interval": r["interval"], + "strategy_mode": r["strategy_mode"], + "metrics": json.loads(r["metrics_json"]), + "config": json.loads(r["config_json"]), + "equity_curve": json.loads(r["equity_curve_json"]) + }) + return results diff --git a/external/Quant.ai/backend/app/llm_client.py b/external/Quant.ai/backend/app/llm_client.py new file mode 100644 index 0000000000000000000000000000000000000000..3b9c9b822044ad967c62af78621ff8a0fa913ff3 --- /dev/null +++ b/external/Quant.ai/backend/app/llm_client.py @@ -0,0 +1,208 @@ +# backend/app/llm_client.py +""" +Unified LLM Client Layer — Supports OpenAI and Google Gemini via HTTP API. +No heavy SDK packages required. Includes retry backoff and token/cost counters. +""" + +import os +import time +import requests +import logging + +logger = logging.getLogger(__name__) + +TOTAL_TOKENS_USED = 0 +TOTAL_COST_USD = 0.0 + +def estimate_cost(prompt_tokens: int, completion_tokens: int, provider: str = "openai") -> float: + """Estimate token costs based on current provider pricing""" + if provider == "gemini": + # gemini-1.5-flash: $0.075 / 1M input tokens, $0.30 / 1M output tokens + return (prompt_tokens * 0.075 / 1_000_000) + (completion_tokens * 0.30 / 1_000_000) + else: + # gpt-4o-mini: $0.15 / 1M input tokens, $0.60 / 1M output tokens + return (prompt_tokens * 0.15 / 1_000_000) + (completion_tokens * 0.60 / 1_000_000) + +def get_usage_stats() -> dict: + """Return accumulated token count and cost estimate""" + global TOTAL_TOKENS_USED, TOTAL_COST_USD + openai_key = os.environ.get("OPENAI_API_KEY") + gemini_key = os.environ.get("GEMINI_API_KEY") + provider = "none" + if gemini_key: + provider = "gemini" + elif openai_key: + provider = "openai" + + return { + "total_tokens_used": TOTAL_TOKENS_USED, + "total_cost_usd": round(TOTAL_COST_USD, 6), + "provider": provider, + "available": provider != "none" + } + +def _chat_completion_openai_compat(url: str, headers: dict, model: str, payload_base: dict, attempt: int) -> dict: + """Attempt OpenAI-compatible endpoint request""" + try: + res = requests.post(url, json=payload_base, headers=headers, timeout=30) + if res.status_code == 200: + return res.json() + else: + logger.warning(f"LLM API compat endpoint returned {res.status_code}: {res.text}") + except Exception as e: + logger.warning(f"LLM API compat endpoint error: {e}") + return None + +def _chat_completion_gemini_native(messages: list, gemini_key: str, response_format=None) -> dict: + """Fallback to native Google Gemini API endpoint""" + url = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={gemini_key}" + headers = {"Content-Type": "application/json"} + + contents = [] + system_instruction = None + + for m in messages: + role = m["role"] + content = m["content"] + if role == "system": + system_instruction = {"parts": [{"text": content}]} + else: + gemini_role = "user" if role == "user" else "model" + contents.append({ + "role": gemini_role, + "parts": [{"text": content}] + }) + + payload = {"contents": contents} + if system_instruction: + payload["systemInstruction"] = system_instruction + + generation_config = {} + if response_format and response_format.get("type") == "json_object": + generation_config["responseMimeType"] = "application/json" + if generation_config: + payload["generationConfig"] = generation_config + + try: + res = requests.post(url, json=payload, headers=headers, timeout=30) + if res.status_code == 200: + res_json = res.json() + # Extract content and usage metadata + try: + candidate = res_json["candidates"][0] + text = candidate["content"]["parts"][0]["text"] + usage = res_json.get("usageMetadata", {}) + prompt_tokens = usage.get("promptTokenCount", 0) + completion_tokens = usage.get("candidatesTokenCount", 0) + + # Mock OpenAI response format to unify downstream parsing + return { + "choices": [{ + "message": { + "role": "assistant", + "content": text + } + }], + "usage": { + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens + } + } + except Exception as parse_err: + logger.error(f"Failed to parse native gemini response: {parse_err}. Response: {res_json}") + else: + logger.warning(f"Gemini native endpoint returned {res.status_code}: {res.text}") + except Exception as e: + logger.warning(f"Gemini native endpoint error: {e}") + return None + +def chat_completion(messages: list, tools: list = None, response_format=None, provider: str = None) -> dict: + """ + Send messages to OpenAI or Gemini and return structured response. + Returns: {"content": str, "provider": str, "available": bool, "usage": dict} + """ + global TOTAL_TOKENS_USED, TOTAL_COST_USD + + openai_key = os.environ.get("OPENAI_API_KEY") + gemini_key = os.environ.get("GEMINI_API_KEY") + + if not openai_key and not gemini_key: + return {"provider": "none", "available": False} + + if not provider: + if gemini_key: + provider = "gemini" + else: + provider = "openai" + + # Set headers and URL based on provider + if provider == "gemini": + url = "https://generativelanguage.googleapis.com/v1beta/openai/chat/completions" + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {gemini_key}" + } + model = "gemini-1.5-flash" + else: + url = "https://api.openai.com/v1/chat/completions" + headers = { + "Content-Type": "application/json", + "Authorization": f"Bearer {openai_key}" + } + model = "gpt-4o-mini" + + payload = { + "model": model, + "messages": messages, + } + + if response_format: + payload["response_format"] = response_format + + if tools: + payload["tools"] = tools + + response = None + for attempt in range(3): + # 1. Try OpenAI-compatible endpoint + response = _chat_completion_openai_compat(url, headers, model, payload, attempt) + if response: + break + + # 2. If it's Gemini and compat endpoint fails, try Native Gemini API + if provider == "gemini" and gemini_key: + logger.info("Attempting fallback to Gemini native endpoint...") + response = _chat_completion_gemini_native(messages, gemini_key, response_format) + if response: + break + + # Retry wait with exponential backoff + time.sleep(2 ** (attempt + 1)) + + if not response: + return None + + try: + content = response["choices"][0]["message"]["content"] + usage = response.get("usage", {}) + prompt_tokens = usage.get("prompt_tokens", 0) + completion_tokens = usage.get("completion_tokens", 0) + + TOTAL_TOKENS_USED += (prompt_tokens + completion_tokens) + cost = estimate_cost(prompt_tokens, completion_tokens, provider) + TOTAL_COST_USD += cost + + return { + "content": content, + "provider": provider, + "available": True, + "usage": { + "prompt_tokens": prompt_tokens, + "completion_tokens": completion_tokens, + "total_tokens": prompt_tokens + completion_tokens, + "cost_usd": cost + } + } + except Exception as e: + logger.error(f"Error parsing final LLM response dict: {e}") + return None diff --git a/external/Quant.ai/backend/app/patterns.py b/external/Quant.ai/backend/app/patterns.py new file mode 100644 index 0000000000000000000000000000000000000000..a06e07d175ec91d32174a0f7e8db1d5114f08383 --- /dev/null +++ b/external/Quant.ai/backend/app/patterns.py @@ -0,0 +1,321 @@ +# backend/app/patterns.py + +import pandas as pd +import numpy as np + +def detect_candlestick_patterns(df): + """ + 检测 K 线数值特征与 22 种 K 线及形态模式: + - Feature Columns: + 'range', 'body', 'body_ratio', 'upper_shadow', 'lower_shadow', + 'upper_ratio', 'lower_ratio', 'gap_up', 'gap_down', + 'trend_up_ctx', 'trend_down_ctx', 'rv' + + - Pattern Columns: + 'Pattern_Long_Bull', 'Pattern_Long_Bear', 'Pattern_Doji', 'Pattern_Hammer', + 'Pattern_Hanging_Man', 'Pattern_Inverted_Hammer', 'Pattern_Shooting_Star', + 'Pattern_Marubozu', 'Pattern_Spinning_Top', 'Pattern_Bullish_Engulfing', + 'Pattern_Bearish_Engulfing', 'Pattern_Piercing', 'Pattern_Dark_Cloud_Cover', + 'Pattern_Harami', 'Pattern_Morning_Star', 'Pattern_Evening_Star', + 'Pattern_Three_White_Soldiers', 'Pattern_Three_Black_Crows', + 'Pattern_Rising_Three_Methods', 'Pattern_Falling_Three_Methods', + 'Pattern_Gap_Breakout', 'Pattern_Exhaustion_Gap' + """ + df = df.copy() + + # 避免行数太少报错 + if len(df) < 5: + # 填充默认的列 + for col in [ + 'range', 'body', 'body_ratio', 'upper_shadow', 'lower_shadow', + 'upper_ratio', 'lower_ratio', 'gap_up', 'gap_down', + 'trend_up_ctx', 'trend_down_ctx', 'rv', + 'Pattern_Long_Bull', 'Pattern_Long_Bear', 'Pattern_Doji', 'Pattern_Hammer', + 'Pattern_Hanging_Man', 'Pattern_Inverted_Hammer', 'Pattern_Shooting_Star', + 'Pattern_Marubozu', 'Pattern_Spinning_Top', 'Pattern_Bullish_Engulfing', + 'Pattern_Bearish_Engulfing', 'Pattern_Piercing', 'Pattern_Dark_Cloud_Cover', + 'Pattern_Harami', 'Pattern_Morning_Star', 'Pattern_Evening_Star', + 'Pattern_Three_White_Soldiers', 'Pattern_Three_Black_Crows', + 'Pattern_Rising_Three_Methods', 'Pattern_Falling_Three_Methods', + 'Pattern_Gap_Breakout', 'Pattern_Exhaustion_Gap' + ]: + df[col] = False + return df + + o = df['Open'] + h = df['High'] + l = df['Low'] + c = df['Close'] + v = df['Volume'] + + eps = 1e-8 + + # 1. 计算基础数值特征 + df['range'] = h - l + df['body'] = (c - o).abs() + df['body_ratio'] = df['body'] / np.maximum(df['range'], eps) + df['upper_shadow'] = h - np.maximum(o, c) + df['lower_shadow'] = np.minimum(o, c) - l + df['upper_ratio'] = df['upper_shadow'] / np.maximum(df['body'], eps) + df['lower_ratio'] = df['lower_shadow'] / np.maximum(df['body'], eps) + df['gap_up'] = l > h.shift(1) + df['gap_down'] = h < l.shift(1) + + # 计算趋势上下文 (20日/分钟 EMA vs 50日/分钟 EMA) + ema20 = c.ewm(span=20, adjust=False).mean() + ema50 = c.ewm(span=50, adjust=False).mean() + + # slope(ema20, 5) using 5-period linear regression slope + slope_ema20 = (2 * ema20 + ema20.shift(1) - ema20.shift(3) - 2 * ema20.shift(4)) / 10.0 + + df['trend_up_ctx'] = (ema20 > ema50) & (slope_ema20 > 0) + df['trend_down_ctx'] = (ema20 < ema50) & (slope_ema20 < 0) + + # rv (Relative Volume) + df['rv'] = v / np.maximum(v.rolling(window=20, min_periods=1).mean(), eps) + + # 快捷变量,方便编写条件 + bull = c > o + bear = c < o + body_ratio = df['body_ratio'] + upper_ratio = df['upper_ratio'] + lower_ratio = df['lower_ratio'] + trend_up_ctx = df['trend_up_ctx'] + trend_down_ctx = df['trend_down_ctx'] + gap_up = df['gap_up'] + gap_down = df['gap_down'] + rv = df['rv'] + + # 2. 单K线与常规形态识别 + df['Pattern_Long_Bull'] = bull & (body_ratio >= 0.6) & (upper_ratio <= 0.3) & (lower_ratio <= 0.3) + df['Pattern_Long_Bear'] = bear & (body_ratio >= 0.6) & (upper_ratio <= 0.3) & (lower_ratio <= 0.3) + df['Pattern_Doji'] = body_ratio <= 0.1 + df['Pattern_Hammer'] = (lower_ratio >= 2.0) & (upper_ratio <= 0.5) & (body_ratio <= 0.35) & trend_down_ctx + df['Pattern_Hanging_Man'] = (lower_ratio >= 2.0) & (upper_ratio <= 0.5) & (body_ratio <= 0.35) & trend_up_ctx + df['Pattern_Inverted_Hammer'] = (upper_ratio >= 2.0) & (lower_ratio <= 0.5) & (body_ratio <= 0.35) & trend_down_ctx + df['Pattern_Shooting_Star'] = (upper_ratio >= 2.0) & (lower_ratio <= 0.5) & (body_ratio <= 0.35) & trend_up_ctx + df['Pattern_Marubozu'] = (body_ratio >= 0.8) & (upper_ratio <= 0.1) & (lower_ratio <= 0.1) + df['Pattern_Spinning_Top'] = (body_ratio > 0.1) & (body_ratio < 0.35) & (upper_ratio > 0.5) & (lower_ratio > 0.5) + + # 3. 双K线形态识别 + prev_close = c.shift(1) + prev_open = o.shift(1) + + df['Pattern_Bullish_Engulfing'] = (prev_close < prev_open) & bull & (o <= prev_close) & (c >= prev_open) + df['Pattern_Bearish_Engulfing'] = (prev_close > prev_open) & bear & (o >= prev_close) & (c <= prev_open) + + prev_mid = (prev_open + prev_close) / 2 + df['Pattern_Piercing'] = (prev_close < prev_open) & bull & (o < prev_close) & (c >= prev_mid) & (c < prev_open) + df['Pattern_Dark_Cloud_Cover'] = (prev_close > prev_open) & bear & (o > prev_close) & (c <= prev_mid) & (c > prev_open) + + curr_body_high = np.maximum(o, c) + curr_body_low = np.minimum(o, c) + prev_body_high = np.maximum(prev_open, prev_close) + prev_body_low = np.minimum(prev_open, prev_close) + df['Pattern_Harami'] = (curr_body_low >= prev_body_low) & (curr_body_high <= prev_body_high) + + # 4. 三日及多日形态识别 + # shift values for Day 1 (t-2) and Day 2 (t-1) + b1_open, b1_close = o.shift(2), c.shift(2) + b1_body = df['body'].shift(2) + b1_range = df['range'].shift(2) + b1_body_ratio = b1_body / np.maximum(b1_range, eps) + b1_bear = b1_close < b1_open + b1_bull = b1_close > b1_open + + b2_open, b2_close = o.shift(1), c.shift(1) + b2_body = df['body'].shift(1) + b2_range = df['range'].shift(1) + b2_body_ratio = b2_body / np.maximum(b2_range, eps) + + # 启明星 + first_big_down = b1_bear & (b1_body_ratio >= 0.6) + second_small = b2_body_ratio <= 0.25 + third_big_up = bull & (body_ratio >= 0.6) + reclaim = c >= (b1_open + b1_close) / 2 + df['Pattern_Morning_Star'] = first_big_down & second_small & third_big_up & reclaim + + # 黄昏星 + first_big_up = b1_bull & (b1_body_ratio >= 0.6) + third_big_down = bear & (body_ratio >= 0.6) + decline = c <= (b1_open + b1_close) / 2 + df['Pattern_Evening_Star'] = first_big_up & second_small & third_big_down & decline + + # 红三兵 + df['Pattern_Three_White_Soldiers'] = ( + b1_bull & (b2_close > b2_open) & bull & + (c > b2_close) & (b2_close > b1_close) & + (b2_open >= b1_open) & (b2_open <= b1_close) & + (o >= b2_open) & (o <= b2_close) + ) + + # 三只乌鸦 + df['Pattern_Three_Black_Crows'] = ( + b1_bear & (b2_close < b2_open) & bear & + (c < b2_close) & (b2_close < b1_close) & + (b2_open <= b1_open) & (b2_open >= b1_close) & + (o <= b2_open) & (o >= b2_close) + ) + + # 上升三法 / 下降三法 (5日模式) + c4, o4, h4, l4 = c.shift(4), o.shift(4), h.shift(4), l.shift(4) + c3, o3, h3, l3 = c.shift(3), o.shift(3), h.shift(3), l.shift(3) + c2, o2, h2, l2 = c.shift(2), o.shift(2), h.shift(2), l.shift(2) + c1, o1, h1, l1 = c.shift(1), o.shift(1), h.shift(1), l.shift(1) + + # 上升三法 + day1_up = (c4 > o4) & ((c4 - o4) / np.maximum(h4 - l4, eps) >= 0.5) + day234_inside_up = ( + (l3 > l4) & (h3 < h4) & (abs(c3-o3) < (c4-o4)*0.5) & + (l2 > l4) & (h2 < h4) & (abs(c2-o2) < (c4-o4)*0.5) & + (l1 > l4) & (h1 < h4) & (abs(c1-o1) < (c4-o4)*0.5) + ) + day5_up = (c > o) & (c > c4) & ((c - o) / np.maximum(h - l, eps) >= 0.5) + df['Pattern_Rising_Three_Methods'] = day1_up & day234_inside_up & day5_up + + # 下降三法 + day1_dn = (c4 < o4) & ((o4 - c4) / np.maximum(h4 - l4, eps) >= 0.5) + day234_inside_dn = ( + (l3 > l4) & (h3 < h4) & (abs(c3-o3) < (o4-c4)*0.5) & + (l2 > l4) & (h2 < h4) & (abs(c2-o2) < (o4-c4)*0.5) & + (l1 > l4) & (h1 < h4) & (abs(c1-o1) < (o4-c4)*0.5) + ) + day5_dn = (c < o) & (c < c4) & ((o - c) / np.maximum(h - l, eps) >= 0.5) + df['Pattern_Falling_Three_Methods'] = day1_dn & day234_inside_dn & day5_dn + + # 5. 缺口与突破模式 + df['Pattern_Gap_Breakout'] = gap_up & (rv >= 1.5) & trend_up_ctx + df['Pattern_Exhaustion_Gap'] = (gap_up & (rv >= 1.5) & bear) | (gap_down & (rv >= 1.5) & bull) + + return df + +def detect_double_tops_bottoms(df, window=5, threshold=0.015): + """ + 检测 M顶 (Double Top) 与 W底 (Double Bottom) + + 参数: + - window: 局部最高/最低点寻找的窗口宽度 + - threshold: 两个波峰/波谷价格差异的百分比上限 (默认 1.5%) + + 返回: + - 'Pattern_M_Top': bool (在颈线跌破点标记为 True) + - 'Pattern_W_Bottom': bool (在颈线突破点标记为 True) + - 'M_Neckline': float (记录颈线价格,没有则为 NaN) + - 'W_Neckline': float (记录颈线价格,没有则为 NaN) + """ + df = df.copy() + df['Pattern_M_Top'] = False + df['Pattern_W_Bottom'] = False + df['M_Neckline'] = np.nan + df['W_Neckline'] = np.nan + + if len(df) < window * 4: + return df + + close = df['Close'].values + high = df['High'].values + low = df['Low'].values + + # 1. 寻找局部波峰(Peaks)与波谷(Troughs) + peaks = [] # 元素格式: (index, price) + troughs = [] # 元素格式: (index, price) + + for i in range(window, len(df) - window): + # 局部高点判定 + is_peak = True + for w in range(1, window + 1): + if high[i] < high[i-w] or high[i] < high[i+w]: + is_peak = False + break + if is_peak: + peaks.append((i, float(high[i]))) + + # 局部低点判定 + is_trough = True + for w in range(1, window + 1): + if low[i] > low[i-w] or low[i] > low[i+w]: + is_trough = False + break + if is_trough: + troughs.append((i, float(low[i]))) + + # 2. 识别 M 顶 (双顶) + # 两峰 P1(t1) 与 P2(t2),中间夹着一谷 T(t_mid) + # 颈线为 T 的最低价。当价格跌破颈线时,确认 M 顶。 + for p_idx in range(len(peaks) - 1): + t1, p1 = peaks[p_idx] + t2, p2 = peaks[p_idx + 1] + + # 两个峰高度相差在阈值内 + if abs(p1 - p2) / max(p1, p2) <= threshold: + # 寻找两个峰之间的最低点(谷底) + t_mid_candidates = [t for t in troughs if t1 < t[0] < t2] + if t_mid_candidates: + # 颈线点取两峰之间最低的那个谷底值 + t_neck, p_neck = min(t_mid_candidates, key=lambda x: x[1]) + + # 寻找 t2 之后,价格首次跌破 p_neck 的时刻 + # 为防止在历史中过早标出,我们检查 t2 之后的收盘价 + for i in range(t2, len(df)): + # 如果中间价格又向上突破了双顶最高价,则该形态失效 + limit_high = max(p1, p2) * 1.01 + if close[i] > limit_high: + break + # 如果跌破颈线 + if close[i] < p_neck: + # 只在跌破的那一分钟标记 True + df.iloc[i, df.columns.get_loc('Pattern_M_Top')] = True + df.iloc[i, df.columns.get_loc('M_Neckline')] = p_neck + break + + # 3. 识别 W 底 (双底) + # 两谷 T1(t1) 与 T2(t2),中间夹着一峰 P(t_mid) + # 颈线为 P 的最高价。当价格突破颈线时,确认 W 底。 + for t_idx in range(len(troughs) - 1): + t1, tr1 = troughs[t_idx] + t2, tr2 = troughs[t_idx + 1] + + # 两个谷底相差在阈值内 + if abs(tr1 - tr2) / max(tr1, tr2) <= threshold: + # 寻找两个谷之间的最高点(峰顶) + p_mid_candidates = [p for p in peaks if t1 < p[0] < t2] + if p_mid_candidates: + t_neck, p_neck = max(p_mid_candidates, key=lambda x: x[1]) + + # 寻找 t2 之后,价格首次突破 p_neck 的时刻 + for i in range(t2, len(df)): + # 如果中间价格跌破了双底最低价,则形态失效 + limit_low = min(tr1, tr2) * 0.99 + if close[i] < limit_low: + break + # 如果突破颈线 + if close[i] > p_neck: + df.iloc[i, df.columns.get_loc('Pattern_W_Bottom')] = True + df.iloc[i, df.columns.get_loc('W_Neckline')] = p_neck + break + + return df + +def analyze_patterns(df): + """ + 一键运行所有形态检测,合并返回 + """ + df = detect_candlestick_patterns(df) + df = detect_double_tops_bottoms(df) + return df + +if __name__ == "__main__": + print("Testing patterns.py...") + # Create a dummy dataframe with OHLCV data + dates = pd.date_range("2026-06-01", periods=10) + data = { + "Open": [100.0, 102.0, 101.0, 105.0, 104.0, 106.0, 107.0, 105.0, 108.0, 110.0], + "High": [103.0, 104.0, 102.0, 106.0, 105.0, 107.0, 108.0, 106.0, 109.0, 112.0], + "Low": [99.0, 101.0, 100.0, 104.0, 103.0, 105.0, 106.0, 104.0, 107.0, 109.0], + "Close": [102.0, 101.5, 101.8, 104.5, 104.2, 106.8, 105.5, 104.8, 108.5, 111.0], + "Volume": [1000, 1500, 1200, 2000, 1100, 1300, 900, 1400, 2200, 3000] + } + df_test = pd.DataFrame(data, index=dates) + res = analyze_patterns(df_test) + print("Columns in result:", res.columns.tolist()) + print("\nFirst row features:\n", res.iloc[-1]) diff --git a/external/Quant.ai/backend/app/risk_analyst.py b/external/Quant.ai/backend/app/risk_analyst.py new file mode 100644 index 0000000000000000000000000000000000000000..dfdbbc2f5984d647384d6a7ae056b4e348c11a6f --- /dev/null +++ b/external/Quant.ai/backend/app/risk_analyst.py @@ -0,0 +1,323 @@ +# backend/app/risk_analyst.py +""" +AI Risk Analyst Module — Post-backtest analysis and risk report generation. +Analyzes drawdowns, regime performance, parameter sensitivity, transaction costs, and overfitting risk. +""" + +import numpy as np + + +def generate_risk_report(backtest_result: dict, strategy_config: dict) -> dict: + """ + Generate a comprehensive risk analysis report from backtest results. + Returns structured JSON that includes both data points and natural language insights. + """ + ticker = strategy_config.get("ticker", "UNKNOWN") + interval = strategy_config.get("interval", "1d") + strategy_mode = strategy_config.get("strategy_mode", "dynamic") + + summary = { + "net_pnl": backtest_result.get("net_pnl", 0), + "pnl_pct": backtest_result.get("pnl_pct", 0), + "max_drawdown": backtest_result.get("max_drawdown", 0), + "sharpe": backtest_result.get("sharpe", 0), + "calmar": backtest_result.get("calmar", 0), + "cagr": backtest_result.get("cagr", 0), + "profit_factor": backtest_result.get("profit_factor", 0), + "win_rate": backtest_result.get("win_rate", 0), + "round_trips": backtest_result.get("round_trips", 0), + "commission": backtest_result.get("commission", 0), + } + + # Build analysis sections + sections = [] + + # 1. Performance Overview + sections.append(_analyze_performance(summary, ticker, strategy_mode, interval)) + + # 2. Risk Assessment + sections.append(_analyze_risk(summary, backtest_result)) + + # 3. Regime Analysis + sections.append(_analyze_regimes(backtest_result)) + + # 4. Transaction Cost Impact + sections.append(_analyze_costs(summary, backtest_result)) + + # 5. Strategy Recommendations + sections.append(_generate_recommendations(summary, backtest_result, strategy_config)) + + # Overall risk score (0-100, lower is riskier) + risk_score = _compute_risk_score(summary) + + return { + "ticker": ticker, + "strategy": strategy_mode, + "interval": interval, + "risk_score": risk_score, + "sections": sections, + "key_metrics": summary, + } + + +def _analyze_performance(summary, ticker, strategy, interval): + """Analyze overall performance""" + pnl = summary["net_pnl"] + pnl_pct = summary["pnl_pct"] + sharpe = summary["sharpe"] + calmar = summary["calmar"] + win_rate = summary["win_rate"] + profit_factor = summary["profit_factor"] + + insights = [] + + # PnL assessment + if pnl > 0: + insights.append(f"The {strategy} strategy on {ticker} ({interval}) generated a **positive return** of ${pnl:,.2f} ({pnl_pct:+.2f}%).") + else: + insights.append(f"The {strategy} strategy on {ticker} ({interval}) resulted in a **net loss** of ${pnl:,.2f} ({pnl_pct:+.2f}%). Consider revising parameters or strategy selection.") + + # Sharpe assessment + if sharpe > 2.0: + insights.append(f"Sharpe Ratio of {sharpe:.2f} is **excellent** — strong risk-adjusted returns.") + elif sharpe > 1.0: + insights.append(f"Sharpe Ratio of {sharpe:.2f} is **good** — above-average risk-adjusted performance.") + elif sharpe > 0: + insights.append(f"Sharpe Ratio of {sharpe:.2f} is **marginal** — returns barely compensate for volatility.") + else: + insights.append(f"Sharpe Ratio of {sharpe:.2f} is **negative** — the strategy underperformed risk-free rate.") + + # Win rate vs Profit Factor balance + if win_rate > 60 and profit_factor > 1.5: + insights.append(f"Win rate {win_rate:.1f}% with profit factor {profit_factor:.2f} indicates a **robust edge**.") + elif win_rate < 40 and profit_factor < 1.0: + insights.append(f"Low win rate ({win_rate:.1f}%) combined with profit factor below 1.0 ({profit_factor:.2f}) suggests **no statistical edge**.") + elif win_rate < 45: + if profit_factor > 1.5: + insights.append(f"Despite low win rate ({win_rate:.1f}%), profit factor of {profit_factor:.2f} shows winners are significantly larger than losers — typical of trend-following systems.") + else: + insights.append(f"Win rate of {win_rate:.1f}% is below average. Consider tighter entry filters or regime-based filtering.") + + return { + "title": "Performance Overview", + "icon": "📊", + "insights": insights, + "severity": "positive" if pnl > 0 else "negative" + } + + +def _analyze_risk(summary, backtest_result): + """Analyze risk metrics""" + max_dd = summary["max_drawdown"] + calmar = summary["calmar"] + insights = [] + + # Max drawdown severity + dd_pct = max_dd * 100 + if dd_pct > 20: + insights.append(f"**⚠️ Critical**: Maximum drawdown reached **{dd_pct:.1f}%** — this exceeds institutional risk tolerance (typically 10-15%). A drawdown of this magnitude can be psychologically devastating and may trigger forced liquidation.") + elif dd_pct > 10: + insights.append(f"Maximum drawdown of **{dd_pct:.1f}%** is **elevated** but within acceptable bounds for aggressive strategies. The soft drawdown circuit breaker (7%) was likely triggered during this period.") + elif dd_pct > 5: + insights.append(f"Maximum drawdown of **{dd_pct:.1f}%** is **moderate** — well within the hard drawdown limit (12%).") + else: + insights.append(f"Maximum drawdown of **{dd_pct:.1f}%** is **minimal** — excellent capital preservation.") + + # Calmar assessment + if calmar > 3: + insights.append(f"Calmar Ratio of {calmar:.2f} is **outstanding** — return per unit of drawdown risk is very high.") + elif calmar > 1: + insights.append(f"Calmar Ratio of {calmar:.2f} is **acceptable** — return compensates for drawdown risk.") + elif calmar > 0: + insights.append(f"Calmar Ratio of {calmar:.2f} is **poor** — drawdown pain may not justify the returns.") + + # Consecutive loss analysis + ledger = backtest_result.get("ledger", []) + sell_trades = [t for t in ledger if t.get("action") == "SELL"] + max_consecutive_loss = 0 + current_streak = 0 + for t in sell_trades: + if t.get("realized_pnl", 0) < 0: + current_streak += 1 + max_consecutive_loss = max(max_consecutive_loss, current_streak) + else: + current_streak = 0 + + if max_consecutive_loss >= 5: + insights.append(f"**⚠️ Warning**: Maximum consecutive losing streak was **{max_consecutive_loss} trades** — this would trigger the consecutive-loss risk reduction (threshold: 5).") + elif max_consecutive_loss >= 3: + insights.append(f"Maximum consecutive losing streak: {max_consecutive_loss} trades — within normal variance.") + + return { + "title": "Risk Assessment", + "icon": "🛡️", + "insights": insights, + "severity": "warning" if dd_pct > 10 else "positive" + } + + +def _analyze_regimes(backtest_result): + """Analyze performance across market regimes""" + regime_breakdown = backtest_result.get("regime_breakdown", []) + regime_distribution = backtest_result.get("regime_distribution", {}) + insights = [] + + if not regime_breakdown: + insights.append("No regime-specific trade data available. The strategy may not have generated trades across different market conditions.") + return { + "title": "Market Regime Analysis", + "icon": "🚦", + "insights": insights, + "severity": "neutral" + } + + # Identify best and worst performing regimes + best_regime = max(regime_breakdown, key=lambda x: x["total_pnl"]) if regime_breakdown else None + worst_regime = min(regime_breakdown, key=lambda x: x["total_pnl"]) if regime_breakdown else None + + if best_regime: + insights.append(f"**Best performing regime**: `{best_regime['regime']}` — ${best_regime['total_pnl']:+,.2f} across {best_regime['trade_count']} trades ({best_regime['win_rate']:.0f}% win rate).") + + if worst_regime and worst_regime["total_pnl"] < 0: + insights.append(f"**Worst performing regime**: `{worst_regime['regime']}` — ${worst_regime['total_pnl']:+,.2f} across {worst_regime['trade_count']} trades ({worst_regime['win_rate']:.0f}% win rate).") + + # Regime distribution context + if regime_distribution: + dominant_regime = max(regime_distribution.items(), key=lambda x: x[1]) + insights.append(f"Market spent **{dominant_regime[1]:.0f}%** of the time in `{dominant_regime[0]}` regime.") + + # Check for regime concentration risk + for rb in regime_breakdown: + if rb["trade_count"] == 0: + continue + if rb["win_rate"] < 30 and rb["trade_count"] >= 3: + insights.append(f"**⚠️ Caution**: Strategy has only {rb['win_rate']:.0f}% win rate in `{rb['regime']}` regime — consider disabling trading in this market condition.") + + return { + "title": "Market Regime Analysis", + "icon": "🚦", + "insights": insights, + "severity": "neutral" + } + + +def _analyze_costs(summary, backtest_result): + """Analyze transaction cost impact""" + commission = summary["commission"] + gross_profit = backtest_result.get("gross_profit", 0) + gross_loss = backtest_result.get("gross_loss", 0) + net_pnl = summary["net_pnl"] + round_trips = summary["round_trips"] + insights = [] + + # Commission as % of gross profit + total_gross = gross_profit + abs(gross_loss) if gross_profit > 0 else 1 + commission_ratio = (commission / max(abs(net_pnl), 1)) * 100 if net_pnl != 0 else 0 + + if commission > abs(net_pnl) and net_pnl > 0: + insights.append(f"**⚠️ Critical**: Transaction costs (${commission:,.2f}) exceed net profit (${net_pnl:,.2f}) — the strategy may not survive real trading friction. Consider reducing trade frequency or increasing position hold time.") + elif commission_ratio > 50: + insights.append(f"Transaction costs consume **{commission_ratio:.0f}%** of net PnL — this is dangerously high. Each unnecessary round trip costs approximately ${commission/max(round_trips, 1):.2f}.") + elif commission_ratio > 20: + insights.append(f"Transaction costs account for **{commission_ratio:.0f}%** of net PnL (${commission:,.2f}) — moderate friction. Monitor cost sensitivity.") + else: + insights.append(f"Transaction costs (${commission:,.2f}) are **well-controlled** relative to performance — {commission_ratio:.0f}% of net PnL.") + + # Cost per round trip + if round_trips > 0: + cost_per_trip = commission / round_trips + insights.append(f"Average cost per round trip: **${cost_per_trip:.2f}** (commission only, excluding slippage).") + + return { + "title": "Transaction Cost Impact", + "icon": "💰", + "insights": insights, + "severity": "warning" if commission_ratio > 50 else "positive" + } + + +def _generate_recommendations(summary, backtest_result, strategy_config): + """Generate actionable recommendations""" + insights = [] + + pnl = summary["net_pnl"] + max_dd = summary["max_drawdown"] + win_rate = summary["win_rate"] + sharpe = summary["sharpe"] + round_trips = summary["round_trips"] + + # Strategy-specific advice + if round_trips == 0: + insights.append("**No trades were executed** — the entry conditions may be too restrictive. Consider loosening RSI thresholds, reducing ADX trend requirements, or switching to a less filtered strategy mode.") + elif round_trips < 3: + insights.append(f"Only {round_trips} round trips — insufficient sample size for statistical significance. Extend the backtest period or test on additional tickers.") + + if pnl > 0 and sharpe > 0.5: + insights.append("**Next steps**: Run walk-forward optimization to validate out-of-sample performance. Test parameter sensitivity by varying ATR multiplier ±0.5 and RSI threshold ±10.") + + if max_dd > 0.15: + insights.append("**Risk reduction**: Consider lowering `risk_per_trade_pct` from current value or tightening the hard drawdown limit. A 15%+ drawdown on a $30K account means a $4,500 paper loss.") + + if win_rate < 40 and pnl < 0: + insights.append("**Strategy pivot**: Low win rate with negative PnL suggests the strategy lacks edge in this market condition. Try: (1) switching to mean reversion in range-bound markets, (2) adding volume confirmation filters, or (3) testing on a different ticker with stronger trends.") + + if win_rate > 55 and pnl > 0: + insights.append("**Overfitting warning**: High win rate + positive PnL should be validated out-of-sample. Run walk-forward optimization before trusting these results.") + + # Always recommend + insights.append("**Standard validation checklist**: (1) Walk-forward optimization, (2) Cost stress test (2x-3x slippage), (3) Monte Carlo simulation of trade order, (4) Test on correlated but different tickers.") + + return { + "title": "Recommendations & Next Steps", + "icon": "🔬", + "insights": insights, + "severity": "neutral" + } + + +def _compute_risk_score(summary): + """ + Compute a composite risk score from 0-100 (higher = better/safer). + """ + score = 50 # Start neutral + + # PnL contribution (±15) + if summary["pnl_pct"] > 5: + score += 15 + elif summary["pnl_pct"] > 0: + score += 8 + elif summary["pnl_pct"] > -5: + score -= 5 + else: + score -= 15 + + # Sharpe contribution (±15) + if summary["sharpe"] > 2: + score += 15 + elif summary["sharpe"] > 1: + score += 10 + elif summary["sharpe"] > 0: + score += 3 + else: + score -= 10 + + # Drawdown penalty (±10) + dd_pct = summary["max_drawdown"] * 100 + if dd_pct < 5: + score += 10 + elif dd_pct < 10: + score += 5 + elif dd_pct > 20: + score -= 15 + elif dd_pct > 15: + score -= 10 + + # Win rate contribution (±10) + if summary["win_rate"] > 60: + score += 10 + elif summary["win_rate"] > 45: + score += 5 + elif summary["win_rate"] < 30: + score -= 10 + + return max(0, min(100, score)) diff --git a/external/Quant.ai/backend/app/simulator.py b/external/Quant.ai/backend/app/simulator.py new file mode 100644 index 0000000000000000000000000000000000000000..60e1041806de24d98b65d034356c864472d00507 --- /dev/null +++ b/external/Quant.ai/backend/app/simulator.py @@ -0,0 +1,304 @@ +# backend/app/simulator.py + +import pandas as pd +import numpy as np +import datetime +from app.config import INITIAL_CASH, FORCE_LIQUIDATION_TIME, SOFT_DRAWDOWN_LIMIT, HARD_DRAWDOWN_LIMIT, MAX_CONSECUTIVE_LOSSES, FORCE_LIQUIDATION_OPEN_FOCUS +from app.trading_engine import Portfolio +from app.strategy import evaluate_market_state + +def run_backtest_sim(df, ticker, strategy_params, risk_params, is_intraday=True): + """ + 通用回测执行引擎,支持日内 (is_intraday=True) 和日线 (is_intraday=False) 级别回测。 + 增强输出:regime_breakdown, drawdown_curve, Sharpe, Calmar, CAGR, Profit Factor + """ + df = df.copy() + if is_intraday: + # Precompute ORB (Opening Range Breakout) High/Low for each day + # Range is defined between 9:30 and 9:35 (first 5 minutes of regular trading hours) + df['Time'] = df.index.time + df['Date'] = df.index.date + + import datetime as dt_mod + open_mask = (df['Time'] >= dt_mod.time(9, 30)) & (df['Time'] <= dt_mod.time(9, 35)) + opening_df = df[open_mask] + + if not opening_df.empty: + orb_high = opening_df.groupby('Date')['High'].max().to_dict() + orb_low = opening_df.groupby('Date')['Low'].min().to_dict() + df['ORB_High'] = df['Date'].map(orb_high).fillna(0.0) + df['ORB_Low'] = df['Date'].map(orb_low).fillna(0.0) + else: + df['ORB_High'] = 0.0 + df['ORB_Low'] = 0.0 + + portfolio = Portfolio( + initial_cash=INITIAL_CASH, + slippage_rate=risk_params.get("slippage_rate", 0.0003), + commission_per_share=risk_params.get("commission_per_share", 0.005), + min_commission_per_order=risk_params.get("min_commission_per_order", 1.0) + ) + + # 提取账户风控限制 + soft_dd = risk_params.get("soft_dd", SOFT_DRAWDOWN_LIMIT) + hard_dd = risk_params.get("hard_dd", HARD_DRAWDOWN_LIMIT) + max_consecutive_losses = risk_params.get("max_consecutive_losses", MAX_CONSECUTIVE_LOSSES) + + # 提取开盘突击模式参数,默认是 True + market_open_focus = strategy_params.get("market_open_focus", True) + + equity_curve = [] + + # 记录每笔交易所处的 regime(用于 regime breakdown) + trade_regime_map = {} # buy_timestamp -> regime + + # 我们从第2行开始,因为策略需要 prev_row 进行对比 + for i in range(1, len(df)): + row = df.iloc[i] + prev_row = df.iloc[i-1] + timestamp = df.index[i] + time_str = timestamp.strftime("%H:%M") + + close_price = float(row['Close']) + current_prices = {ticker: close_price} + + shares = portfolio.get_position_shares(ticker) + avg_cost = portfolio.get_position_avg_cost(ticker) + + # 1. 账户级风控指标更新 (含最高权益及回撤计算) + equity = portfolio.get_equity(current_prices) + portfolio.peak_equity = max(portfolio.peak_equity, equity) + drawdown_pct = (portfolio.peak_equity - equity) / portfolio.peak_equity if portfolio.peak_equity > 0 else 0.0 + + # 统计最近 SELL 操作的 realized_pnl + sell_trades = [t for t in portfolio.ledger if t['action'] == 'SELL'] + consecutive_losses = 0 + for t in reversed(sell_trades): + if t.get('realized_pnl', 0.0) < 0: + consecutive_losses += 1 + else: + break + portfolio.consecutive_losses = consecutive_losses + + # 2. 判定硬/软熔断并更新 risk_multiplier + if drawdown_pct >= hard_dd: + portfolio.risk_multiplier = 0.0 + elif drawdown_pct >= soft_dd or consecutive_losses >= max_consecutive_losses: + portfolio.risk_multiplier = 0.5 + else: + portfolio.risk_multiplier = 1.0 + + # 3. 更新追踪止损的最高价 + if shares > 0: + portfolio.update_highest_price(ticker, close_price) + + highest_price = portfolio.get_position_highest_price(ticker) + + # 记录资产曲线数据 + equity_curve.append({ + "time": int(timestamp.timestamp()), + "value": round(equity, 2) + }) + + # 4. 日内清仓检测 (仅限 1分钟、5分钟等日内级别) + liq_time = FORCE_LIQUIDATION_OPEN_FOCUS if market_open_focus else FORCE_LIQUIDATION_TIME + if is_intraday and time_str == liq_time and shares > 0: + portfolio.sell(timestamp, ticker, close_price, shares) + continue + + # 5. 执行常规策略评估 + is_trading_window = True + if is_intraday: + if market_open_focus: + # 开盘突击:只在 9:35 - 10:15 之间开新仓 + import datetime as dt_mod + is_trading_window = dt_mod.time(9, 35) <= timestamp.time() <= dt_mod.time(10, 15) + else: + # 日内交易时间窗口:上午 9:35 到 下午 15:54 + is_trading_window = datetime.time(9, 35) <= timestamp.time() < datetime.time(15, 54) + + # 如果我们已经持有仓位,为了检查止损止盈等,任何时间(直到强制平仓前)都是交易窗口 + if shares > 0: + is_trading_window = True + if is_trading_window: + current_regime = row.get('Regime', 'range_bound') + + action, explanation = evaluate_market_state( + row, prev_row, shares, avg_cost, ticker, highest_price, strategy_params + ) + + if action == "BUY" and shares == 0: + # 仓位计算 + if risk_params.get("position_sizing_mode", "atr") == "atr": + shares_to_buy = portfolio.calculate_position_size( + ticker, close_price, row['ATR'], + risk_pct=risk_params.get("risk_per_trade_pct", 0.01), + atr_multiplier=strategy_params.get("trailing_stop_atr_mult", 2.0), + max_size_pct=risk_params.get("max_position_size_pct", 0.50) + ) + else: + target_allocation = equity * risk_params.get("max_position_size_pct", 0.50) + shares_to_buy = int(target_allocation / close_price) + + if shares_to_buy > 0: + portfolio.buy(timestamp, ticker, close_price, shares_to_buy) + # 记录买入时的 regime + trade_regime_map[str(timestamp)] = current_regime + + elif action == "SELL" and shares > 0: + portfolio.sell(timestamp, ticker, close_price, shares) + + # 6. 计算回测指标 + total_trades = len(portfolio.ledger) + final_equity = portfolio.get_equity({ticker: df.iloc[-1]['Close']}) + net_pnl = final_equity - INITIAL_CASH + pnl_pct = (net_pnl / INITIAL_CASH) * 100 + + sell_trades = [t for t in portfolio.ledger if t['action'] == 'SELL'] + winning_trades = [t for t in sell_trades if t.get('realized_pnl', 0.0) > 0] + losing_trades = [t for t in sell_trades if t.get('realized_pnl', 0.0) < 0] + win_rate = (len(winning_trades) / len(sell_trades)) * 100 if sell_trades else 0.0 + + total_commission = sum(t['commission'] for t in portfolio.ledger) + + # 统计最大回撤与 drawdown curve + eq_vals = [e["value"] for e in equity_curve] + max_drawdown = 0.0 + drawdown_curve = [] + if eq_vals: + peaks = np.maximum.accumulate(eq_vals) + drawdowns = (peaks - eq_vals) / peaks + max_drawdown = float(np.max(drawdowns)) + for idx_ec, ec in enumerate(equity_curve): + drawdown_curve.append({ + "time": ec["time"], + "value": round(float(drawdowns[idx_ec]) * -100, 2) # 负百分比 + }) + + # 7. 高级指标计算 + # Profit Factor = 总盈利 / 总亏损 + gross_profit = sum(t.get('realized_pnl', 0.0) for t in winning_trades) + gross_loss = abs(sum(t.get('realized_pnl', 0.0) for t in losing_trades)) + profit_factor = round(gross_profit / max(gross_loss, 1e-8), 2) + + # 计算回测跨度的交易日数 + if len(df) >= 2: + start_date = df.index[0] + end_date = df.index[-1] + total_days = (end_date - start_date).days + total_years = total_days / 365.25 if total_days > 0 else 1.0 / 365.25 + else: + total_years = 1.0 / 365.25 + + # CAGR = (Final/Initial)^(1/years) - 1 + if final_equity > 0 and INITIAL_CASH > 0 and total_years > 0: + cagr = (final_equity / INITIAL_CASH) ** (1.0 / max(total_years, 0.01)) - 1.0 + else: + cagr = 0.0 + + # Sharpe Ratio (基于日/bar收益序列,假设 risk-free = 0) + if len(eq_vals) > 1: + returns = np.diff(eq_vals) / np.array(eq_vals[:-1]) + if np.std(returns) > 0: + # 年化 Sharpe(按交易日数年化) + bars_per_year = len(eq_vals) / max(total_years, 0.01) + sharpe = (np.mean(returns) / np.std(returns)) * np.sqrt(bars_per_year) + else: + sharpe = 0.0 + else: + sharpe = 0.0 + + # Calmar Ratio = CAGR / Max Drawdown + calmar = round(cagr / max(max_drawdown, 1e-8), 2) if max_drawdown > 0.001 else 0.0 + + # 8. Regime Breakdown — 统计不同市场状态下交易表现 + regime_breakdown = _compute_regime_breakdown(portfolio.ledger, trade_regime_map) + + # 9. Regime 分布统计 (每个 regime 的 bar 数量占比) + regime_distribution = {} + if 'Regime' in df.columns: + regime_counts = df['Regime'].value_counts() + total_bars = len(df) + for regime_name, count in regime_counts.items(): + regime_distribution[regime_name] = round(count / total_bars * 100, 1) + + return { + "final_equity": round(final_equity, 2), + "net_pnl": round(net_pnl, 2), + "pnl_pct": round(pnl_pct, 2), + "total_trades": total_trades, + "round_trips": len(sell_trades), + "win_rate": round(win_rate, 2), + "commission": round(total_commission, 2), + "max_drawdown": round(max_drawdown, 4), + # 新增高级指标 + "sharpe": round(sharpe, 2), + "calmar": calmar, + "cagr": round(cagr * 100, 2), # 百分比 + "profit_factor": profit_factor, + "gross_profit": round(gross_profit, 2), + "gross_loss": round(gross_loss, 2), + # 数据序列 + "ledger": portfolio.ledger, + "equity_curve": equity_curve, + "drawdown_curve": drawdown_curve, + # Regime 统计 + "regime_breakdown": regime_breakdown, + "regime_distribution": regime_distribution, + } + + +def _compute_regime_breakdown(ledger, trade_regime_map): + """ + 按 regime 汇总交易表现:pnl, win_rate, trade_count + """ + regime_stats = {} + + # 将 BUY/SELL 配对,并查找每对交易的 regime + buy_trades = [t for t in ledger if t['action'] == 'BUY'] + sell_trades = [t for t in ledger if t['action'] == 'SELL'] + + for i, sell in enumerate(sell_trades): + # 每个 sell 与对应的 buy 配对 + if i < len(buy_trades): + buy_ts = buy_trades[i]['timestamp'] + regime = trade_regime_map.get(buy_ts, 'unknown') + else: + regime = 'unknown' + + pnl = sell.get('realized_pnl', 0.0) + + if regime not in regime_stats: + regime_stats[regime] = { + 'total_pnl': 0.0, + 'trade_count': 0, + 'wins': 0, + 'losses': 0, + 'total_commission': 0.0 + } + + regime_stats[regime]['total_pnl'] += pnl + regime_stats[regime]['trade_count'] += 1 + regime_stats[regime]['total_commission'] += sell.get('commission', 0.0) + if pnl > 0: + regime_stats[regime]['wins'] += 1 + else: + regime_stats[regime]['losses'] += 1 + + # 转为前端友好格式 + result = [] + for regime, stats in regime_stats.items(): + win_rate = (stats['wins'] / stats['trade_count'] * 100) if stats['trade_count'] > 0 else 0.0 + result.append({ + "regime": regime, + "total_pnl": round(stats['total_pnl'], 2), + "trade_count": stats['trade_count'], + "win_rate": round(win_rate, 1), + "wins": stats['wins'], + "losses": stats['losses'], + "commission": round(stats['total_commission'], 2) + }) + + # 按 trade_count 降序 + result.sort(key=lambda x: x['trade_count'], reverse=True) + return result diff --git a/external/Quant.ai/backend/app/strategy.py b/external/Quant.ai/backend/app/strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..bba3a5ed5b2b856880f32cb77e3d5e457bc7e4b8 --- /dev/null +++ b/external/Quant.ai/backend/app/strategy.py @@ -0,0 +1,204 @@ +# backend/app/strategy.py + +DEFAULT_PARAMS = { + "stop_loss_pct": 0.01, + "profit_target_pct": 0.015, + "trailing_stop_mode": "atr", + "trailing_stop_atr_mult": 2.0, + "rsi_threshold_buy": 65.0, + "strategy_mode": "dynamic" # dynamic, consensus, ema_cross, breakout, patterns, opening_breakout +} + +def evaluate_market_state(row, prev_row, current_shares, avg_cost, ticker, highest_price=0.0, params=None): + """ + 评估当前 K 线数据,决定交易动作。 + 支持自定义参数和多种策略模式: + - BUY: 满足触发条件,买入做多 + - SELL: 满足止盈、止损、移动追踪止损或破位,卖出平仓 + - HOLD: 无操作 + """ + # 合并默认参数 + p = DEFAULT_PARAMS.copy() + if params: + for k, v in params.items(): + if v is not None: + p[k] = v + + close = row['Close'] + vwap = row['VWAP'] + ema_9 = row['EMA_9'] + ema_21 = row['EMA_21'] + ema_50 = row['EMA_50'] + rsi = row['RSI'] + squeeze = row['Squeeze_On'] + atr = row['ATR'] + + # 提取昨日及盘前关键位 + pmh = row.get('PMH', 0.0) + pdh = row.get('PDH', 0.0) + + # 提取5分钟开盘突击关键位 + orb_high = row.get('ORB_High', 0.0) + orb_low = row.get('ORB_Low', 0.0) + + # 形态标记 (如果存在) + pattern_w = row.get('Pattern_W_Bottom', False) + pattern_m = row.get('Pattern_M_Top', False) + pattern_hammer = row.get('Pattern_Hammer', False) + pattern_shooting = row.get('Pattern_Shooting_Star', False) + pattern_bull_eng = row.get('Pattern_Bullish_Engulfing', False) + pattern_bear_eng = row.get('Pattern_Bearish_Engulfing', False) + + # 新指标与状态分类获取 + regime = row.get('Regime', 'range_bound') + donchian_high = row.get('Donchian_High', 0.0) + donchian_low = row.get('Donchian_Low', 0.0) + rvol = row.get('RVOL', 1.0) + + # ------------------ 状态1:未持有仓位 (寻找买入机会) ------------------ + if current_shares == 0: + # A. 动态状态路由过滤 (Regime Router) + if p["strategy_mode"] == "dynamic": + if regime == "high_volatility": + return "HOLD", "【状态路由】市场处于极端高波动状态,执行风控收缩,保持空仓观望。" + if regime == "trend_down": + return "HOLD", "【状态路由】市场处于下行趋势,做多风险过大,保持空仓防守。" + + # 基础弱势过滤:价格必须在 VWAP 之上(除非是底背离反转模式) + # 这里保留基本 VWAP 顺势法则,除 Patterns 模式和 Dynamic 震荡模式外,其他模式都需要 close >= vwap + is_range_bound = (p["strategy_mode"] == "dynamic" and regime == "range_bound") + if p["strategy_mode"] not in ["patterns", "opening_breakout"] and not is_range_bound and close < vwap: + return "HOLD", "价格处于 VWAP 下方,属于弱势区间,不建仓。" + + # 1. 均线多头排列 + is_bullish_trend = (ema_9 > ema_21) and (ema_21 > ema_50) + + # 2. 均线金叉 (EMA_9 穿过 EMA_21) + prev_ema_9 = prev_row['EMA_9'] + prev_ema_21 = prev_row['EMA_21'] + is_gold_cross = (prev_ema_9 <= prev_ema_21) and (ema_9 > ema_21) + + # 3. 突破盘前/昨日最高点 + prev_close = prev_row['Close'] + is_pmh_breakout = (prev_close <= pmh) and (close > pmh) and (pmh > 0) + is_pdh_breakout = (prev_close <= pdh) and (close > pdh) and (pdh > 0) + + # 4. 回调到 VWAP 支撑区 (0.2% 范围内) + is_near_vwap_support = abs(close - vwap) / vwap <= 0.002 + + # 5. 静态过滤 (仅在非 dynamic 和非 opening_breakout 模式下应用) + if p["strategy_mode"] not in ["dynamic", "opening_breakout"]: + if rsi > p["rsi_threshold_buy"]: + return "HOLD", f"RSI 值为 {rsi:.1f},处于超买区间 (>{p['rsi_threshold_buy']:.0f}),暂不追高。" + if squeeze: + return "HOLD", "市场处于挤压状态 (Squeeze On),暂不建仓。" + + # ---------------- 不同策略模式的买入决策 ---------------- + + # 动态状态路由策略 + if p["strategy_mode"] == "dynamic": + if regime == "trend_up": + # 趋势模式下:检查通道突破或金叉 + # 突破唐奇安通道上轨 且 成交量放大 (RVOL >= 1.2) + if close >= donchian_high and rvol >= 1.2: + return "BUY", f"【动态路由-趋势突破】价格突破唐奇安通道上轨 {donchian_high:.2f} 刀,且 RVOL={rvol:.2f} 量能放大。" + if is_gold_cross: + return "BUY", "【动态路由-趋势金叉】EMA_9 向上穿越 EMA_21 形成金叉,趋势转强。" + elif regime == "range_bound": + # 震荡模式下:检查均值回归或形态反弹 + # 价格跌破布林下轨且RSI超卖 + bb_lower = row.get('BB_Lower', 0.0) + if bb_lower > 0 and close < bb_lower and rsi < 25: + return "BUY", f"【动态路由-均值回归】价格跌破布林下轨 {bb_lower:.2f} 刀且 RSI={rsi:.1f} 超卖,预计将反弹。" + # 底部反转K线形态 + is_bullish_pattern = pattern_w or pattern_hammer or pattern_bull_eng or row.get('Pattern_Morning_Star', False) or row.get('Pattern_Piercing', False) + if is_bullish_pattern: + return "BUY", "【动态路由-底部形态】检测到 W底/锤子线/吞没/启明星 等看涨反转形态。" + + # A. 均线交叉策略 + elif p["strategy_mode"] == "ema_cross": + if is_gold_cross: + return "BUY", f"【EMA金叉买入】EMA_9 向上穿越 EMA_21 形成金叉,多头动能显现。" + + # B. 突破交易策略 + elif p["strategy_mode"] == "breakout": + if is_pmh_breakout and is_bullish_trend: + return "BUY", f"【阻力位突破】股价突破盘前最高位 {pmh:.2f} 刀,且均线呈多头排列。" + if is_pdh_breakout and is_bullish_trend: + return "BUY", f"【阻力位突破】股价突破昨日最高位 {pdh:.2f} 刀,且均线呈多头排列。" + + # C. K线形态策略 + elif p["strategy_mode"] == "patterns": + if pattern_w: + return "BUY", f"【W底反转】检测到双底 (W-Bottom) 形态突破颈线,看涨信号确认。" + if pattern_hammer and is_near_vwap_support: + return "BUY", f"【锤子线买入】在 VWAP 支撑线附近检测到 Hammer (锤子线) 看涨反转形态。" + if pattern_bull_eng and is_near_vwap_support: + return "BUY", f"【吞没看涨】在 VWAP 支撑线附近检测到阳包阴 (Bullish Engulfing) 形态。" + + # D. 共振共识策略 + elif p["strategy_mode"] == "consensus": + if is_gold_cross and is_near_vwap_support: + return "BUY", "【共振回调买入】价格回调至 VWAP 支撑区并触发 9/21 EMA 金叉。" + if (is_pmh_breakout or is_pdh_breakout) and is_bullish_trend: + level_name = "盘前高位 (PMH)" if is_pmh_breakout else "昨日高位 (PDH)" + return "BUY", f"【共振突破买入】股价强力突破 {level_name},且日内 EMA 多头排列。" + if pattern_w: + return "BUY", "【共振形态买入】检测到 W底 (Double Bottom) 形态突破颈线。" + + # E. 开盘区间突破策略 (ORB) + elif p["strategy_mode"] == "opening_breakout": + if orb_high > 0 and close > orb_high and rvol >= 1.2: + return "BUY", f"【开盘突击-突破】股价突破5分钟开盘最高位 {orb_high:.2f} 刀,且成交量放大 (RVOL={rvol:.2f})。" + + # ------------------ 状态2:已持有仓位 (寻找平仓机会) ------------------ + else: + # 计算当前浮动盈亏 + pnl_pct = (close - avg_cost) / avg_cost + + # 0. 动态风控平仓 (当处于 dynamic 模式时,如状态转入 trend_down 或 high_volatility 强制出场) + if p["strategy_mode"] == "dynamic" and regime in ["trend_down", "high_volatility"]: + return "SELL", f"【动态路由-风控平仓】市场状态恶化转为 {regime} 风险区间,立即离场避险。" + + # 0.5 开盘突击突破失败止损 (跌破开盘区间低点) + if p["strategy_mode"] == "opening_breakout" and orb_low > 0 and close < orb_low: + return "SELL", f"【开盘突击-突破失败止损】股价跌破5分钟开盘最低位 {orb_low:.2f} 刀,平仓防守。" + + # 1. 移动追踪止损 (Trailing Stop Loss) + if p["trailing_stop_mode"] == "atr": + stop_distance = atr * p["trailing_stop_atr_mult"] + atr_stop_price = highest_price - stop_distance + if close < atr_stop_price: + return "SELL", f"【移动追踪止损】股价从最高价 {highest_price:.2f} 回撤超 {p['trailing_stop_atr_mult']}*ATR (当前追踪止损价: {atr_stop_price:.2f},收盘价: {close:.2f})。" + + elif p["trailing_stop_mode"] == "flat": + flat_stop_price = highest_price * (1 - p["stop_loss_pct"]) + if close < flat_stop_price: + return "SELL", f"【移动比例止损】股价从最高价 {highest_price:.2f} 回跌超 {p['stop_loss_pct']*100:.1f}% (当前止损价: {flat_stop_price:.2f},收盘价: {close:.2f})。" + + else: + if pnl_pct <= -p["stop_loss_pct"]: + return "SELL", f"【硬性止损】价格跌破成本的 {p['stop_loss_pct']*100:.1f}%,执行止损。" + + # 2. 硬性止盈目标 + if pnl_pct >= p["profit_target_pct"]: + return "SELL", f"【目标止盈】股价达到 {p['profit_target_pct']*100:.1f}% 目标位 (涨幅: {pnl_pct*100:.2f}%),全额止盈。" + + # 3. 形态平仓 + if p["strategy_mode"] in ["patterns", "consensus", "dynamic"]: + if pattern_m: + return "SELL", f"【M顶平仓】检测到双顶 (M-Top) 跌破颈线,趋势转空,平仓防守。" + if pattern_shooting: + return "SELL", f"【射击之星平仓】高位检测到 Shooting Star (流星线),买盘竭尽,平仓出场。" + if pattern_bear_eng: + return "SELL", f"【吞没平仓】检测到阴包阳 (Bearish Engulfing) 看跌形态,平仓避险。" + + # 4. 趋势破位离场 (非 dynamic 模式使用) + if p["strategy_mode"] != "dynamic" and close < vwap: + return "SELL", f"【趋势破位】股价跌破日内生命线 VWAP ({vwap:.2f} 刀),平仓防守。" + + # 5. 动量死叉离场 (EMA 模式使用) + if p["strategy_mode"] == "ema_cross" and ema_9 < ema_21: + return "SELL", "【死叉平仓】快线 EMA_9 跌破慢线 EMA_21 形成死叉,多头动能耗尽。" + + return "HOLD", "继续持有当前仓位,或保持空仓观望。" diff --git a/external/Quant.ai/backend/app/trading_engine.py b/external/Quant.ai/backend/app/trading_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..ad839d9858954ccd292d5d8c8801f1091430b4d7 --- /dev/null +++ b/external/Quant.ai/backend/app/trading_engine.py @@ -0,0 +1,255 @@ +# backend/app/trading_engine.py + +from app.config import INITIAL_CASH, SLIPPAGE_RATE, COMMISSION_PER_SHARE, MIN_COMMISSION_PER_ORDER + +class Portfolio: + def __init__(self, initial_cash=INITIAL_CASH, slippage_rate=SLIPPAGE_RATE, commission_per_share=COMMISSION_PER_SHARE, min_commission_per_order=MIN_COMMISSION_PER_ORDER): + self.initial_cash = initial_cash + self.cash = initial_cash + self.slippage_rate = slippage_rate + self.commission_per_share = commission_per_share + self.min_commission_per_order = min_commission_per_order + self.positions = {} # 格式: { TICKER: {"shares": int, "avg_cost": float, "highest_price": float} } + self.ledger = [] # 详细的交易流水账 + self.realized_pnl = 0.0 # 已实现盈亏 + self.peak_equity = initial_cash + self.risk_multiplier = 1.0 + self.consecutive_losses = 0 + + + def get_position_shares(self, ticker): + if ticker in self.positions: + return self.positions[ticker]["shares"] + return 0 + + def get_position_avg_cost(self, ticker): + if ticker in self.positions: + return self.positions[ticker]["avg_cost"] + return 0.0 + + def get_position_highest_price(self, ticker): + if ticker in self.positions: + return self.positions[ticker].get("highest_price", self.positions[ticker]["avg_cost"]) + return 0.0 + + def update_highest_price(self, ticker, current_price): + """ + 更新持仓期间达到的最高价,用于移动追踪止损。 + """ + if ticker in self.positions: + self.positions[ticker]["highest_price"] = max( + self.positions[ticker].get("highest_price", 0.0), + current_price + ) + + def get_equity(self, current_prices): + """ + 计算账户总资产 (可用资金 + 所有持仓市值) + """ + equity = self.cash + for ticker, pos in self.positions.items(): + if ticker in current_prices: + equity += pos["shares"] * current_prices[ticker] + else: + equity += pos["shares"] * pos["avg_cost"] + return equity + + def get_unrealized_pnl(self, current_prices): + """ + 计算未实现浮动盈亏 + """ + unrealized = 0.0 + for ticker, pos in self.positions.items(): + if ticker in current_prices: + market_price = current_prices[ticker] + unrealized += (market_price - pos["avg_cost"]) * pos["shares"] + return unrealized + + def calculate_position_size(self, ticker, current_price, atr, risk_pct=0.01, atr_multiplier=2.0, max_size_pct=0.5): + """ + 动态仓位管理:使用 ATR 波动率计算符合账户风险预期的买入股数。 + - 风险金额 = 账户总净资产 * (risk_pct * self.risk_multiplier) + - 止损距离 = ATR * atr_multiplier + - 股数 = 风险金额 / 止损距离 + - 最终股数不超过账户总净资产的 max_size_pct + """ + total_equity = self.get_equity({ticker: current_price}) + + # 应用账户级风控乘数 + effective_risk_pct = risk_pct * self.risk_multiplier + if effective_risk_pct <= 0: + return 0 + + # 兜底:如果 ATR 异常或为 0,退化为固定比例分配 + if atr <= 0: + target_allocation = total_equity * max_size_pct + return int(target_allocation / current_price) + + dollar_risk = total_equity * effective_risk_pct + stop_distance = atr * atr_multiplier + + if stop_distance <= 0: + return 0 + + shares = int(dollar_risk / stop_distance) + + # 上限控制 (MAX_POSITION_SIZE_PCT) + max_allocation = total_equity * max_size_pct + max_shares = int(max_allocation / current_price) + + return min(shares, max_shares) + + def buy(self, timestamp, ticker, price, shares): + """ + 执行买入模拟: + 1. 计入滑点:实际成交价高于盘面价格(因买入推高价格) + 2. 计算每股佣金与最低交易佣金 + """ + if shares <= 0: + return False, "买入股数必须大于 0" + + # 计入滑点损耗 (买入时滑点拉高买入价格) + execution_price = price * (1 + self.slippage_rate) + + # 计算佣金 (每股0.005刀,最低1刀,如果费率为0则为0) + if self.commission_per_share <= 0: + commission = 0.0 + else: + commission = max(shares * self.commission_per_share, self.min_commission_per_order) + + # 总支出 = 股本 + 佣金 + total_cost = (execution_price * shares) + commission + + if total_cost > self.cash: + return False, f"资金不足:需要 {total_cost:.2f} 刀,但账户只有 {self.cash:.2f} 刀。" + + # 扣除资金 + self.cash -= total_cost + + # 更新持仓和均价 + if ticker in self.positions: + pos = self.positions[ticker] + old_shares = pos["shares"] + old_cost = pos["avg_cost"] + new_shares = old_shares + shares + new_cost = ((old_shares * old_cost) + (shares * execution_price)) / new_shares + self.positions[ticker] = { + "shares": new_shares, + "avg_cost": new_cost, + "highest_price": max(pos.get("highest_price", 0.0), execution_price) + } + else: + self.positions[ticker] = { + "shares": shares, + "avg_cost": execution_price, + "highest_price": execution_price + } + + # 记录账单 + self.ledger.append({ + "timestamp": str(timestamp), + "action": "BUY", + "ticker": ticker, + "shares": shares, + "market_price": round(price, 4), + "execution_price": round(execution_price, 4), + "commission": round(commission, 2), + "total_value": round(execution_price * shares, 2), + "total_cost": round(total_cost, 2), + "cash_remaining": round(self.cash, 2) + }) + + return True, f"成功在 {execution_price:.2f} 刀买入 {shares} 股 {ticker} (佣金: {commission:.2f} 刀)" + + def sell(self, timestamp, ticker, price, shares): + """ + 执行卖出/平仓模拟: + 1. 计入滑点:实际成交价低于盘面价格(因抛售拉低价格) + 2. 扣除佣金 + """ + if ticker not in self.positions: + return False, f"账户中未持有 {ticker}" + + pos = self.positions[ticker] + owned_shares = pos["shares"] + + # 如果卖出股数大于持有股数,自动修正为全清 + if shares > owned_shares: + shares = owned_shares + + # 计入滑点损耗 (卖出时滑点降低卖出得到的价格) + execution_price = price * (1 - self.slippage_rate) + + # 计算佣金 + if self.commission_per_share <= 0: + commission = 0.0 + else: + commission = max(shares * self.commission_per_share, self.min_commission_per_order) + + # 回笼资金 = 销售额 - 佣金 + revenue = (execution_price * shares) - commission + + # 增加资金 + self.cash += revenue + + # 计算并累加已实现利润 + pnl = (execution_price - pos["avg_cost"]) * shares + self.realized_pnl += pnl + + # 更新/删除持仓 + if shares == owned_shares: + del self.positions[ticker] + else: + self.positions[ticker]["shares"] -= shares + + # 记录账单 + self.ledger.append({ + "timestamp": str(timestamp), + "action": "SELL", + "ticker": ticker, + "shares": shares, + "market_price": round(price, 4), + "execution_price": round(execution_price, 4), + "commission": round(commission, 2), + "total_value": round(execution_price * shares, 2), + "revenue": round(revenue, 2), + "realized_pnl": round(pnl, 2), + "cash_remaining": round(self.cash, 2) + }) + + return True, f"成功在 {execution_price:.2f} 刀卖出 {shares} 股 {ticker} (实现利润: {pnl:.2f} 刀,佣金: {commission:.2f} 刀)" + + def force_liquidate_all(self, timestamp, current_prices): + """ + 市价强制平仓所有持仓(用于每日美东 15:55 清仓或触及大额止损时) + """ + liquidated_actions = [] + tickers_to_sell = list(self.positions.keys()) + + for ticker in tickers_to_sell: + if ticker in current_prices: + price = current_prices[ticker] + shares = self.positions[ticker]["shares"] + success, msg = self.sell(timestamp, ticker, price, shares) + if success: + liquidated_actions.append(msg) + else: + price = self.positions[ticker]["avg_cost"] + shares = self.positions[ticker]["shares"] + success, msg = self.sell(timestamp, ticker, price, shares) + if success: + liquidated_actions.append(msg + " (由于缺失最新价,以成本价结算)") + + return liquidated_actions + + def reset(self): + """ + 重置账户状态 + """ + self.cash = self.initial_cash + self.positions = {} + self.ledger = [] + self.realized_pnl = 0.0 + self.peak_equity = self.initial_cash + self.risk_multiplier = 1.0 + self.consecutive_losses = 0 diff --git a/external/Quant.ai/backend/main.py b/external/Quant.ai/backend/main.py new file mode 100644 index 0000000000000000000000000000000000000000..f54abf799c26f9568d7a9b3c7245504127cf64ce --- /dev/null +++ b/external/Quant.ai/backend/main.py @@ -0,0 +1,113 @@ +# backend/main.py + +import argparse +import sys +import pandas as pd +import datetime +import os + +# 确保 backend 目录在 sys.path 中 +sys.path.append(os.path.dirname(os.path.abspath(__file__))) + +from app.config import INITIAL_CASH, MAX_POSITION_SIZE_PCT, WATCHLIST +from app.data_manager import fetch_and_prepare_data +from app.patterns import analyze_patterns +from app.simulator import run_backtest_sim + +def run_simulation(ticker, period="5d", interval="1m", strategy_mode="dynamic", position_sizing_mode="atr"): + """ + 运行日内/日线回测模拟器: + 1. 获取历史数据(分钟级或日线级) + 2. 运行 K 线形态与数值特征引擎 + 3. 调用通用回测模拟器,执行带 Regime Router 和高级风控的模拟 + 4. 输出交易业绩及对账流水 + """ + print("=" * 70) + print(f" QUANT.AI - BACKTEST SIMULATOR (通用回测模拟器)") + print(f" 股票代码: {ticker} | 周期: {interval} | 区间: {period} | 模式: {strategy_mode} | 仓位管理: {position_sizing_mode}") + print("=" * 70) + + # 1. 抓取与计算全部技术数据 + try: + df_raw = fetch_and_prepare_data(ticker, period=period, interval=interval) + df = analyze_patterns(df_raw) + except Exception as e: + print(f"数据加载或计算失败: {str(e)}") + sys.exit(1) + + print(f"数据加载成功:常规交易时段共 {len(df)} 根 K 线。") + print("正在启动模拟引擎...\n") + + # 2. 准备回测配置参数 + strategy_params = { + "strategy_mode": strategy_mode, + "stop_loss_pct": 0.015, + "profit_target_pct": 0.030, + "trailing_stop_mode": "atr", + "trailing_stop_atr_mult": 2.0, + "rsi_threshold_buy": 65.0 + } + + risk_params = { + "slippage_rate": 0.0003, + "commission_per_share": 0.005, + "min_commission_per_order": 1.0, + "position_sizing_mode": position_sizing_mode, + "risk_per_trade_pct": 0.01, + "max_position_size_pct": MAX_POSITION_SIZE_PCT + } + + is_intraday = interval in ["1m", "5m", "15m", "30m", "1h"] + + # 3. 运行回测模拟 + res = run_backtest_sim(df, ticker, strategy_params, risk_params, is_intraday=is_intraday) + + # 4. 输出回测统计报告 + print("\n" + "=" * 70) + print(" QUANT.AI - BACKTEST REPORT (回测统计报告)") + print("=" * 70) + print(f" 初始资金: $ {INITIAL_CASH:,.2f}") + print(f" 最终资产: $ {res['final_equity']:,.2f}") + print(f" 累计盈亏: $ {res['net_pnl']:+,.2f} ({res['pnl_pct']:+.2f}%)") + print(f" 最大资产回撤: {res['max_drawdown']*100:.2f}%") + print(f" 总交易笔数: {res['total_trades']} 次 (共 {res['round_trips']} 个平仓交易对)") + print(f" 策略胜率: {res['win_rate']:.2f}%") + print(f" 佣金总支出: $ {res['commission']:,.2f}") + print("-" * 70) + + # 统计市场状态 (Regime) 分布 + regime_counts = df['Regime'].value_counts() + print("【市场状态路由占比 (Market Regimes Dist)】:") + for regime_name, count in regime_counts.items(): + pct = (count / len(df)) * 100 + print(f" - {regime_name:<16}: {count:>5} 根 K线 ({pct:.2f}%)") + + print("-" * 70) + + # 打印交易流水账 + ledger = res["ledger"] + if len(ledger) > 0: + print("【交易流水明细 (Transaction Ledger)】:") + for t in ledger: + pnl_str = f" | 利润: {t['realized_pnl']:+,.2f}" if t['action'] == 'SELL' else "" + print(f" {t['timestamp']} | {t['action']} {t['ticker']} | 股数: {t['shares']} | 成交价: ${t['execution_price']:.2f} (市价: ${t['market_price']:.2f}) | 手续费: ${t['commission']:.2f}{pnl_str}") + else: + print("【提示】: 回测期间没有触发任何交易信号。系统防仓防守空仓!") + print("=" * 70) + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Quant.ai 量化交易回测模拟器") + parser.add_argument("--ticker", type=str, default="TSLA", help="测试股票代码 (默认: TSLA)") + parser.add_argument("--period", type=str, default="5d", help="回测区间,支持 1d, 5d, 1mo, 1y 等 (默认: 5d)") + parser.add_argument("--interval", type=str, default="1m", help="K线周期,支持 1m, 5m, 15m, 1d 等 (默认: 1m)") + parser.add_argument("--strategy", type=str, default="dynamic", choices=["dynamic", "consensus", "ema_cross", "breakout", "patterns"], help="策略模式 (默认: dynamic)") + parser.add_argument("--sizing", type=str, default="atr", choices=["atr", "flat"], help="仓位算仓模式 (默认: atr)") + + args = parser.parse_args() + + # 校验股票是否在池中 + ticker = args.ticker.upper() + if ticker not in WATCHLIST: + print(f"[WARNING] 警告:{ticker} 不在预设监控池 {WATCHLIST} 中,将抓取数据测试。") + + run_simulation(ticker, period=args.period, interval=args.interval, strategy_mode=args.strategy, position_sizing_mode=args.sizing) diff --git a/external/Quant.ai/backend/main_api.py b/external/Quant.ai/backend/main_api.py new file mode 100644 index 0000000000000000000000000000000000000000..148ecb4256e1c5b764793485da8672ca13718e4c --- /dev/null +++ b/external/Quant.ai/backend/main_api.py @@ -0,0 +1,1382 @@ +# backend/main_api.py + +from fastapi import FastAPI, Query +from fastapi.middleware.cors import CORSMiddleware +from pydantic import BaseModel +from typing import Optional +import uvicorn +import datetime +import pandas as pd +import numpy as np +import yfinance as yf + +import math + +def clean_float(val, default=0.0): + if val is None or pd.isna(val): + return default + try: + v = float(val) + if math.isnan(v) or math.isinf(v): + return default + return v + except Exception: + return default + + +from app.config import INITIAL_CASH, WATCHLIST, FORCE_LIQUIDATION_TIME +from app.data_manager import fetch_and_prepare_data, get_company_info, calculate_atr, INTERVAL_TO_PERIOD +from app.patterns import analyze_patterns +from app.simulator import run_backtest_sim +from app.agent import parse_research_prompt, get_example_prompts, get_backend_tools, get_chat_response +from app.llm_client import get_usage_stats as llm_get_usage +from app.data_cache import get_cache_stats, invalidate_cache +from app.experiment_manager import list_experiments, save_experiment, get_experiment, delete_experiment, compare_experiments +from app.risk_analyst import generate_risk_report +import time + +from app.broker.live_runner import LiveTradingRunner + +class LiveStartRequest(BaseModel): + params: Optional[dict] = None + ignore_market_hours: Optional[bool] = True + +app = FastAPI(title="Quant.ai API Server") + +# Instantiate live trading background runner +live_runner = LiveTradingRunner() + +# 请求延迟追踪 +request_latencies = [] + +@app.middleware("http") +async def track_latency(request, call_next): + start = time.time() + response = await call_next(request) + duration_ms = (time.time() - start) * 1000 + request_latencies.append(duration_ms) + if len(request_latencies) > 1000: # 只保留最近1000条 + request_latencies.pop(0) + return response + +# 允许跨域请求 (CORS),方便 React 前端调用 +app.add_middleware( + CORSMiddleware, + allow_origins=["*"], # 开发阶段允许所有来源 + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +@app.get("/api/watchlist") +def get_watchlist_data(): + """ + 获取自选股池的列表 + """ + return {"watchlist": WATCHLIST} + +@app.get("/api/company_info") +def get_company_details(ticker: str): + """ + 获取指定股票的公司详情元数据 + """ + info = get_company_info(ticker.upper()) + return info + +@app.get("/api/scan") +def scan_market_stocks(tickers: str = None): + """ + 接口:运行盘前扫描器,分析多个股票的 RVol, ATR%, Gap% 强度并输出推荐意见 + """ + if tickers: + ticker_list = [t.strip().upper() for t in tickers.split(",") if t.strip()] + else: + # 默认扫描 watchlist + ticker_list = WATCHLIST.copy() + + results = [] + for ticker in ticker_list: + try: + # 获取最近 30 天的日线数据 + stock = yf.Ticker(ticker) + df = stock.history(period="30d") + + if df.empty or len(df) < 20: + continue + + latest_day = df.iloc[-1] + prev_day = df.iloc[-2] + + # 1. 相对成交量 (RVol) + avg_volume_20d = df['Volume'].iloc[-21:-1].mean() + latest_volume = latest_day['Volume'] + rvol = latest_volume / avg_volume_20d if avg_volume_20d > 0 else 0 + + # 2. 波动率 ATR % of Price + df['ATR'] = calculate_atr(df, period=14) + latest_atr = df['ATR'].iloc[-1] + atr_pct = (latest_atr / latest_day['Close']) * 100 if latest_day['Close'] > 0 else 0 + + # 3. 跳空幅度 Gap% + gap_pct = ((latest_day['Open'] - prev_day['Close']) / prev_day['Close']) * 100 + + # 清理 nan 和 inf 值 + price = clean_float(latest_day['Close']) + rvol = clean_float(rvol) + atr_pct = clean_float(atr_pct) + gap_pct = clean_float(gap_pct) + volume_m = clean_float(latest_volume) / 1_000_000 + + # 获取公司基本静态档案 + company_details = get_company_info(ticker) + + # 推荐规则 + recommended = bool(rvol > 1.2 and atr_pct > 1.5) + + results.append({ + "ticker": ticker, + "name": company_details["name"], + "sector": company_details["sector"], + "price": float(round(price, 2)), + "rvol": float(round(rvol, 2)), + "atr_pct": float(round(atr_pct, 2)), + "gap_pct": float(round(gap_pct, 2)), + "volume_m": float(round(volume_m, 2)), + "recommended": recommended, + "reason": f"成交量放大至 {rvol:.1f} 倍,日均振幅达 {atr_pct:.1f}%,具备极强的交易热度。" if recommended else "当前市场动能不足或振幅较窄,建议观望。" + }) + except Exception as e: + # 异常时记录基础数据 + results.append({ + "ticker": ticker, + "name": f"{ticker} Corp", + "sector": "未知", + "price": 0.0, + "rvol": 0.0, + "atr_pct": 0.0, + "gap_pct": 0.0, + "volume_m": 0.0, + "recommended": False, + "reason": f"数据抓取失败: {str(e)}" + }) + + # 按相对成交量降序排列 + results.sort(key=lambda x: x["rvol"], reverse=True) + return {"success": True, "results": results} + +def _run_backtest_core( + ticker: str = "TSLA", + period: str = None, + interval: str = "1m", + strategy_mode: str = "dynamic", + stop_loss_pct: float = 0.015, + profit_target_pct: float = 0.030, + trailing_stop_mode: str = "atr", + trailing_stop_atr_mult: float = 2.0, + rsi_threshold_buy: float = 65.0, + risk_per_trade_pct: float = 0.01, + max_position_size_pct: float = 0.50, + commission_per_share: float = 0.005, + slippage_rate: float = 0.0003, + market_open_focus: bool = True +): + ticker = ticker.upper() + try: + # 1. 整理策略与风险管理参数 + strategy_params = { + "strategy_mode": strategy_mode, + "stop_loss_pct": stop_loss_pct, + "profit_target_pct": profit_target_pct, + "trailing_stop_mode": trailing_stop_mode, + "trailing_stop_atr_mult": trailing_stop_atr_mult, + "rsi_threshold_buy": rsi_threshold_buy, + "market_open_focus": market_open_focus + } + + risk_params = { + "slippage_rate": slippage_rate, + "commission_per_share": commission_per_share, + "min_commission_per_order": 1.0, + "position_sizing_mode": "atr", + "risk_per_trade_pct": risk_per_trade_pct, + "max_position_size_pct": max_position_size_pct + } + + # 2. 拉取数据 + df_raw = fetch_and_prepare_data(ticker, period=period, interval=interval) + + # 3. 运行形态检测 + df = analyze_patterns(df_raw) + + # 记录形态检测出的日志事件,用于前端展示 + patterns_log = [] + for idx, row in df.iterrows(): + timestamp_str = idx.strftime("%Y-%m-%d %H:%M") + close_p = float(row['Close']) + + if row.get('Pattern_W_Bottom', False): + patterns_log.append({ + "time": timestamp_str, + "ticker": ticker, + "pattern": "W-Bottom (双底)", + "type": "bullish", + "price": round(close_p, 2), + "desc": "股价完成了两阶段探底,并强势突破了中间的波峰颈线阻力,看涨信号确认。" + }) + if row.get('Pattern_M_Top', False): + patterns_log.append({ + "time": timestamp_str, + "ticker": ticker, + "pattern": "M-Top (双顶)", + "type": "bearish", + "price": round(close_p, 2), + "desc": "股价两次上攻均受阻,随后跌破了中间波谷的颈线支撑,看跌形态确认。" + }) + if row.get('Pattern_Hammer', False): + patterns_log.append({ + "time": timestamp_str, + "ticker": ticker, + "pattern": "Hammer (锤子线)", + "type": "bullish", + "price": round(close_p, 2), + "desc": "低位出现长下影线小实体,代表下方买方托盘力量极其强劲,是看涨信号。" + }) + if row.get('Pattern_Shooting_Star', False): + patterns_log.append({ + "time": timestamp_str, + "ticker": ticker, + "pattern": "Shooting Star (流星线)", + "type": "bearish", + "price": round(close_p, 2), + "desc": "高位出现长上影线小实体,代表向上试探失败,抛盘涌现,见顶风险加剧。" + }) + if row.get('Pattern_Bullish_Engulfing', False): + patterns_log.append({ + "time": timestamp_str, + "ticker": ticker, + "pattern": "Bullish Engulfing (阳包阴)", + "type": "bullish", + "price": round(close_p, 2), + "desc": "大阳线实体完全包住前一根阴线,说明买方完全反击并掌控了局势。" + }) + if row.get('Pattern_Bearish_Engulfing', False): + patterns_log.append({ + "time": timestamp_str, + "ticker": ticker, + "pattern": "Bearish Engulfing (阴包阳)", + "type": "bearish", + "price": round(close_p, 2), + "desc": "大阴线实体完全包住前一根阳线,说明卖方力量空前强大,恐慌盘砸盘。" + }) + + # 4. 执行模拟回测 + is_intraday = interval in ["1m", "5m", "15m", "30m", "1h"] + res = run_backtest_sim(df, ticker, strategy_params, risk_params, is_intraday=is_intraday) + + # 5. 整理 K线数据给前端 TradingView 图表渲染 + chart_candles = [] + for idx, r in df.iterrows(): + chart_candles.append({ + "time": int(idx.timestamp()), + "open": round(clean_float(r['Open']), 2), + "high": round(clean_float(r['High']), 2), + "low": round(clean_float(r['Low']), 2), + "close": round(clean_float(r['Close']), 2), + "volume": int(clean_float(r['Volume'])), + "vwap": round(clean_float(r['VWAP']), 2) if not pd.isna(r['VWAP']) else None, + "ema_9": round(clean_float(r['EMA_9']), 2) if not pd.isna(r['EMA_9']) else None, + "ema_21": round(clean_float(r['EMA_21']), 2) if not pd.isna(r['EMA_21']) else None, + "ema_50": round(clean_float(r['EMA_50']), 2) if not pd.isna(r['EMA_50']) else None, + "rsi": round(clean_float(r['RSI']), 1) if not pd.isna(r['RSI']) else None, + "squeeze": bool(r['Squeeze_On']) if not pd.isna(r['Squeeze_On']) else False, + "regime": r.get('Regime', 'range_bound') + }) + + # 整理买卖标记 (markers) + trade_markers = [] + for trade in res["ledger"]: + trade_time = int(pd.to_datetime(trade['timestamp']).timestamp()) + + if trade['action'] == 'BUY': + trade_markers.append({ + "time": trade_time, + "position": "belowBar", + "color": "#00c805", + "shape": "arrowUp", + "text": f"BUY {trade['shares']}股 @ {trade['execution_price']:.2f}" + }) + elif trade['action'] == 'SELL': + pnl = trade.get('realized_pnl', 0.0) + color = "#ff3b30" if pnl < 0 else "#00c805" + text = f"SELL {trade['shares']}股 @ {trade['execution_price']:.2f} ({'+' if pnl>=0 else ''}{pnl:.2f})" + trade_markers.append({ + "time": trade_time, + "position": "aboveBar", + "color": color, + "shape": "arrowDown", + "text": text + }) + + # 按时间排序形态日志 + patterns_log = sorted(patterns_log, key=lambda x: x["time"], reverse=True) + patterns_log = patterns_log[:100] + + return { + "success": True, + "ticker": ticker, + "period": period or INTERVAL_TO_PERIOD.get(interval, "5d"), + "interval": interval, + "summary": { + "initial_cash": INITIAL_CASH, + "final_equity": clean_float(res["final_equity"]), + "net_pnl": clean_float(res["net_pnl"]), + "pnl_pct": clean_float(res["pnl_pct"]), + "total_trades": int(res["total_trades"]), + "round_trips": int(res["round_trips"]), + "win_rate": clean_float(res["win_rate"]), + "commission": clean_float(res["commission"]), + "max_drawdown": clean_float(res["max_drawdown"]), + "sharpe": clean_float(res.get("sharpe", 0)), + "calmar": clean_float(res.get("calmar", 0)), + "cagr": clean_float(res.get("cagr", 0)), + "profit_factor": clean_float(res.get("profit_factor", 0)), + "gross_profit": clean_float(res.get("gross_profit", 0)), + "gross_loss": clean_float(res.get("gross_loss", 0)), + }, + "ledger": res["ledger"], + "candles": chart_candles, + "markers": trade_markers, + "equity_curve": res["equity_curve"], + "drawdown_curve": res.get("drawdown_curve", []), + "regime_breakdown": res.get("regime_breakdown", []), + "regime_distribution": res.get("regime_distribution", {}), + "patterns_log": patterns_log + } + + except Exception as e: + import traceback + traceback.print_exc() + return {"success": False, "error": str(e)} + +@app.get("/api/backtest") +def run_backtest_api( + ticker: str = "TSLA", + period: str = None, + interval: str = "1m", + strategy_mode: str = "dynamic", + stop_loss_pct: float = 0.015, + profit_target_pct: float = 0.030, + trailing_stop_mode: str = "atr", + trailing_stop_atr_mult: float = 2.0, + rsi_threshold_buy: float = 65.0, + risk_per_trade_pct: float = 0.01, + max_position_size_pct: float = 0.50, + commission_per_share: float = 0.005, + slippage_rate: float = 0.0003, + market_open_focus: bool = True +): + """ + 接口:运行自定义配置参数的回测,包含 K线、均线、市场状态路由与交易流水 + """ + return _run_backtest_core( + ticker=ticker, + period=period, + interval=interval, + strategy_mode=strategy_mode, + stop_loss_pct=stop_loss_pct, + profit_target_pct=profit_target_pct, + trailing_stop_mode=trailing_stop_mode, + trailing_stop_atr_mult=trailing_stop_atr_mult, + rsi_threshold_buy=rsi_threshold_buy, + risk_per_trade_pct=risk_per_trade_pct, + max_position_size_pct=max_position_size_pct, + commission_per_share=commission_per_share, + slippage_rate=slippage_rate, + market_open_focus=market_open_focus + ) + + +# ========== AI Agent & Walk-Forward & Monitoring Endpoints ========== + +class ChatRequest(BaseModel): + message: str + history: Optional[list] = [] + +@app.post("/api/agent/chat") +def agent_chat(request: ChatRequest): + """ + AI 研究助手对话接口 — 接受自然语言策略描述,返回解析后的策略配置 + AI 回复 + """ + try: + result = get_chat_response(request.message, request.history) + return {"success": True, **result} + except Exception as e: + return {"success": False, "error": str(e)} + +class ExecuteRequest(BaseModel): + strategy_config: dict + experiment_name: Optional[str] = None + +@app.post("/api/agent/execute") +def agent_execute(request: ExecuteRequest): + """ + 一键执行:根据策略配置获取数据 + 运行回测 + 生成风险报告 + 保存实验 + """ + try: + config = request.strategy_config + ticker = config.get("ticker", "TSLA").upper() + interval = config.get("interval", "1d") + + # 运行回测核心 + result = _run_backtest_core( + ticker=ticker, + period=None, + interval=interval, + strategy_mode=config.get("strategy_mode", "dynamic"), + stop_loss_pct=config.get("stop_loss_pct", 0.015), + profit_target_pct=config.get("profit_target_pct", 0.030), + trailing_stop_mode=config.get("trailing_stop_mode", "atr"), + trailing_stop_atr_mult=config.get("trailing_stop_atr_mult", 2.0), + rsi_threshold_buy=config.get("rsi_threshold_buy", 65.0), + risk_per_trade_pct=config.get("risk_per_trade_pct", 0.01), + max_position_size_pct=config.get("max_position_size_pct", 0.50), + commission_per_share=config.get("commission_per_share", 0.005), + slippage_rate=config.get("slippage_rate", 0.0003), + market_open_focus=config.get("market_open_focus", True) + ) + + if not result.get("success", False): + return result + + # 默认保存为实验 + exp_name = request.experiment_name or f"LLM_{ticker}_{config.get('strategy_mode', 'dynamic')}" + new_id = save_experiment( + name=exp_name, + ticker=ticker, + interval=interval, + strategy_mode=config.get("strategy_mode", "dynamic"), + config=config, + metrics=result["summary"], + equity_curve=result.get("equity_curve", []), + drawdown_curve=result.get("drawdown_curve", []), + regime_breakdown=result.get("regime_breakdown", []) + ) + + result["experiment_id"] = new_id + result["experiment_saved"] = True + return result + except Exception as e: + return {"success": False, "error": str(e)} + +class WalkForwardRequest(BaseModel): + ticker: str = "TSLA" + interval: str = "1d" + period: Optional[str] = "1y" + train_size: Optional[int] = 120 + test_size: Optional[int] = 40 + +@app.post("/api/walk_forward") +def run_walk_forward_api_endpoint(request: WalkForwardRequest): + """ + 运行 Walk-Forward 优化并返回 IS vs OOS Sharpe 汇总结果 + """ + ticker = request.ticker.upper() + interval = request.interval + period = request.period or "1y" + train_size = request.train_size or 120 + test_size = request.test_size or 40 + + try: + df_raw = fetch_and_prepare_data(ticker, period=period, interval=interval) + df = analyze_patterns(df_raw) + + total_len = len(df) + if total_len < (train_size + test_size): + return {"success": False, "error": f"历史数据共 {total_len} 根 Bar,不足以分配 Train({train_size}) + Test({test_size})!"} + + param_grid = [] + for mode in ["dynamic", "consensus"]: + for atr_mult in [1.5, 2.0, 2.5]: + for rsi_th in [60.0, 65.0, 70.0]: + param_grid.append({ + "strategy_mode": mode, + "trailing_stop_atr_mult": atr_mult, + "rsi_threshold_buy": rsi_th, + "stop_loss_pct": 0.015, + "profit_target_pct": 0.030 + }) + + risk_params = { + "slippage_rate": 0.0003, + "commission_per_share": 0.005, + "min_commission_per_order": 1.0, + "position_sizing_mode": "atr", + "risk_per_trade_pct": 0.01, + "max_position_size_pct": 0.50 + } + + start_idx = 0 + oos_results = [] + is_intraday = interval in ["1m", "5m", "15m", "30m", "1h"] + window_count = 1 + + while start_idx + train_size + test_size <= total_len: + train_df = df.iloc[start_idx : start_idx + train_size] + test_df = df.iloc[start_idx + train_size : start_idx + train_size + test_size] + + train_start_date = train_df.index[0].strftime("%Y-%m-%d") + train_end_date = train_df.index[-1].strftime("%Y-%m-%d") + test_start_date = test_df.index[0].strftime("%Y-%m-%d") + test_end_date = test_df.index[-1].strftime("%Y-%m-%d") + + best_score = -999999.0 + best_params = None + + for params in param_grid: + res = run_backtest_sim(train_df, ticker, params, risk_params, is_intraday=is_intraday) + score = res["net_pnl"] - (res["max_drawdown"] * 30000.0 * 2.0) + if score > best_score: + best_score = score + best_params = params + + test_res = run_backtest_sim(test_df, ticker, best_params, risk_params, is_intraday=is_intraday) + + # 计算 IS Sharpe + train_best_res = run_backtest_sim(train_df, ticker, best_params, risk_params, is_intraday=is_intraday) + is_sharpe = train_best_res.get("sharpe", 0.0) + oos_sharpe = test_res.get("sharpe", 0.0) + + oos_results.append({ + "window": window_count, + "train_period": f"{train_start_date} ~ {train_end_date}", + "test_period": f"{test_start_date} ~ {test_end_date}", + "best_params": best_params, + "is_sharpe": round(clean_float(is_sharpe), 2), + "oos_sharpe": round(clean_float(oos_sharpe), 2), + "net_pnl": round(clean_float(test_res["net_pnl"]), 2), + "max_drawdown": round(clean_float(test_res["max_drawdown"]), 4), + "round_trips": int(test_res["round_trips"]), + "win_rate": round(clean_float(test_res["win_rate"]), 2), + "commission": round(clean_float(test_res["commission"]), 2) + }) + + start_idx += test_size + window_count += 1 + + # 对照组:全样本默认参数 + default_params = { + "strategy_mode": "dynamic", + "trailing_stop_atr_mult": 2.0, + "rsi_threshold_buy": 65.0, + "stop_loss_pct": 0.015, + "profit_target_pct": 0.030 + } + static_res = run_backtest_sim(df, ticker, default_params, risk_params, is_intraday=is_intraday) + + total_wf_pnl = sum(r["net_pnl"] for r in oos_results) + total_wf_commission = sum(r["commission"] for r in oos_results) + avg_wf_drawdown = float(np.mean([r["max_drawdown"] for r in oos_results])) if oos_results else 0.0 + total_wf_trades = sum(r["round_trips"] for r in oos_results) + + # 计算 IS Sharpe 和 OOS Sharpe 相关性 + is_sharhes = [r["is_sharpe"] for r in oos_results] + oos_sharhes = [r["oos_sharpe"] for r in oos_results] + correlation = 0.0 + if len(is_sharhes) > 1 and np.std(is_sharhes) > 0 and np.std(oos_sharhes) > 0: + correlation = float(np.corrcoef(is_sharhes, oos_sharhes)[0, 1]) + + correlation = clean_float(correlation) + is_overfitted = False + avg_is_sharpe = float(np.mean(is_sharhes)) if is_sharhes else 0.0 + avg_oos_sharpe = float(np.mean(oos_sharhes)) if oos_sharhes else 0.0 + + if avg_is_sharpe > 1.2 and avg_oos_sharpe < 0.3: + is_overfitted = True + + return { + "success": True, + "ticker": ticker, + "interval": interval, + "period": period, + "oos_results": oos_results, + "correlation": round(correlation, 2), + "is_overfitted": is_overfitted, + "static_control": { + "net_pnl": round(clean_float(static_res["net_pnl"]), 2), + "pnl_pct": round(clean_float(static_res["pnl_pct"]), 2), + "round_trips": int(static_res["round_trips"]), + "commission": round(clean_float(static_res["commission"]), 2), + "max_drawdown": round(clean_float(static_res["max_drawdown"]), 4), + "sharpe": round(clean_float(static_res.get("sharpe", 0.0)), 2) + }, + "summary": { + "total_wf_pnl": round(total_wf_pnl, 2), + "total_wf_commission": round(total_wf_commission, 2), + "avg_wf_drawdown": round(avg_wf_drawdown, 4), + "total_wf_trades": total_wf_trades, + "avg_is_sharpe": round(avg_is_sharpe, 2), + "avg_oos_sharpe": round(avg_oos_sharpe, 2) + } + } + except Exception as e: + return {"success": False, "error": str(e)} + +class TuneRequest(BaseModel): + ticker: str + interval: str = "1m" + period: Optional[str] = "5d" + +@app.post("/api/ai_tune") +def ai_tune_endpoint(request: TuneRequest): + """ + 运行 AI 托管参数自动调优接口 + """ + ticker = request.ticker.upper() + interval = request.interval + period = request.period or "5d" + + try: + # 1. 抓取与清洗指标数据 + df_raw = fetch_and_prepare_data(ticker, period=period, interval=interval) + df = analyze_patterns(df_raw) + + # 2. 定义调优参数搜索网格 + best_score = -999999.0 + best_params = None + best_res = None + + strategy_options = ["opening_breakout", "consensus", "dynamic", "patterns"] + stop_loss_options = [0.005, 0.01, 0.015, 0.02] # 紧凑止损线 + profit_target_options = [0.01, 0.02, 0.03, 0.05] # 止盈线 + atr_mult_options = [1.5, 2.0, 2.5] + + risk_params = { + "slippage_rate": 0.0003, + "commission_per_share": 0.005, + "min_commission_per_order": 1.0, + "position_sizing_mode": "atr", + "risk_per_trade_pct": 0.01, + "max_position_size_pct": 0.50 + } + + is_intraday = interval in ["1m", "5m", "15m", "30m", "1h"] + + for mode in strategy_options: + for sl in stop_loss_options: + for pt in profit_target_options: + for atr_m in atr_mult_options: + params = { + "strategy_mode": mode, + "stop_loss_pct": sl, + "profit_target_pct": pt, + "trailing_stop_mode": "atr", + "trailing_stop_atr_mult": atr_m, + "rsi_threshold_buy": 65.0, + "market_open_focus": True + } + + res = run_backtest_sim(df, ticker, params, risk_params, is_intraday=is_intraday) + + net_pnl = res["net_pnl"] + max_dd = res["max_drawdown"] + win_rate = res["win_rate"] + trades = res["round_trips"] + + if trades == 0: + score = -1000.0 + else: + # 评分函数:利润优先,严厉惩罚大回撤,结合胜率 + score = net_pnl - (max_dd * 30000.0 * 4.0) + (win_rate * 2.0) + + if score > best_score: + best_score = score + best_params = params + best_res = res + + if not best_params: + best_params = { + "strategy_mode": "opening_breakout", + "stop_loss_pct": 0.01, + "profit_target_pct": 0.02, + "trailing_stop_mode": "atr", + "trailing_stop_atr_mult": 1.5, + "rsi_threshold_buy": 65.0, + "market_open_focus": True + } + best_res = {"net_pnl": 0.0, "max_drawdown": 0.0, "win_rate": 0.0, "round_trips": 0} + + ticker_details = get_company_info(ticker) + name = ticker_details.get("name", ticker) + + mode_cn = { + "opening_breakout": "开盘突击突破策略", + "consensus": "共振共识策略", + "dynamic": "动态状态路由策略", + "patterns": "K线形态反转策略" + }.get(best_params["strategy_mode"], best_params["strategy_mode"]) + + reasoning = ( + f"AI 智能托管针对 {name} 最近 {period} 的日内波动特征运行了机器学习调优算法。\n" + f"由于开盘 3-5 分钟振幅大且伴随突破,AI 自动推荐采用【{mode_cn}】来追踪走势。\n" + f"风控策略已自动调整为:硬止损设为 {(best_params['stop_loss_pct']*100):.1f}%," + f"目标止盈设为 {(best_params['profit_target_pct']*100):.1f}%," + f"配合 {best_params['trailing_stop_atr_mult']:.1f}倍 ATR 移动追踪止损以防高位跌落。\n" + f"该优化组合在近期的历史回测中实现了约 ${best_res['net_pnl']:.2f} 的净盈亏," + f"胜率达 {best_res['win_rate']:.1f}%,最大回撤控制在 {(best_res['max_drawdown']*100):.2f}%,有效规避了单边下挫风险。" + ) + + return { + "success": True, + "best_params": best_params, + "reasoning": reasoning, + "metrics": { + "net_pnl": round(best_res["net_pnl"], 2), + "win_rate": round(best_res["win_rate"], 2), + "max_drawdown": round(best_res["max_drawdown"], 4), + "round_trips": best_res["round_trips"] + } + } + except Exception as e: + import traceback + traceback.print_exc() + return {"success": False, "error": str(e)} + +@app.get("/api/metrics") +def get_metrics(): + """ + 监控指标端点:请求次数、响应延迟统计、本地数据缓存容量、LLM 费用与 token + """ + lats = request_latencies[-100:] if request_latencies else [0.0] + p50 = float(np.percentile(lats, 50)) if lats else 0.0 + p95 = float(np.percentile(lats, 95)) if lats else 0.0 + + # 缓存统计 + cache_stats = get_cache_stats() + # LLM 统计 + llm_usage = llm_get_usage() + + return { + "success": True, + "total_requests": len(request_latencies), + "latency_p50_ms": round(p50, 1), + "latency_p95_ms": round(p95, 1), + "cache": cache_stats, + "llm_usage": llm_usage + } + +# ========== Experiments Endpoints ========== + +@app.get("/api/experiments") +def get_experiments_list(): + """获取所有已保存的实验""" + try: + return {"success": True, "experiments": list_experiments()} + except Exception as e: + return {"success": False, "error": str(e)} + +class SaveExperimentRequest(BaseModel): + name: str + ticker: str + interval: str + strategy_mode: str + config: dict + metrics: dict + equity_curve: list + drawdown_curve: list + regime_breakdown: list + +@app.post("/api/experiments/save") +def post_save_experiment(request: SaveExperimentRequest): + """保存当前实验""" + try: + new_id = save_experiment( + name=request.name, + ticker=request.ticker, + interval=request.interval, + strategy_mode=request.strategy_mode, + config=request.config, + metrics=request.metrics, + equity_curve=request.equity_curve, + drawdown_curve=request.drawdown_curve, + regime_breakdown=request.regime_breakdown + ) + return {"success": True, "id": new_id} + except Exception as e: + return {"success": False, "error": str(e)} + +class CompareRequest(BaseModel): + ids: list + +@app.post("/api/experiments/compare") +def post_compare_experiments(request: CompareRequest): + """对比多个实验""" + try: + results = compare_experiments(request.ids) + return {"success": True, "results": results} + except Exception as e: + return {"success": False, "error": str(e)} + +@app.delete("/api/experiments/{id}") +def delete_saved_experiment(id: int): + """删除指定的实验""" + try: + success = delete_experiment(id) + return {"success": success} + except Exception as e: + return {"success": False, "error": str(e)} + +class ResearchRequest(BaseModel): + prompt: str + +@app.post("/api/agent/research") +def agent_research(request: ResearchRequest): + """ + AI Agent: Parse natural language research prompt into strategy config + execution plan + """ + try: + result = parse_research_prompt(request.prompt) + return {"success": True, **result} + except Exception as e: + return {"success": False, "error": str(e)} + +@app.get("/api/agent/examples") +def agent_examples(): + """ + Return example prompts for the chat interface + """ + return {"examples": get_example_prompts(), "tools": get_backend_tools()} + +class ReportRequest(BaseModel): + ticker: str = "TSLA" + interval: str = "1d" + strategy_mode: str = "dynamic" + stop_loss_pct: float = 0.015 + profit_target_pct: float = 0.030 + trailing_stop_mode: str = "atr" + trailing_stop_atr_mult: float = 2.0 + rsi_threshold_buy: float = 65.0 + risk_per_trade_pct: float = 0.01 + max_position_size_pct: float = 0.50 + position_sizing_mode: str = "atr" + commission_per_share: float = 0.005 + slippage_rate: float = 0.0003 + +@app.post("/api/report/generate") +def generate_report(request: ReportRequest): + """ + Generate AI risk analysis report: run backtest then analyze results + """ + try: + ticker = request.ticker.upper() + strategy_params = { + "strategy_mode": request.strategy_mode, + "stop_loss_pct": request.stop_loss_pct, + "profit_target_pct": request.profit_target_pct, + "trailing_stop_mode": request.trailing_stop_mode, + "trailing_stop_atr_mult": request.trailing_stop_atr_mult, + "rsi_threshold_buy": request.rsi_threshold_buy, + } + risk_params = { + "slippage_rate": request.slippage_rate, + "commission_per_share": request.commission_per_share, + "min_commission_per_order": 1.0, + "position_sizing_mode": request.position_sizing_mode, + "risk_per_trade_pct": request.risk_per_trade_pct, + "max_position_size_pct": request.max_position_size_pct, + } + + # Run backtest + df_raw = fetch_and_prepare_data(ticker, interval=request.interval) + df = analyze_patterns(df_raw) + is_intraday = request.interval in ["1m", "5m", "15m", "30m", "1h"] + backtest_result = run_backtest_sim(df, ticker, strategy_params, risk_params, is_intraday=is_intraday) + + # Generate risk report + strategy_config = { + "ticker": ticker, + "interval": request.interval, + "strategy_mode": request.strategy_mode, + } + report = generate_risk_report(backtest_result, strategy_config) + + return {"success": True, "report": report} + except Exception as e: + import traceback + traceback.print_exc() + return {"success": False, "error": str(e)} + +@app.get("/api/research_report") +def get_research_report(): + """ + 读取并解析本地 deep-research-report.md 报告,将其转化为结构化的 JSON 返回给前端 + """ + import os + import re + + # 查找本地研究报告文件 + possible_paths = [ + "deep-research-report.md", + "../deep-research-report.md", + os.path.join(os.path.dirname(__file__), "..", "deep-research-report.md"), + os.path.join(os.path.dirname(__file__), "deep-research-report.md"), + ] + filepath = None + for p in possible_paths: + if os.path.exists(p): + filepath = p + break + + if not filepath: + # 兜底查找 + for root, dirs, files in os.walk(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))): + if "deep-research-report.md" in files: + filepath = os.path.join(root, "deep-research-report.md") + break + + if not filepath or not os.path.exists(filepath): + return {"success": False, "error": f"未找到 deep-research-report.md 文件,请检查路径。查找过的路径: {possible_paths}"} + + try: + with open(filepath, "r", encoding="utf-8") as f: + content = f.read() + + # 提取标题 + title_match = re.search(r'^#\s+(.*?)$', content, re.MULTILINE) + title = title_match.group(1).strip() if title_match else "日线为主的全自动炒股软件开发分析报告" + + # 以双换行符 + ## 拆分大章节 + raw_sections = re.split(r'\n##\s+', content) + sections = [] + + for i, rs in enumerate(raw_sections): + if i == 0: + # 标题下方的首段引言 (如果有的话) + intro_text = rs.replace(f"# {title}", "").strip() + if intro_text: + sections.append({ + "title": "执行摘要", + "id": "executive_summary", + "components": [{"type": "paragraph", "content": intro_text}] + }) + continue + + lines = rs.split("\n") + heading = lines[0].strip() + body_text = "\n".join(lines[1:]).strip() + + # 生成前端滚动锚点 ID + id_mapping = { + "执行摘要": "executive_summary", + "关键目标与约束": "key_goals___constraints", + "K线形态与技术指标": "kline_patterns___indicators", + "量化策略清单": "quantitative_strategy_checklist", + "风控与资金管理": "risk_control___capital_management", + "回测与参数优化": "backtesting___parameter_optimization", + "实盘部署与代码清单": "production_deployment___code_checklist", + "参考来源与合规风险提示": "references___compliance_risk_alert" + } + section_id = id_mapping.get(heading) + if not section_id: + section_id = heading.lower() + section_id = re.sub(r'[^a-z0-9]', '_', section_id).strip('_') + if not section_id: + section_id = f"sec_{i}" + + components = [] + body_lines = body_text.split("\n") + idx = 0 + while idx < len(body_lines): + line = body_lines[idx].strip() + if not line: + idx += 1 + continue + + # 1. 三级子标题 + if line.startswith("###"): + sub_heading = line.replace("###", "").strip() + components.append({ + "type": "heading3", + "content": sub_heading + }) + idx += 1 + continue + + # 2. Markdown 表格 + if line.startswith("|") and idx + 1 < len(body_lines) and re.match(r'^\|[\s:-|]+$', body_lines[idx+1].strip()): + table_lines = [] + while idx < len(body_lines) and (body_lines[idx].strip().startswith("|") or not body_lines[idx].strip()): + if body_lines[idx].strip(): + table_lines.append(body_lines[idx].strip()) + idx += 1 + + if len(table_lines) >= 3: + headers = [c.strip() for c in table_lines[0].split("|")[1:-1]] + rows = [] + for t_line in table_lines[2:]: + cols = [c.strip() for c in t_line.split("|")[1:-1]] + if len(cols) < len(headers): + cols += [""] * (len(headers) - len(cols)) + else: + cols = cols[:len(headers)] + rows.append(dict(zip(headers, cols))) + components.append({ + "type": "table", + "headers": headers, + "rows": rows + }) + continue + + # 3. 代码块 + if line.startswith("```"): + lang = line.replace("```", "").strip() + code_content = [] + idx += 1 + while idx < len(body_lines) and not body_lines[idx].strip().startswith("```"): + code_content.append(body_lines[idx]) + idx += 1 + idx += 1 # 跨过 ``` + components.append({ + "type": "code", + "lang": lang, + "content": "\n".join(code_content) + }) + continue + + # 4. 引用块 / 警示框 (Github Alerts) + if line.startswith(">"): + alert_type = "info" + cleaned_line = line[1:].strip() + match_tag = re.match(r'^\[!(NOTE|TIP|IMPORTANT|WARNING|CAUTION)\]', cleaned_line) + if match_tag: + alert_type = match_tag.group(1).lower() + cleaned_line = cleaned_line[match_tag.end():].strip() + + alert_lines = [cleaned_line] if cleaned_line else [] + idx += 1 + while idx < len(body_lines) and body_lines[idx].strip().startswith(">"): + cleaned_body_line = body_lines[idx].strip()[1:].strip() + if cleaned_body_line: + alert_lines.append(cleaned_body_line) + idx += 1 + components.append({ + "type": "alert", + "alert_type": alert_type, + "content": " ".join(alert_lines) + }) + continue + + # 5. 列表项 + if line.startswith("-") or line.startswith("*") or (re.match(r'^\d+\.', line)): + list_items = [] + while idx < len(body_lines) and (body_lines[idx].strip().startswith("-") or body_lines[idx].strip().startswith("*") or re.match(r'^\d+\.', body_lines[idx].strip())): + cleaned_item = re.sub(r'^[-*\d.]+\s+', '', body_lines[idx].strip()) + list_items.append(cleaned_item) + idx += 1 + components.append({ + "type": "list", + "items": list_items + }) + continue + + # 6. 普通段落 + p_lines = [line] + idx += 1 + while idx < len(body_lines): + next_line = body_lines[idx].strip() + if not next_line: + idx += 1 + break + # 如果下一行是任何其他区块的起点,直接中断 + if next_line.startswith("###") or next_line.startswith("##") or next_line.startswith("|") or next_line.startswith("```") or next_line.startswith(">") or next_line.startswith("-") or next_line.startswith("*") or re.match(r'^\d+\.', next_line): + break + p_lines.append(next_line) + idx += 1 + + components.append({ + "type": "paragraph", + "content": " ".join(p_lines) + }) + + sections.append({ + "title": heading, + "id": section_id, + "components": components + }) + + return {"success": True, "title": title, "sections": sections} + except Exception as e: + return {"success": False, "error": f"解析报告失败: {str(e)}"} + + +@app.get("/api/replay/available_dates") +def get_replay_available_dates(ticker: str = "TSLA"): + ticker = ticker.upper() + try: + # 获取 5d 1m 数据 + df = fetch_and_prepare_data(ticker, period="5d", interval="1m") + # 提取独特日期列表(按时间从近到远排序,转为字符串) + unique_dates = sorted(list(set(df.index.date.astype(str))), reverse=True) + return {"success": True, "dates": unique_dates[:5]} + except Exception as e: + return {"success": False, "error": str(e)} + + +@app.get("/api/replay/data") +def get_replay_data( + ticker: str = "TSLA", + date: str = None, + strategy_mode: str = "opening_breakout", + stop_loss_pct: float = 0.015, + profit_target_pct: float = 0.030, + trailing_stop_mode: str = "atr", + trailing_stop_atr_mult: float = 2.0, + rsi_threshold_buy: float = 65.0, + risk_per_trade_pct: float = 0.01, + max_position_size_pct: float = 0.50, + commission_per_share: float = 0.005, + slippage_rate: float = 0.0003, + market_open_focus: bool = True +): + ticker = ticker.upper() + try: + if not date: + return {"success": False, "error": "必须指定 date 参数"} + + # 1. 拉取 5d 1m 的数据 (包含前后日数据以计算正确的指标,如 EMA/RSI) + df_all = fetch_and_prepare_data(ticker, period="5d", interval="1m") + + # 2. 运行形态分析 + df_all = analyze_patterns(df_all) + + # 3. 筛选出指定日期的数据 + target_date = datetime.datetime.strptime(date, "%Y-%m-%d").date() + df_date = df_all[df_all.index.date == target_date].copy() + + if df_date.empty: + return {"success": False, "error": f"没有找到 {date} 对应的数据。"} + + # 4. 在该日期的数据上运行策略回测 + strategy_params = { + "strategy_mode": strategy_mode, + "stop_loss_pct": stop_loss_pct, + "profit_target_pct": profit_target_pct, + "trailing_stop_mode": trailing_stop_mode, + "trailing_stop_atr_mult": trailing_stop_atr_mult, + "rsi_threshold_buy": rsi_threshold_buy, + "market_open_focus": market_open_focus + } + + risk_params = { + "slippage_rate": slippage_rate, + "commission_per_share": commission_per_share, + "min_commission_per_order": 1.0, + "position_sizing_mode": "atr", + "risk_per_trade_pct": risk_per_trade_pct, + "max_position_size_pct": max_position_size_pct + } + + res = run_backtest_sim(df_date, ticker, strategy_params, risk_params, is_intraday=True) + + # 5. 整理 K线数据给前端 TradingView 图表渲染 + chart_candles = [] + for idx, r in df_date.iterrows(): + chart_candles.append({ + "time": int(idx.timestamp()), + "open": round(clean_float(r['Open']), 2), + "high": round(clean_float(r['High']), 2), + "low": round(clean_float(r['Low']), 2), + "close": round(clean_float(r['Close']), 2), + "volume": int(clean_float(r['Volume'])), + "vwap": round(clean_float(r['VWAP']), 2) if not pd.isna(r['VWAP']) else None, + "ema_9": round(clean_float(r['EMA_9']), 2) if not pd.isna(r['EMA_9']) else None, + "ema_21": round(clean_float(r['EMA_21']), 2) if not pd.isna(r['EMA_21']) else None, + "ema_50": round(clean_float(r['EMA_50']), 2) if not pd.isna(r['EMA_50']) else None, + "rsi": round(clean_float(r['RSI']), 1) if not pd.isna(r['RSI']) else None, + "squeeze": bool(r['Squeeze_On']) if not pd.isna(r['Squeeze_On']) else False, + "regime": r.get('Regime', 'range_bound') + }) + + # 整理买卖标记 (markers) + trade_markers = [] + for trade in res["ledger"]: + trade_time = int(pd.to_datetime(trade['timestamp']).timestamp()) + if trade['action'] == 'BUY': + trade_markers.append({ + "time": trade_time, + "position": "belowBar", + "color": "#00c805", + "shape": "arrowUp", + "text": f"BUY {trade['shares']}股 @ {trade['execution_price']:.2f}" + }) + elif trade['action'] == 'SELL': + pnl = trade.get('realized_pnl', 0.0) + color = "#ff3b30" if pnl < 0 else "#00c805" + text = f"SELL {trade['shares']}股 @ {trade['execution_price']:.2f} ({'+' if pnl>=0 else ''}{pnl:.2f})" + trade_markers.append({ + "time": trade_time, + "position": "aboveBar", + "color": color, + "shape": "arrowDown", + "text": text + }) + + return { + "success": True, + "ticker": ticker, + "date": date, + "summary": { + "initial_cash": float(res.get("initial_cash", 100000.0)), + "final_equity": float(res.get("final_equity", 100000.0)), + "net_pnl": float(res.get("net_pnl", 0.0)), + "pnl_pct": float(res.get("pnl_pct", 0.0)), + "total_trades": int(res.get("total_trades", 0)), + "round_trips": int(res.get("round_trips", 0)), + "win_rate": float(res.get("win_rate", 0.0)), + "commission": float(res.get("commission", 0.0)), + "max_drawdown": float(res.get("max_drawdown", 0.0)) + }, + "ledger": res["ledger"], + "candles": chart_candles, + "markers": trade_markers, + "equity_curve": res["equity_curve"] + } + except Exception as e: + import traceback + traceback.print_exc() + return {"success": False, "error": str(e)} + + +@app.get("/api/intraday_data") +def get_intraday_data(ticker: str, date: str): + ticker = ticker.upper() + try: + # 获取 5d 1m 的数据并计算指标 + df_all = fetch_and_prepare_data(ticker, period="5d", interval="1m") + df_all = analyze_patterns(df_all) + + # 筛选特定日期 + target_date = datetime.datetime.strptime(date, "%Y-%m-%d").date() + df_date = df_all[df_all.index.date == target_date] + + if df_date.empty: + return {"success": False, "error": f"没有找到 {date} 对应的日内数据"} + + chart_candles = [] + for idx, r in df_date.iterrows(): + chart_candles.append({ + "time": int(idx.timestamp()), + "open": round(clean_float(r['Open']), 2), + "high": round(clean_float(r['High']), 2), + "low": round(clean_float(r['Low']), 2), + "close": round(clean_float(r['Close']), 2), + "volume": int(clean_float(r['Volume'])), + "vwap": round(clean_float(r['VWAP']), 2) if not pd.isna(r['VWAP']) else None, + "ema_9": round(clean_float(r['EMA_9']), 2) if not pd.isna(r['EMA_9']) else None, + "ema_21": round(clean_float(r['EMA_21']), 2) if not pd.isna(r['EMA_21']) else None, + "ema_50": round(clean_float(r['EMA_50']), 2) if not pd.isna(r['EMA_50']) else None, + }) + return {"success": True, "ticker": ticker, "date": date, "candles": chart_candles} + except Exception as e: + return {"success": False, "error": str(e)} + + +@app.get("/api/broker/account") +def get_broker_account(): + """ + 获取 Alpaca 真实模拟盘账户资金和状态 + """ + from app.config import ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_BASE_URL + from app.broker.alpaca_adapter import AlpacaAdapter + + if not ALPACA_API_KEY or "your_paper_api_key_here" in ALPACA_API_KEY: + return { + "success": False, + "error": "Alpaca API 证书未配置。请在 backend/.env 中填写您的 ALPACA_API_KEY 和 ALPACA_API_SECRET。" + } + try: + adapter = AlpacaAdapter( + api_key=ALPACA_API_KEY, + api_secret=ALPACA_SECRET_KEY, + base_url=ALPACA_BASE_URL + ) + summary = adapter.get_account_summary() + return summary + except Exception as e: + return {"success": False, "error": f"连接 Alpaca 失败: {str(e)}"} + + +@app.get("/api/broker/positions") +def get_broker_positions(): + """ + 获取 Alpaca 真实模拟盘持仓列表 + """ + from app.config import ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_BASE_URL + from app.broker.alpaca_adapter import AlpacaAdapter + + if not ALPACA_API_KEY or "your_paper_api_key_here" in ALPACA_API_KEY: + return { + "success": False, + "error": "Alpaca API 证书未配置。请在 backend/.env 中填写您的 ALPACA_API_KEY 和 ALPACA_API_SECRET。" + } + try: + adapter = AlpacaAdapter( + api_key=ALPACA_API_KEY, + api_secret=ALPACA_SECRET_KEY, + base_url=ALPACA_BASE_URL + ) + positions = adapter.get_open_positions() + return {"success": True, "positions": positions} + except Exception as e: + return {"success": False, "error": f"获取持仓失败: {str(e)}"} + + +@app.post("/api/live/start") +def start_live_trading(req: LiveStartRequest): + success = live_runner.start(strategy_params=req.params, ignore_market_hours=req.ignore_market_hours) + return {"success": success, "status": live_runner.get_status()} + + +@app.post("/api/live/stop") +def stop_live_trading(): + success = live_runner.stop() + return {"success": success, "status": live_runner.get_status()} + + +@app.get("/api/live/status") +def get_live_status(): + return { + "success": True, + "status": live_runner.get_status(), + "logs": live_runner.logs + } + + +@app.post("/api/broker/cancel_orders") +def cancel_all_orders(): + from app.config import ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_BASE_URL + from app.broker.alpaca_adapter import AlpacaAdapter + try: + adapter = AlpacaAdapter(ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_BASE_URL) + res = adapter.cancel_all_orders() + live_runner.add_log("📢 用户手动触发:撤销所有未成交挂单。") + return res + except Exception as e: + return {"success": False, "error": str(e)} + + +@app.post("/api/broker/close_positions") +def close_all_positions(): + from app.config import ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_BASE_URL + from app.broker.alpaca_adapter import AlpacaAdapter + try: + adapter = AlpacaAdapter(ALPACA_API_KEY, ALPACA_SECRET_KEY, ALPACA_BASE_URL) + res = adapter.close_all_positions() + live_runner.add_log("🚨 用户手动触发:一键紧急平仓所有持仓!") + return res + except Exception as e: + return {"success": False, "error": str(e)} + + +if __name__ == "__main__": + print("启动 FastAPI 服务器于 http://127.0.0.1:8000 ...") + uvicorn.run("main_api:app", host="127.0.0.1", port=8000, reload=True) diff --git a/external/Quant.ai/backend/walk_forward.py b/external/Quant.ai/backend/walk_forward.py new file mode 100644 index 0000000000000000000000000000000000000000..0f02b1cbaecf419e30b79be96dfedc376617d1d9 --- /dev/null +++ b/external/Quant.ai/backend/walk_forward.py @@ -0,0 +1,184 @@ +# backend/walk_forward.py + +import argparse +import sys +import pandas as pd +import numpy as np +import os + +# 确保 backend 目录在 sys.path 中 +sys.path.append(os.path.dirname(os.path.abspath(__file__))) + +from app.data_manager import fetch_and_prepare_data +from app.patterns import analyze_patterns +from app.simulator import run_backtest_sim + +def walk_forward_optimization(ticker, interval="1d", period="2y", train_size=120, test_size=40): + """ + 运行滚动优化回测 (Walk-forward rolling optimization) + - 使用 train_size 根 K线作为训练集寻找最佳参数组合 + - 在随后的 test_size 根 K线中作为样本外测试执行该参数组合 + - 滚动前进,直到覆盖所有行情数据 + """ + print("=" * 80) + print(f" QUANT.AI - WALK-FORWARD OPTIMIZER (滚动参数优化引擎)") + print(f" 标的代码: {ticker} | 周期: {interval} | 区间: {period} | 训练集大小: {train_size} | 测试集大小: {test_size}") + print("=" * 80) + + # 1. 抓取与清洗指标数据 + try: + df_raw = fetch_and_prepare_data(ticker, period=period, interval=interval) + df = analyze_patterns(df_raw) + except Exception as e: + raise ValueError(f"数据加载或指标计算失败: {str(e)}") + + total_len = len(df) + if total_len < (train_size + test_size): + raise ValueError(f"错误:历史数据共 {total_len} 根 Bar,不足以支持当前 Train({train_size}) + Test({test_size}) 的滚动窗口分配!") + + print(f"行情数据准备就绪:共包含 {total_len} 根 K 线。") + print("正在生成参数搜索网格...") + + # 2. 定义参数网格 + param_grid = [] + for mode in ["dynamic", "consensus"]: + for atr_mult in [1.5, 2.0, 2.5]: + for rsi_th in [60.0, 65.0, 70.0]: + param_grid.append({ + "strategy_mode": mode, + "trailing_stop_atr_mult": atr_mult, + "rsi_threshold_buy": rsi_th, + "stop_loss_pct": 0.015, + "profit_target_pct": 0.030 + }) + + risk_params = { + "slippage_rate": 0.0003, + "commission_per_share": 0.005, + "min_commission_per_order": 1.0, + "position_sizing_mode": "atr", + "risk_per_trade_pct": 0.01, + "max_position_size_pct": 0.50 + } + + # 3. 滚动窗口优化循环 + start_idx = 0 + oos_results = [] + + is_intraday = interval in ["1m", "5m", "15m", "30m", "1h"] + + print("\n[开始滚动优化]") + window_count = 1 + + while start_idx + train_size + test_size <= total_len: + train_df = df.iloc[start_idx : start_idx + train_size] + test_df = df.iloc[start_idx + train_size : start_idx + train_size + test_size] + + train_start_date = train_df.index[0].strftime("%Y-%m-%d") + train_end_date = train_df.index[-1].strftime("%Y-%m-%d") + test_start_date = test_df.index[0].strftime("%Y-%m-%d") + test_end_date = test_df.index[-1].strftime("%Y-%m-%d") + + # 寻找训练集上的最佳参数 + best_score = -999999.0 + best_params = None + + for params in param_grid: + res = run_backtest_sim(train_df, ticker, params, risk_params, is_intraday=is_intraday) + # 目标函数:净亏损惩罚下的净利润收益 (Sharpe-like Objective) + score = res["net_pnl"] - (res["max_drawdown"] * 30000.0 * 2.0) + if score > best_score: + best_score = score + best_params = params + + # 使用最佳参数在测试集上回测(样本外测试) + test_res = run_backtest_sim(test_df, ticker, best_params, risk_params, is_intraday=is_intraday) + + print(f" 窗口 #{window_count} | 训练集: {train_start_date} ~ {train_end_date} | 测试集: {test_start_date} ~ {test_end_date}") + print(f" -> 最佳参数: Mode={best_params['strategy_mode']}, ATR_Mult={best_params['trailing_stop_atr_mult']}, RSI={best_params['rsi_threshold_buy']}") + print(f" -> 样本外表现: 盈亏 ${test_res['net_pnl']:+,.2f} | 最大回撤 {test_res['max_drawdown']*100:.2f}% | 交易对数 {test_res['round_trips']} | 胜率 {test_res['win_rate']}%") + + oos_results.append({ + "window": window_count, + "train_period": f"{train_start_date} ~ {train_end_date}", + "test_period": f"{test_start_date} ~ {test_end_date}", + "best_params": best_params, + "net_pnl": test_res["net_pnl"], + "max_drawdown": test_res["max_drawdown"], + "round_trips": test_res["round_trips"], + "win_rate": test_res["win_rate"], + "commission": test_res["commission"] + }) + + # 前进一个测试集步长 + start_idx += test_size + window_count += 1 + + # 4. 对照组:在整个数据集上运行静态默认参数 + default_params = { + "strategy_mode": "dynamic", + "trailing_stop_atr_mult": 2.0, + "rsi_threshold_buy": 65.0, + "stop_loss_pct": 0.015, + "profit_target_pct": 0.030 + } + static_res = run_backtest_sim(df, ticker, default_params, risk_params, is_intraday=is_intraday) + + # 5. 汇总 Walk-forward 表现 + total_wf_pnl = sum(r["net_pnl"] for r in oos_results) + total_wf_commission = sum(r["commission"] for r in oos_results) + avg_wf_drawdown = float(np.mean([r["max_drawdown"] for r in oos_results])) if oos_results else 0.0 + total_wf_trades = sum(r["round_trips"] for r in oos_results) + + print("\n" + "=" * 80) + print(" WALK-FORWARD PERFORMANCE VS STATIC CONTROL") + print("=" * 80) + print(f" 【滚动参数优化 (Walk-Forward) 样本外表现】:") + print(f" - 累计样本外净利润: $ {total_wf_pnl:+,.2f}") + print(f" - 总交易笔数(对): {total_wf_trades} 笔") + print(f" - 佣金支出总计: $ {total_wf_commission:,.2f}") + print(f" - 平均滚动最大回撤: {avg_wf_drawdown*100:.2f}%") + print("-" * 80) + print(f" 【静态默认参数 (Static Default) 全样本对照组表现】:") + print(f" - 累计净利润: $ {static_res['net_pnl']:+,.2f} ({static_res['pnl_pct']:+.2f}%)") + print(f" - 总交易笔数(对): {static_res['round_trips']} 笔") + print(f" - 佣金支出总计: $ {static_res['commission']:,.2f}") + print(f" - 全历史最大回撤: {static_res['max_drawdown']*100:.2f}%") + print("=" * 80) + + return { + "ticker": ticker, + "interval": interval, + "period": period or "1y", + "train_size": train_size, + "test_size": test_size, + "oos_results": oos_results, + "static_control": { + "net_pnl": static_res["net_pnl"], + "pnl_pct": static_res["pnl_pct"], + "round_trips": static_res["round_trips"], + "commission": static_res["commission"], + "max_drawdown": static_res["max_drawdown"] + }, + "summary": { + "total_wf_pnl": total_wf_pnl, + "total_wf_commission": total_wf_commission, + "avg_wf_drawdown": avg_wf_drawdown, + "total_wf_trades": total_wf_trades + } + } + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description="Walk-Forward Rolling Parameter Optimizer") + parser.add_argument("--ticker", type=str, default="TSLA", help="测试股票代码 (默认: TSLA)") + parser.add_argument("--interval", type=str, default="1d", help="K线周期 (默认: 1d)") + parser.add_argument("--period", type=str, default="1y", help="总历史时间段 (默认: 1y)") + parser.add_argument("--train", type=int, default=120, help="训练集 K线根数 (默认: 120)") + parser.add_argument("--test", type=int, default=40, help="测试集 K线根数 (默认: 40)") + + args = parser.parse_args() + try: + walk_forward_optimization(args.ticker, args.interval, args.period, args.train, args.test) + except Exception as e: + print(e) + sys.exit(1) diff --git a/external/Quant.ai/deep-research-report.md b/external/Quant.ai/deep-research-report.md new file mode 100644 index 0000000000000000000000000000000000000000..149abfb95ef5997001b2ac84bd4fdd46d7ba8331 --- /dev/null +++ b/external/Quant.ai/deep-research-report.md @@ -0,0 +1,620 @@ +# 日线为主的全自动炒股软件开发分析报告 + +## 执行摘要 + +你的目标是做一套“以日线为主、手工式交易风格、但完全自动执行”的股票交易系统,并把目标表达为**长期平均每天净赚 500 美元**。从系统工程角度看,这个目标可以被拆成三个问题:一是是否存在**长期正期望**;二是资金规模能否把这个期望放大到 500 美元/日;三是系统是否能在**回测—模拟盘—实盘**迁移过程中不被交易成本、执行偏差、制度约束和过拟合吞噬。学术和工程证据都支持“趋势、动量、短期反转、配对/相对价值”这些策略族在特定市场与样本下曾经有效,但也同时显示,参数搜索、样本内挑选和数据窥探会显著放大虚假优势,因此回测与上线治理和策略本身同等重要。citeturn12search8turn12search5turn12search6turn14search0turn13search3turn15search0turn15search1 + +如果把“平均每天净赚 500 美元”近似成“每年净赚 12.5 万美元”,那么**资金规模**几乎决定了目标的现实性。按近似计算,本金 5 万美元对应约 250% 年化净收益目标,本金 10 万美元对应约 125%,本金 25 万美元对应约 50%,本金 50 万美元对应约 25%,本金 100 万美元对应约 12.5%。前两档对日线股票系统通常过于激进;25 万美元以上仍然困难,但开始进入“可以通过多策略、严格风控、稳定执行去争取”的区间;50 万到 100 万美元更符合“日线主导、低频执行、追求稳健”的现实路径。这个结论不代表保证收益,而是提醒你:**目标收益最终必须和本金、容忍回撤、杠杆、交易品种与可做空能力一起设计**。 + +本报告的核心结论有四条。第一,**K 线形态不要直接当“神谕”**,应当把 K 线拆解为可度量特征,例如实体占比、上下影线、缺口、趋势上下文、量能确认,再与指标和风险规则组合使用。第二,针对“日线为主”的软件,最值得优先编码的不是几十个花式模型,而是三组主策略:**趋势/突破、低 ADX 环境下的均值回归、以及带市场过滤的波段/动量**。第三,任何参数建议都只能作为**起始网格**,不能把“历史最优点”直接上线;你必须做样本外检验、滚动回测、Walk-forward、PBO/DSR 检测和成本压力测试。第四,实盘成功与否,往往不是因为指标公式,反而是因为**数据口径、除权复权、交易日历、回报对账、异常告警、回滚机制和合规边界**是否处理完整。citeturn15search0turn15search1turn15search18turn30search4turn21view1 + +从开发优先级看,我建议你按以下顺序落地:先做**单市场、单币种、单边做多**版本;先上**一到两个可解释策略**,而不是“全家桶”;先做**严格风控与回测框架**,再堆叠指标;最后再扩到配对交易、指数对冲和日内/日线混合执行。对于股票现货,制度差异也非常关键:A 股普通股票存在“买入证券在交收前不得卖出,除非属于当日回转交易品种”的约束,而上交所、深交所又对程序化交易设有报告和管理规则;美股则有 9:30–16:00 ET 常规交易时段、保证金和日内保证金要求、税务申报和数据订阅限制。你的架构必须从一开始就把这些差异做成**市场适配层**,而不是写死在策略内部。citeturn43search5turn25view1turn19view10turn41search2turn41search4turn16search0 + +## 关键目标与约束 + +下表把你已经明确和“未指定”的项目,转成开发规格。 + +| 项目 | 当前状态 | 工程含义 | +|---|---|---| +| 目标收益 | 平均每天净赚 500 美元 | 必须把目标分解为:日均净值增长目标、最大可接受回撤、所需资金规模、策略容量 | +| 风险容忍度 | 未指定 | 不能直接给仓位上限;默认应从保守值开始,例如单笔风险 0.25%–0.75% 权益 | +| 交易品种 | 未指定 | 代码必须做市场抽象层:A 股/美股/ETF/指数 ETF/可转债/港股各自交易规则不同 | +| 资金规模 | 未指定 | 决定目标收益可行性,也决定是否需要杠杆、是否需要多策略并行 | +| 是否允许杠杆 | 未指定 | 必须把杠杆开关、融资利率、保证金规则、强平逻辑写成配置项 | +| 交易时段 | 日线为主 | 信号主周期建议为日线;下单可选择收盘、次日开盘、次日 VWAP、条件单或分批执行 | + +如果你做的是**A 股普通股票**,上交所现行规则明确,投资者买入的证券在交收前不得卖出,但实行当日回转交易的品种除外;上交所现行竞价交易时段为 9:15–9:25 开盘集合竞价,9:30–11:30 与 13:00–14:57 连续竞价,14:57–15:00 收盘集合竞价。若采用程序化交易,交易所的程序化交易管理实施细则已于 2025 年生效,且深交所规则明确把**个人投资者**也纳入程序化交易投资者范围,首次进行程序化交易前须履行报告义务。citeturn43search5turn18search3turn25view1turn24search2 + +如果你做的是**美股**,纳斯达克常规交易时段为周一至周五 9:30–16:00 ET;保证金方面,FINRA 概览页说明 Reg T 一般允许客户借入新开仓股票买入价的 50%,而自 2026 年 6 月 4 日起,FINRA Rule 4210 已切换到新的**日内保证金**框架,日内保证金要求取代了旧的 PDT 规则逻辑。也就是说,美股若允许杠杆,你必须把保证金检查和经纪商风控回报实时纳入系统,而不是只在日终核算。citeturn19view10turn41search2turn41search4turn41search7 + +基于这些约束,建议你的第一版系统采用下面这种“最小可行交易域”: + +| 维度 | 第一版建议 | +|---|---| +| 市场 | 先二选一:A 股或美股,不建议首版跨市场 | +| 标的池 | 先做流动性较好的 50–300 只股票或 ETF 白名单 | +| 方向 | 先做单边长仓;若做空,再单独加借券/融券层 | +| 周期 | 信号用日线;执行可选次日开盘/限价/VWAP | +| 持有期 | 2–40 个交易日的波段化持有,避免一开始就做超长趋势或高频 | +| 策略数 | 先 1–2 个主策略 + 1 个统一风控引擎 | +| 回测口径 | 默认使用复权收盘生成信号、原始价执行、成本单独建模 | + +## K线形态与技术指标 + +### K线应先被拆成特征,而不是先背名字 + +行业里常见的 K 线“形态名词库”非常庞大。TA-Lib 的 Pattern Recognition Functions 本身就列出了大批模式识别接口,包括 Doji、Hammer、Engulfing、Morning Star、Evening Star、Three White Soldiers、Three Black Crows、Tasuki Gap、Rising/Falling Three Methods 等几十类模式。工程上最稳妥的做法,不是先追求“全叫得出名字”,而是先把 K 线拆成**稳定、可复用、可组合**的数值特征,再在此基础上构建形态检测器。citeturn32view0turn31view1turn31view3 + +建议你先统一定义一组基础特征: + +| 特征名 | 定义 | 作用 | +|---|---|---| +| `range` | `high - low` | 当日波动区间 | +| `body` | `abs(close - open)` | 实体大小 | +| `body_ratio` | `body / max(range, eps)` | 强弱实体占比 | +| `upper_shadow` | `high - max(open, close)` | 上影线 | +| `lower_shadow` | `min(open, close) - low` | 下影线 | +| `upper_ratio` | `upper_shadow / max(body, eps)` | 上影线相对实体比例 | +| `lower_ratio` | `lower_shadow / max(body, eps)` | 下影线相对实体比例 | +| `gap_up` | `low > prev_high` | 向上缺口 | +| `gap_down` | `high < prev_low` | 向下缺口 | +| `trend_up_ctx` | `ema20 > ema50 and slope(ema20,5)>0` | 上升趋势上下文 | +| `trend_down_ctx` | `ema20 < ema50 and slope(ema20,5)<0` | 下降趋势上下文 | +| `rv` | `volume / sma(volume,20)` | 量能确认 | + +一个可以直接移植的基础工具层伪代码如下: + +```pseudo +function candle_features(bar, prev_bar, ema20, ema50, vol_ma20): + range = max(bar.high - bar.low, EPS) + body = abs(bar.close - bar.open) + upper_shadow = bar.high - max(bar.open, bar.close) + lower_shadow = min(bar.open, bar.close) - bar.low + + return { + bull: bar.close > bar.open, + bear: bar.close < bar.open, + range: range, + body: body, + body_ratio: body / range, + upper_ratio: upper_shadow / max(body, EPS), + lower_ratio: lower_shadow / max(body, EPS), + gap_up: bar.low > prev_bar.high, + gap_down: bar.high < prev_bar.low, + rv: bar.volume / max(vol_ma20, EPS), + trend_up_ctx: ema20 > ema50 and slope(ema20, 5) > 0, + trend_down_ctx: ema20 < ema50 and slope(ema20, 5) < 0 + } +``` + +### 常见日线 K 线形态与量化判定 + +下表覆盖了**最值得先编码**的主流日线形态。阈值不是唯一标准,而是为了便于落地为代码;你之后可以把这些阈值做成配置项,配合 Walk-forward 优化,而不是硬编码成“真理”。 + +| 形态 | 心理学含义 | 建议量化判定 | +|---|---|---| +| 长阳线 | 买方全天主导,趋势延续概率上升 | `bull and body_ratio >= 0.6 and upper_ratio <= 0.3 and lower_ratio <= 0.3` | +| 长阴线 | 卖方全天主导,弱势延续概率上升 | `bear and body_ratio >= 0.6 and upper_ratio <= 0.3 and lower_ratio <= 0.3` | +| 十字星 Doji | 多空犹豫,拐点或中继,需结合上下文 | `body_ratio <= 0.1` | +| 锤头 Hammer | 下探后被强力拉回,常见于下跌末端 | `lower_ratio >= 2.0 and upper_ratio <= 0.5 and body_ratio <= 0.35 and trend_down_ctx` | +| 上吊线 Hanging Man | 上涨后的“锤头”,常是风险预警 | 同锤头,但要求 `trend_up_ctx` | +| 倒锤头 Inverted Hammer | 下跌后试探反攻 | `upper_ratio >= 2.0 and lower_ratio <= 0.5 and body_ratio <= 0.35 and trend_down_ctx` | +| 射击之星 Shooting Star | 上涨后冲高回落,卖压出现 | 与倒锤相同,但要求 `trend_up_ctx` | +| 光头光脚 Marubozu | 极强单边推进 | `body_ratio >= 0.8 and upper_ratio <= 0.1 and lower_ratio <= 0.1` | +| 纺锤线 Spinning Top | 有波动但收盘拉回中性,方向不明 | `0.1 < body_ratio < 0.35 and upper_ratio > 0.5 and lower_ratio > 0.5` | +| 看涨吞没 Engulfing | 强反包,常见于反转起点 | 前一根为阴线,后一根为阳线,且 `curr.open <= prev.close and curr.close >= prev.open` | +| 看跌吞没 Engulfing | 强反包下压 | 前一根为阳线,后一根为阴线,且 `curr.open >= prev.close and curr.close <= prev.open` | +| 刺透 Piercing | 下跌后强力回补,偏反转 | 前阴后阳;后一根收盘进入前阴实体 50% 以上但未完全吞没 | +| 乌云盖顶 Dark Cloud Cover | 上涨后被打回,偏反转 | 前阳后阴;后一根收盘跌入前阳实体 50% 以上 | +| 孕线 Harami | 波动收缩,方向待确认 | 当前实体完全落在前一根实体内部 | +| 启明星 Morning Star | 三日见底结构 | 大阴 + 小实体犹豫 + 大阳并收回第一根实体至少 50% | +| 黄昏星 Evening Star | 三日见顶结构 | 大阳 + 小实体犹豫 + 大阴并跌回第一根实体至少 50% | +| 红三兵 | 多头连续推进,趋势强化 | 连续三根阳线,收盘逐步抬高,回撤小 | +| 三只乌鸦 | 空头连续推进,趋势恶化 | 连续三根阴线,收盘逐步下移,反抽小 | +| 上升三法 / 下降三法 | 强趋势中的整理后延续 | 外层长实体 + 中间若干逆向小实体 + 最后一根顺势突破 | +| 缺口突破/竭尽缺口 | 价格重定价,需配量能与上下文 | `gap_up` 或 `gap_down`,并要求 `rv >= 1.5` 与趋势上下文一致 | + +这些模式都能直接映射到 TA-Lib 已公开的模式接口命名,例如 `CDLDOJI`、`CDLHAMMER`、`CDLENGULFING`、`CDLMORNINGSTAR`、`CDLEVENINGSTAR`、`CDL3WHITESOLDIERS`、`CDL3BLACKCROWS`、`CDLRISEFALL3METHODS`、`CDLTASUKIGAP` 等;如果你希望最大覆盖,可以把“本报告阈值版模式检测器”与“TA-Lib 整数输出版模式检测器”并行实现,前者便于自定义,后者便于做基准对照。citeturn32view0turn31view1turn31view2turn31view3 + +下面给出几个最常用的可编码伪代码模板: + +```pseudo +function is_hammer(f): + return f.lower_ratio >= 2.0 + and f.upper_ratio <= 0.5 + and f.body_ratio <= 0.35 + and f.trend_down_ctx + +function bullish_engulfing(prev, curr): + return prev.close < prev.open + and curr.close > curr.open + and curr.open <= prev.close + and curr.close >= prev.open + +function morning_star(b1, b2, b3): + first_big_down = b1.close < b1.open and abs(b1.close-b1.open)/(b1.high-b1.low) >= 0.6 + second_small = abs(b2.close-b2.open)/(b2.high-b2.low) <= 0.25 + third_big_up = b3.close > b3.open and abs(b3.close-b3.open)/(b3.high-b3.low) >= 0.6 + reclaim = b3.close >= b1.open - 0.5 * abs(b1.open - b1.close) + return first_big_down and second_small and third_big_up and reclaim +``` + +### 主流技术指标、公式、信号与参数建议 + +SMA、EMA、MACD、RSI、布林带、ADX、ATR、OBV 这些“老指标”之所以还常用,不是因为它们神奇,而是因为它们分别从**趋势、动量、波动率、方向强度和量价确认**这几个维度提供了稳定特征。Sierra Chart 的官方技术指标参考给出了 SMA、EMA、MACD、RSI、Bollinger Bands、ADX、ATR、OBV 等公式;其中 SMA 为区间均值,EMA 使用 \(2/(n+1)\) 平滑因子,MACD 是快慢 EMA 差,RSI 基于涨跌均值比,布林带是均线加减标准差,ADX 由 DMI/DI 推导,ATR 来自 True Range 的均值,OBV 则是按涨跌方向累加/扣减成交量。citeturn40view0turn39view0turn19view2turn34view2turn33view1turn35view2turn36view0turn37search7turn38view1 + +| 指标 | 核心公式/特征 | 典型信号 | 日线起始参数建议 | 简洁伪代码 | +|---|---|---|---|---| +| SMA | 区间均值;更平滑,滞后更大 | 短均线上穿长均线;均线斜率转正 | `10/20/50/100/200` | `sma[t]=mean(close[t-n+1:t])` | +| EMA | 对近期更敏感;平滑因子 `2/(n+1)` | 适合做趋势状态与动态支撑阻力 | `9/20/50/100` | `ema[t]=a*close[t]+(1-a)*ema[t-1]` | +| MACD | `EMA_fast - EMA_slow`,再求信号线 | 金叉/死叉、零轴上方/下方、柱体扩张 | `12,26,9` 起步;优化网格可测 `8–15,20–35,5–12` | `macd=ema12-ema26; sig=ema(macd,9)` | +| RSI | 涨跌幅相对强度,0–100 区间 | 超卖/超买、50 中轴、背离 | 经典 `14`;短反转可试 `2/3/5`,趋势可试 `14/21` | `rsi=100-100/(1+avg_up/avg_down)` | +| 布林带 | `SMA ± k*std` | 触下轨反弹、挤压后突破、中轨回归 | `20,2` 起步;可测 `10/20/30` 与 `1.5/2/2.5` | `mid=sma20; up=mid+k*std20; dn=mid-k*std20` | +| ATR | True Range 的均值,衡量波动 | 止损距离、仓位缩放、过滤低波动假突破 | `14` 常用;止损乘数 `1.5–3.0` | `atr=sma(tr,14)` | +| ADX + DI | 趋势强度而非方向 | `ADX>20/25` 认为趋势环境增强;`+DI/-DI` 给方向 | `14` 常用 | `adx=wwma(dx,14)` | +| OBV | 上涨日加量、下跌日减量 | 量价背离、突破确认 | `OBV` 配合 `OBV_MA(10/20)` | `obv += vol if close>prev_close else -vol` | +| Donchian | N 日最高/最低通道 | 趋势突破、海龟系统 | `20/55` 常用 | `upper=max(high,n); lower=min(low,n)` | +| Keltner | EMA 中轨 ± ATR 通道 | 与布林挤压组合看波动释放 | `20 EMA, 2 ATR` | `up=ema20 + 2*atr20` | +| ROC / Momentum | 过去 N 日涨幅 | 动量排序、过滤弱票 | `20/60/120/252` | `roc=close/close[-n]-1` | +| 相对量能 RVOL | 当前量/均量 | 突破确认、假信号过滤 | `vol / SMA(vol,20)` | `rv=vol/sma(vol,20)` | + +下面给出一组建议直接落地的指标函数模板: + +```pseudo +function sma(series, n): return rolling_mean(series, n) + +function ema(series, n): + a = 2.0 / (n + 1.0) + ema[0] = series[0] + for t in 1..len(series)-1: + ema[t] = a * series[t] + (1 - a) * ema[t-1] + return ema + +function macd(close, fast=12, slow=26, sig=9): + fast_line = ema(close, fast) + slow_line = ema(close, slow) + macd_line = fast_line - slow_line + signal = ema(macd_line, sig) + hist = macd_line - signal + return macd_line, signal, hist + +function rsi(close, n=14): + up = max(close[t]-close[t-1], 0) + dn = max(close[t-1]-close[t], 0) + rs = ma(up, n) / max(ma(dn, n), EPS) + return 100 - 100 / (1 + rs) + +function atr(high, low, close, n=14): + tr = max(high-low, abs(high-prev_close), abs(low-prev_close)) + return ma(tr, n) + +function adx(high, low, close, n=14): + +dm = max(high-prev_high, 0) if high-prev_high > prev_low-low else 0 + -dm = max(prev_low-low, 0) if prev_low-low > high-prev_high else 0 + tr = ... + +di = 100 * wilder_sum(+dm,n) / max(wilder_sum(tr,n), EPS) + -di = 100 * wilder_sum(-dm,n) / max(wilder_sum(tr,n), EPS) + dx = 100 * abs(+di - -di) / max(+di + -di, EPS) + adx = wilder_ma(dx, n) + return +di, -di, adx +``` + +参数优化时,不要直接寻找“历史收益最高”的点,而要看**稳定区**。一个参数组合如果在 12/26/9、10/24/8、14/30/10 一片区域里都差不多有效,可信度远高于某个孤立尖峰。PBO 和 DSR 文献正是为了解决“你是不是只是把参数拟合到了噪声上”这个问题。citeturn15search0turn15search1 + +## 量化策略清单 + +### 先做“市场状态识别”,再选择策略 + +对日线系统而言,最常见的错误不是策略太少,而是**在错误的市场状态使用了错误的策略**。趋势策略怕震荡;均值回归怕单边;突破策略怕低流动和假信号;配对交易怕协整关系失效。因此建议你先实现一个**Regime Router**,把市场粗分为趋势、震荡、极端波动/风控收缩三类,再决定启用哪个子策略。 + +```mermaid +flowchart TD + A[日线OHLCV与市场指数] --> B[特征计算] + B --> C[趋势强度 ADX / 均线斜率 / 波动率分位数] + C --> D{市场状态} + D -->|趋势强化| E[趋势跟踪 / 突破] + D -->|震荡低趋势| F[均值回归 / 配对] + D -->|高波动高不确定| G[减仓 / 空仓 / 仅执行防守] + E --> H[统一风控] + F --> H + G --> H + H --> I[次日订单计划] +``` + +趋势跟踪、时间序列动量和简单均线过滤在长期跨市场研究中显示出可持续性;横截面动量在股票市场的 3–12 个月区间也有长期文献支持;短期反转和配对交易同样有经典研究基础。下面的胜率、回撤区间并不是“官方数字”,而是基于这些文献揭示的收益形态与实盘工程经验做的**保守推断**,目的是给你提供代码参数的起点,而不是给出保证。citeturn12search8turn12search5turn12search6turn14search0turn13search1turn13search3 + +| 策略族 | 核心逻辑 | 入场规则 | 出场/止损/止盈 | 适用市场 | 优点 | 缺点 | 经验胜率/回撤区间 | +|---|---|---|---|---|---|---|---| +| 趋势跟踪 | 顺中期趋势持有,吃大波段 | `EMA20>EMA50>EMA200` 且 `ADX>20`,回踩均线转强或创 20/55 日新高 | 跌破 `EMA20/EMA50`、或 `2–3 ATR` 追踪止损;通常不设固定止盈 | 单边趋势、行业领涨阶段 | 正偏收益,大单盈利能覆盖多次小亏 | 震荡期来回打脸 | 胜率约 35%–50%,组合级 MDD 常见 15%–35% | +| 均值回归 | 偏离均线/布林后向均值回归 | `ADX<18`、`close donchian_high(20/55)` 且 `RVOL>1.5`,可配 `ADX` | 假突破回落、跌破短通道、`2 ATR` 止损 | 波动收缩后释放、业绩/事件驱动 | 简单、可解释、易自动化 | 假突破多 | 胜率约 35%–50%,MDD 常见 12%–30% | +| 指数对冲波段 | 个股 alpha + 指数 beta 对冲 | 多头信号成立,同时按 beta 对冲股指/ETF | 多头失效或 beta 变化时同步平仓 | 大盘高波动、又想压系统回撤 | 回撤更可控 | 执行复杂,需更强数据 | 胜率约 45%–60%,MDD 常见 8%–20% | +| 配对交易 | 价差偏离后收敛 | 先做相关/协整筛选,再在 spread z-score 超阈值时反向开仓 | `z=0` 附近回补;`|z|` 继续扩大即止损 | 同行业、高相关、相对价值行情 | 市场方向依赖低 | 关系失效时很伤 | 胜率约 50%–65%,MDD 常见 8%–20% | +| 波段交易 | 趋势中做回撤,震荡中做边界 | 上升趋势里等回踩 `EMA20 + RSI回落`;下降趋势镜像做空或回避 | 回到前高/通道中上轨止盈;破结构点止损 | 日线主导、手工风格最像 | 解释性强,适合“人工风格自动化” | 规则边界多,易主观化 | 胜率约 45%–60%,MDD 常见 10%–25% | +| 日内/日线混合 | 日线定方向,日内优化执行 | EOD 生成交易计划;次日开盘、VWAP、分时量能确认后执行 | 以日线失效为主,日内只做执行停损 | 股票容量较大、想降低冲击成本 | 能改善成交均价 | 系统复杂度上升 | 胜率取决于母策略,MDD 通常略低于裸日线执行 | + +下面给出每个策略都能直接复用的一套“统一信号骨架”。你只需要替换 `entry_condition`、`exit_condition` 和 `regime_filter`。 + +```pseudo +function run_strategy(bar, features, state, cfg): + if state.kill_switch: + return NO_ACTION + + if not position_exists(bar.symbol): + if regime_filter(features, cfg) + and entry_condition(features, cfg) + and liquidity_filter(features, cfg) + and market_filter(features.market, cfg): + stop_price = compute_initial_stop(bar, features, cfg) + qty = size_by_risk(account, bar.close, stop_price, cfg) + return BUY(qty, bar.symbol, stop_price) + else: + if exit_condition(features, cfg) or hard_stop_hit(bar, position): + return SELL_ALL(bar.symbol) + else: + maybe_trail_stop(position, features, cfg) + return NO_ACTION +``` + +再给出适合首版上线的几个具体模板。 + +```pseudo +# 趋势跟踪 +entry = close > donchian_high(55) and ema20 > ema50 and ema50 > ema200 and adx > 20 +exit = close < ema20 or close < donchian_low(20) +stop = entry_price - 2.5 * ATR(14) + +# 均值回归 +entry = adx < 18 and close < bb_lower(20,2) and rsi(2) < 10 and rv < 2.5 +exit = close >= bb_mid(20) or rsi(2) > 70 +stop = entry_price - 1.5 * ATR(14) +time_stop = 5 bars + +# 波段回踩 +entry = ema20 > ema50 and close between ema20 and ema20-1*ATR and rsi(5) rising from < 40 +exit = close >= recent_swing_high or close < ema50 +stop = recent_swing_low - 0.5 * ATR +``` + +对你这种“人工式风格”的目标,我建议**优先顺序**是:先做“波段回踩 + 趋势突破”的双模块;第二步再加“低 ADX 的均值回归”作为震荡期替补;第三步才上配对和指数对冲。这样更符合日线交易软件的可维护性。 + +## 风控与资金管理 + +对自动交易系统来说,**风控不是策略的附属品,而是第一策略**。同样的进场信号,在不同的仓位、相关性约束、撤退机制和成本模型下,最终实盘表现可能天差地别。A 股程序化交易规则要求程序化交易投资者满足可用性、安全性和合规性要求,不得影响系统安全和正常交易秩序;美股若使用保证金,FINRA 和 Reg T 会共同决定初始和日内保证金要求。这意味着你的风控层至少要有三层:**交易前风控、持仓中风控、账户级风控**。citeturn25view1turn41search2turn41search4 + +### 建议直接写入代码的风控规则 + +| 风控项 | 建议起始值 | 代码含义 | +|---|---|---| +| 单笔最大风险 | 权益的 `0.25%–0.75%` | 用于根据止损距离反推股数 | +| 单票最大市值占比 | `5%–12%` | 防止单股黑天鹅 | +| 单行业最大敞口 | `20%–30%` | 防止板块同涨同跌放大回撤 | +| 同时持仓数 | `4–12` | 控制组合相关性与复杂度 | +| 组合级最大毛敞口 | 无杠杆先 `<=100%` | 首版尽量不满杠杆 | +| 组合级软回撤阈值 | `6%–8%` | 触发后风险减半 | +| 组合级硬回撤阈值 | `10%–12%` | 停止新开仓,仅允许减仓/平仓 | +| 日内执行损失阈值 | `1R` 或 `1%` 权益 | 若你有日内执行层,达到就停单 | +| 连续亏损熔断 | `5–7` 笔 | 连亏后把风险系数下调 50% | +| 异常波动停机 | 成交异常/数据断流/API 失败 | 立即进入保护模式 | + +仓位控制建议至少同时支持以下三种算法。 + +| 算法 | 公式 | 适用场景 | 风险提示 | +|---|---|---|---| +| 固定比例风险 | `qty = equity * risk_pct / stop_distance` | 首版最推荐 | 简单稳健 | +| 波动率目标 | `weight ∝ 1 / volatility` | 多标的组合 | 需要稳定波动估计 | +| 分数 Kelly | `f = edge / variance` 再乘 `0.25` | 有较成熟胜率/赔率估计时 | 对参数极敏感,不建议满 Kelly | + +固定比例风险是最适合首版系统的。它把“你愿意为这笔想法亏多少钱”作为第一原则,而不是“这只票该买多少股”。伪代码如下: + +```pseudo +function size_by_risk(account, entry_price, stop_price, cfg): + risk_dollar = account.equity * cfg.risk_per_trade + stop_distance = abs(entry_price - stop_price) + raw_qty = floor(risk_dollar / max(stop_distance, EPS)) + max_qty_by_value = floor(account.equity * cfg.max_position_pct / entry_price) + qty = min(raw_qty, max_qty_by_value) + return max(qty, 0) +``` + +账户级熔断建议写得更硬,而不是留给主观判断: + +```pseudo +function account_kill_switch(account, perf, cfg): + if perf.max_drawdown_from_peak >= cfg.hard_dd: + return HARD_STOP + if perf.current_month_drawdown >= cfg.monthly_dd_limit: + return REDUCE_RISK_50 + if perf.consecutive_losses >= cfg.max_consecutive_losses: + return REDUCE_RISK_50 + if perf.api_errors >= cfg.api_error_limit or perf.data_stale: + return PROTECTIVE_MODE + return NORMAL +``` + +### 成本、滑点、杠杆与保证金 + +回测成本必须**比你现在想象的更保守**。IBKR 的官方佣金页显示,美国股票/ETF 的 IBKR Pro Fixed 为每股 0.005 美元、最低每单 1 美元;Tiered 则按月成交量分档,起始可低至每股 0.0035 美元、最低每单 0.35 美元。Alpaca 对部分零售账户提供美股 API 免佣,但官方也明确某些合作安排不一定享受免佣,且仍可能有经纪业务费用或监管费用。工程上应把这些经纪商公告当作**成本下限**,而不是回测成本上限。citeturn28search0turn28search3turn28search1turn28search11 + +建议你的成本模型这样写: + +| 成本项 | 回测建议 | +|---|---| +| 佣金 | `max(固定每单, 每股佣金, 百分比佣金)` 三者择高 | +| 滑点 | 大盘股日线单次 2–5 bps 起步;中小盘 5–20 bps 起步 | +| 跳空风险 | 开盘执行额外加一层“开盘冲击滑点” | +| 税费/监管费 | 写成市场适配模块,按卖出/双边规则配置 | +| 借券费/融资利息 | 若做空或杠杆,必须单独建模 | +| 部分成交 | 低流动性标的禁止“理想一次性全成”假设 | + +若做美股杠杆,初始保证金要服从 Reg T 的一般 50% 框架,且 2026 年起日内保证金要求会在盘中监控账户风险;若做 A 股程序化交易,则除了融资融券业务本身,还要额外考虑交易所程序化报告和交易行为边界。也就是说,**杠杆不能只是一个乘数配置**,它必须伴随融资利率、日内/隔夜买入力、强平检查、API 回报风控和合规告警。citeturn41search2turn41search4turn41search7turn25view1 + +## 回测与参数优化 + +### 数据要求与样本治理 + +你需要的不是“能画图的数据”,而是**能经得起实盘审计的数据**。Polygon/Massive 的股票接口提供可按日和自定义周期获取的 OHLC 与成交量数据,并且提供 splits/dividends 端点以支持历史价格调整;IBKR 则提醒,API 的历史数据必须满足实时 Level 1 订阅要求,而且历史数据会过滤某些脱离 NBBO 的成交类型,因此历史成交量与实时/盘口视角可能不一致。QuantConnect 的文档也明确提醒,带有幸存者偏差、历史不足或清洗不充分的数据会导致劣化交易表现。citeturn21view3turn21view2turn30search3turn21view1turn30search4turn30search15 + +| 数据需求 | 为什么必须有 | +|---|---| +| 原始 OHLCV + 复权价 | 原始价用于执行,复权价用于信号与统计 | +| 拆股/分红/送配事件 | 不处理会扭曲收益、ATR、通道突破、止损距离 | +| 退市/停牌/换代码历史 | 避免幸存者偏差 | +| 交易日历/时区 | 决定日线切片口径与次日执行窗口 | +| 指数/基准数据 | 计算 beta、相对强弱、市场过滤 | +| 成交量与流动性字段 | 防止小票“纸面收益、实盘不成交” | +| 做空与融资可用性 | 若支持空头,这项是硬约束 | +| 点时成分信息 | 若做指数成分轮动,必须 point-in-time | + +如果你做中文市场研究,Tushare Pro、RQData、JoinQuant 都是常见工程入口。Tushare 官方文档显示其 `daily` 日线数据在交易日每日 15:00–17:00 之间更新;RQData 官方文档强调它提供整齐的历史数据 API;JoinQuant 的 API 文档则说明当选择天频率时,算法会在每根日线 bar 运行一次。这些平台适合作为研究/原型,但真正上实盘时,仍应以**你实际下单经纪商的行情口径**做最终一致性验证。citeturn22search3turn22search2turn22search11turn22search4turn23search7 + +### 回测流程与过拟合检测 + +推荐你把研究流程固定成下面这个管道,而不是每次“手工试参数”。 + +```mermaid +flowchart LR + A[数据清洗与企业行为调整] --> B[构建训练集] + B --> C[参数网格/贝叶斯搜索] + C --> D[样本内筛选] + D --> E[样本外测试] + E --> F[滚动回测] + F --> G[Walk-forward] + G --> H[PBO / DSR / Reality Check] + H --> I{通过?} + I -->|是| J[模拟盘] + I -->|否| K[丢弃或重构] +``` + +建议流程如下: + +| 阶段 | 建议做法 | +|---|---| +| 初筛 | 用 1–2 个核心参数族,先找有没有正期望的“区域” | +| 样本内/样本外 | 不低于 60/40;更稳妥可用滚动 3 年训练 + 1 年测试 | +| 滚动回测 | 每隔 1–3 个月重训一次,观察参数漂移 | +| Walk-forward | 每个窗口都只把过去数据给模型,不能偷看未来 | +| 过拟合检测 | 计算 PBO、DSR;必要时做 White’s Reality Check | +| 成本压力测试 | 把滑点、佣金、跳空冲击翻倍/三倍 | +| 稳健性测试 | 随机打乱部分交易顺序、随机剔除部分样本、蒙特卡洛重排 | + +Bailey 与 López de Prado 的 PBO 论文专门提出了用 CSCV 估计回测过拟合概率;DSR 则用于修正多重测试与非正态收益下的 Sharpe 夸大;Hsu、Hsu 与 Kuan 则用 White’s Reality Check 重新检查技术分析规则在数据窥探校正后的有效性。这三类方法应该出现在你的研究流水线上,而不是只出现在论文笔记里。citeturn15search0turn15search1turn15search18 + +一个可以直接写入研究引擎的 Walk-forward 伪代码如下: + +```pseudo +function walk_forward(data, train_len, test_len, param_grid): + results = [] + start = 0 + while start + train_len + test_len <= len(data): + train = data[start : start + train_len] + test = data[start + train_len : start + train_len + test_len] + + best_params = select_params(train, param_grid, objective="net_profit_after_cost_and_dd_penalty") + test_perf = backtest(test, best_params) + + results.append({ + train_start: train.start_date, + train_end: train.end_date, + test_start: test.start_date, + test_end: test.end_date, + params: best_params, + perf: test_perf + }) + start += test_len + return aggregate(results) +``` + +### 开源框架与常用工具 + +不同框架的优势非常不一样。VectorBT 的官方文档强调它完全基于 pandas/NumPy、由 Numba/Rust 加速,适合“在几秒内测试成千上万组策略”;LEAN/QuantConnect 明确定位为研究、回测与实盘一体化的开源引擎;Backtrader 的官方文档强调易用性和策略对象组织;vn.py 提供 CTA 回测、价差交易等模块,适合中文生态;RQAlpha Plus 则明确支持回测、模拟和实盘运行。citeturn20view2turn20view3turn20view0turn19view15turn23search1turn23search5turn23search12 + +| 框架 | 最适合的用途 | 不足 | +|---|---|---| +| VectorBT | 指标研究、参数穷举、超快回测、策略热力图 | 事件驱动交易细节要自己补很多 | +| Backtrader | 结构清晰、上手快、单策略到组合回测 | 大规模参数搜索不如向量化工具快 | +| LEAN | 研究、回测、优化、实盘一体化;多数据和券商连接 | 学习曲线略陡 | +| vn.py | 中文交易网关生态、CTA/价差/多模块 | 股票生态和券商接入要看具体环境 | +| RQAlpha Plus | 中文量化平台流,回测到模拟/实盘链路顺 | 与平台生态绑定较深 | +| Zipline | 经典教材型回测引擎,有滑点和订单延迟建模 | 当前生态相对弱一些 | + +对你这个项目,我建议的组合是:**VectorBT 做参数扫描 + Backtrader 或 LEAN 做事件回测 + 独立风控层 + 独立订单路由器**。如果你确定主战场在中文市场,可以考虑 **RQData/RQAlpha Plus 或 vn.py** 作为主栈候选。 + +## 实盘部署与代码清单 + +### 数据源、下单接口与生产架构 + +在美股公开 API 生态里,Alpaca 与 IBKR 是最实用的两类路线。Alpaca 的 Trading API 文档说明可监控、下单、撤单,并提供唯一订单标识;其 Market Data API 提供实时与历史数据,实时股票流通过 WebSocket 暴露不同 feed,例如 SIP、IEX、delayed SIP 等。IBKR 的 TWS API 文档覆盖了实时与历史行情请求、下单与监控,但其 Market Data Subscriptions 页面明确要求 API 市场数据通常需要 Level 1 订阅、IBKR Pro 账户、最低资金要求与 Market Data API Acknowledgement。对研究数据而言,Massive/Polygon 的 Aggregates 与 Splits/Dividends 端点很适合做历史回测;对中文研究数据,Tushare、RQData、JoinQuant 适合做研究原型。citeturn19view11turn19view12turn19view13turn21view4turn19view14turn21view0turn21view1turn21view2turn21view3turn22search3turn22search2turn22search4 + +```mermaid +flowchart LR + A[市场数据层] --> B[数据清洗与企业行为调整] + B --> C[特征引擎] + C --> D[信号引擎] + D --> E[组合与风控引擎] + E --> F[订单意图] + F --> G[Broker Adapter] + G --> H[成交/持仓/账户回报] + H --> I[对账与PnL] + I --> J[监控告警] + J --> K[日志/审计/版本回滚] +``` + +如果你面向 A 股,系统必须额外包含“**程序化交易报告与券商接口适配**”层。深交所规则明确,首次进行程序化交易前应先报告,重大变更也須报告;报告内容还包括资金规模、杠杆来源、最高申报速率、单日最高申报笔数、交易软件名称与开发主体等。换句话说,你的软件本身就可能成为**被监管对象的一部分**,因此版本管理、软件标识、责任人信息和日志留痕都不能是“以后再说”的事情。citeturn25view1 + +### 需要在代码中直接写入的模块清单 + +下面这张表,就是建议你直接建立的代码目录与函数接口。 + +| 模块 | 函数接口示例 | 输入 | 输出 | 关键说明 | +|---|---|---|---|---| +| 数据拉取 | `load_bars(symbols, start, end, timeframe, adjustment)` | 标的、起止时间、周期、复权模式 | `BarFrame[]` | 必须支持原始价与复权价双口径 | +| 企业行为 | `apply_corporate_actions(bars, splits, dividends)` | Bars、拆股、分红 | 调整后 Bars | 信号与执行口径分离 | +| 交易日历 | `get_calendar(market)` | 市场代码 | 交易日序列/会话 | A 股与美股日历不能共用 | +| 特征引擎 | `compute_features(bars, cfg)` | Bars、参数 | `FeatureFrame` | 输出 K 线特征 + 指标 | +| 状态识别 | `classify_regime(features, market_state, cfg)` | 特征、指数/波动 | `RegimeState` | 决定启用哪类策略 | +| 信号引擎 | `generate_signals(features, regime, positions, cfg)` | 特征、状态、持仓 | `Signal[]` | 只负责“想法”,不决定股数 | +| 仓位引擎 | `size_positions(signals, account, risk_cfg)` | 信号、账户、风控 | `OrderIntent[]` | 根据止损距离反推规模 | +| 风控闸门 | `risk_gate(order_intents, account, positions, limits)` | 订单意图、账户、仓位 | 过滤后订单 | 可一票否决任何信号 | +| 订单路由 | `route_orders(order_intents, broker_cfg)` | 订单意图、券商配置 | `BrokerOrder[]` | 适配 Alpaca/IBKR/券商 API | +| 成交模拟 | `simulate_fills(order, bars, cost_cfg)` | 订单、行情、成本 | `Fill[]` | 回测必须独立实现,不可偷懒 | +| 对账模块 | `reconcile(local_positions, broker_positions, fills)` | 本地仓位、券商仓位 | `ReconReport` | 实盘每天必须做 | +| 监控模块 | `monitor(metrics, thresholds)` | PnL、延迟、API 状态 | `Alert[]` | 钉钉/邮件/短信/Telegram | +| 审计日志 | `write_audit_log(event)` | 事件对象 | 日志记录 | 满足回放与合规需要 | +| 回滚模块 | `rollback(strategy_version)` | 策略版本号 | 成功/失败 | 实盘事故的最后保险 | + +建议统一的数据对象定义如下: + +```pseudo +type Bar = { + symbol: string, + ts: datetime, + open: float, + high: float, + low: float, + close: float, + volume: float, + adj_close: float?, + trade_date: string, + market: string +} + +type Signal = { + symbol: string, + side: "BUY" | "SELL" | "SHORT" | "COVER", + reason: string, + score: float, + planned_entry: float, + initial_stop: float, + planned_exit: float?, + strategy_id: string +} + +type OrderIntent = { + symbol: string, + side: string, + qty: int, + order_type: "MKT" | "LMT" | "VWAP" | "MOC", + tif: string, + limit_price: float?, + stop_price: float?, + client_order_id: string +} +``` + +### 可直接复用的主流程伪代码 + +```pseudo +function daily_main(trade_date): + bars = load_bars(universe, lookback_start(trade_date), trade_date, "1d", adjustment="both") + features = compute_features(bars, indicator_cfg) + regime = classify_regime(features, market_state=features.index, cfg=regime_cfg) + + signals = generate_signals(features, regime, positions, strategy_cfg) + order_intents = size_positions(signals, account, risk_cfg) + approved_orders = risk_gate(order_intents, account, positions, limits) + + save_trade_plan(trade_date + 1, approved_orders) + write_audit_log({ + date: trade_date, + signals: len(signals), + approved: len(approved_orders), + account_equity: account.equity + }) +``` + +如果你做“日线生成信号、次日执行”,则次日开盘前再跑一次执行引擎: + +```pseudo +function next_day_execute(trade_date): + plans = load_trade_plan(trade_date) + if data_is_stale() or api_is_degraded(): + enter_protective_mode() + return + + for p in plans: + live_order = create_broker_order(p, broker_cfg) + submit_order(live_order) +``` + +### 示例参数表 + +这些不是最终参数,而是**首轮上线前的起始配置**。 + +| 参数键 | 建议初值 | 说明 | +|---|---|---| +| `ema_fast` | `20` | 趋势识别快线 | +| `ema_slow` | `50` | 趋势识别慢线 | +| `ema_filter` | `200` | 长趋势过滤 | +| `adx_len` | `14` | 趋势强度 | +| `adx_trend_th` | `20` | 趋势阈值 | +| `rsi_short_len` | `2` | 短反转 | +| `rsi_short_buy` | `10` | 短反转超卖 | +| `bb_len` | `20` | 布林带长度 | +| `bb_k` | `2.0` | 布林带倍数 | +| `atr_len` | `14` | 波动率 | +| `atr_stop_mult` | `1.5–2.5` | 止损倍数 | +| `donchian_breakout` | `20` 或 `55` | 突破通道 | +| `risk_per_trade` | `0.005` | 单笔风险 0.5% | +| `max_position_pct` | `0.08` | 单票 8% | +| `soft_dd` | `0.07` | 软回撤 7% | +| `hard_dd` | `0.12` | 硬回撤 12% | +| `max_consecutive_losses` | `5` | 连亏熔断 | +| `min_rvol_for_breakout` | `1.5` | 突破量能过滤 | + +### 模拟盘到实盘迁移步骤 + +| 阶段 | 目标 | 放行条件 | +|---|---|---| +| 离线研究 | 找到有稳健性的参数区 | 样本外为正、成本敏感性不过度脆弱 | +| 事件回测 | 验证撮合、滑点、订单状态机 | 成本后仍有边际,回撤在可接受范围内 | +| 模拟盘 | 验证数据口径与订单回报一致性 | 本地仓位与券商仓位对账稳定,报警闭环完整 | +| Shadow Live | 实盘看信号但不真钱下单 | 两周以上“计划单”和真实行情一致 | +| 小资金实盘 | 验证真实成交、跳空和风控 | 1–2 个月无重大执行事故 | +| 扩容 | 从 10% 风险预算放到 100% | 逐级提升,不允许一步到位 | + +## 参考来源与合规风险提示 + +### 推荐优先参考来源 + +下表按“官方/原始论文/中文权威资料优先”的原则整理了你最值得持续跟踪的来源。由于不能直接贴裸链接,点击引用即可进入原文。 + +| 类别 | 推荐来源 | 用途 | +|---|---|---| +| 交易所规则 | 上交所交易规则、程序化交易实施细则;深交所程序化交易实施细则与盘后交易规则 citeturn43search5turn18search3turn25view1turn19view9 | 确认交易时段、回转交易限制、程序化报告义务 | +| 美股监管 | FINRA Rule 4210、FINRA Margin Topic、IRS Topic 409 citeturn41search4turn41search2turn41search7turn16search0 | 保证金、日内风险、税务口径 | +| 指标公式 | Sierra Chart Technical Studies Reference;TA-Lib Pattern Recognition citeturn40view0turn39view0turn19view2turn34view2turn33view1turn35view2turn36view0turn38view1turn32view0 | 指标与 K 线模式的公式与标准接口 | +| 学术原始文献 | Moskowitz/Ooi/Pedersen 时间序列动量;Hurst/AQR 趋势跟踪百年证据;Faber 趋势过滤;Jegadeesh/Titman 动量;Gatev 配对交易;Bailey PBO/DSR citeturn12search8turn12search5turn12search6turn14search0turn13search3turn15search0turn15search1 | 评估策略是否有长期研究基础 | +| 回测框架 | LEAN、VectorBT、Backtrader、vn.py、RQAlpha Plus、JoinQuant citeturn20view0turn20view2turn19view15turn23search1turn23search5turn23search12turn23search3 | 研究、回测、模拟盘、实盘框架选择 | +| 数据接口 | Alpaca、IBKR、Massive/Polygon、Tushare、RQData、JoinQuant citeturn19view12turn19view13turn19view11turn21view4turn19view14turn21view0turn21view2turn21view3turn22search3turn22search2turn22search4 | 历史与实时数据、下单与回报 | + +### 风险与合规提示 + +首先是**市场风险**。趋势、动量、反转、配对这些策略即便在长期研究里有效,也都会经历长时间失效、风格切换和深度回撤。你的软件不应追求“每天都赚 500 美元”,而应追求**长期期望值为正、回撤受控、容量可扩展**。这也是为什么本报告一直把目标拆成资金规模、风险预算和策略容量。citeturn12search8turn12search5turn13search3 + +其次是**模型风险**。回测过拟合、样本内挑选和多重测试偏差会让你高估策略质量。没有样本外、滚动、Walk-forward、PBO 和 DSR 的“漂亮回测”,在统计上往往不够可信。citeturn15search0turn15search1turn15search18 + +再次是**实现风险**。企业行为处理错误、幸存者偏差、历史/实时数据口径不一致、订单状态机错误、API 鉴权失效、行情延迟、对账失败,都会让实盘结果和回测完全脱钩。IBKR 官方就明确提醒 API 历史数据有订阅要求且历史成交量与实时数据可能不同;QuantConnect 也明确提醒,数据若存在幸存者偏差或清洗不足,会造成糟糕交易表现。citeturn21view0turn21view1turn30search4turn30search15 + +最后是**法律、交易所规则与税务风险**。若你做 A 股并自动生成/发送指令,交易所规则已把这类行为纳入程序化交易管理,个人投资者也在范围内,首次交易前和重大变更时应履行报告义务;若你做美股并使用保证金,Reg T 与 FINRA 的日内保证金规则会直接影响你的可用买入力和风控;若有盈利,税务处理必须按所在地税法申报,美国可先从 IRS Topic 409 着手,境内则需结合券商与税务机关最新口径,特殊情形如限售股等另有规则。以上内容属于工程与合规研究,不构成法律、税务或个性化投资建议。citeturn25view1turn41search2turn41search4turn16search0turn16search10 \ No newline at end of file diff --git a/external/Quant.ai/fetch_stock.py b/external/Quant.ai/fetch_stock.py new file mode 100644 index 0000000000000000000000000000000000000000..961a8b3ebbb8ed223b62aa1349d2e8ae7b83f590 --- /dev/null +++ b/external/Quant.ai/fetch_stock.py @@ -0,0 +1,106 @@ +import yfinance as yf +import pandas as pd +import numpy as np + +def calculate_atr(df, period=14): + """ + 计算 ATR (Average True Range) 真实波幅,用来衡量波动率。 + ATR 越高,说明波动越大,适合日内交易。 + """ + high_low = df['High'] - df['Low'] + high_close = np.abs(df['High'] - df['Close'].shift()) + low_close = np.abs(df['Low'] - df['Close'].shift()) + + ranges = pd.concat([high_low, high_close, low_close], axis=1) + true_range = np.max(ranges, axis=1) + atr = true_range.rolling(window=period).mean() + return atr + +def scan_stocks(tickers): + """ + 模拟交易员开盘前的扫描逻辑: + 1. 相对成交量 (RVol) - 今天交易量是否是过去20天平均成交量的 1.5 倍以上? + 2. 波动率 (ATR % of Price) - 股票的波动性是否够大? + 3. 跳空幅度 (Gap %) - 开盘价相比昨天收盘价跳空了多少? + """ + print("=" * 60) + print(" QUANT.AI - PROFESSIONAL DAY TRADER SCANNER (盘前选股器)") + print("=" * 60) + print("正在从 Yahoo Finance 获取数据,请稍候...\n") + + watchlist = [] + + for ticker in tickers: + try: + # 获取最近 30 天的日线数据 + stock = yf.Ticker(ticker) + df = stock.history(period="30d") + + if df.empty or len(df) < 20: + continue + + # 最新一天的行情数据 + latest_day = df.iloc[-1] + prev_day = df.iloc[-2] + + # 1. 计算相对成交量 (Relative Volume - RVol) + avg_volume_20d = df['Volume'].iloc[-21:-1].mean() + latest_volume = latest_day['Volume'] + rvol = latest_volume / avg_volume_20d if avg_volume_20d > 0 else 0 + + # 2. 计算 ATR (以百分比形式表示,方便横向对比不同股价的股票) + df['ATR'] = calculate_atr(df, period=14) + latest_atr = df['ATR'].iloc[-1] + atr_pct = (latest_atr / latest_day['Close']) * 100 if latest_day['Close'] > 0 else 0 + + # 3. 计算跳空幅度 (Gap %) + gap_pct = ((latest_day['Open'] - prev_day['Close']) / prev_day['Close']) * 100 + + watchlist.append({ + 'Ticker': ticker, + 'Price': round(latest_day['Close'], 2), + 'RVol': round(rvol, 2), + 'ATR_%': round(atr_pct, 2), + 'Gap_%': round(gap_pct, 2), + 'Volume_Millions': round(latest_volume / 1_000_000, 2) + }) + + except Exception as e: + print(f"获取 {ticker} 数据失败: {str(e)}") + + # 转为 DataFrame 方便处理和展示 + results_df = pd.DataFrame(watchlist) + + # 过滤与排序: + # 1. 过滤:波动率 ATR_% 必须大于 1.5%(波动太小的股我们不做日内) + # 2. 排序:按 RVol (相对成交量) 降序排列,成交量放大的股票才是热点 + results_df = results_df.sort_values(by='RVol', ascending=False) + + print("【候选股票扫描结果列表】:") + print(results_df.to_string(index=False)) + print("\n" + "-" * 60) + + # 选出今天最合适做 Day Trading 的股票 + # 推荐标准:RVol > 1.2 且 ATR_% > 1.5% + recommended = results_df[(results_df['RVol'] > 1.2) & (results_df['ATR_%'] > 1.5)] + + print("【AI 盘前交易推荐】:") + if not recommended.empty: + for idx, row in recommended.iterrows(): + print(f"★ 推荐交易 {row['Ticker']}:") + print(f" - 理由:今日成交量放大到平时的 {row['RVol']} 倍 (RVol={row['RVol']}),波动率达 {row['ATR_%']}%。") + print(f" - 操作策略:根据日内K线走势进行突破或回调买入/做空,单笔最大止损控制在账户的 1%。") + else: + # 如果没有符合高波动和高成交量的股票,宁可观望 + top_stock = results_df.iloc[0] if not results_df.empty else None + print("⚠ 警报:今天市场整体成交量萎缩或波动较低。") + print(" - 建议:【观望/不交易】。频繁交易将产生巨大的佣金损耗!") + if top_stock is not None: + print(f" - 若强行操作,可关注相对最活跃的 {top_stock['Ticker']} (RVol={top_stock['RVol']})。") + + print("=" * 60) + +if __name__ == "__main__": + # 我们扫描 TSLA(特斯拉), NVDA(英伟达), AAPL(苹果), MSFT(微软), AMD(超威半导体) 等大盘股 + popular_stocks = ["TSLA", "NVDA", "AAPL", "MSFT", "AMD"] + scan_stocks(popular_stocks) diff --git a/external/Quant.ai/frontend/.gitignore b/external/Quant.ai/frontend/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a547bf36d8d11a4f89c59c144f24795749086dd1 --- /dev/null +++ b/external/Quant.ai/frontend/.gitignore @@ -0,0 +1,24 @@ +# Logs +logs +*.log +npm-debug.log* +yarn-debug.log* +yarn-error.log* +pnpm-debug.log* +lerna-debug.log* + +node_modules +dist +dist-ssr +*.local + +# Editor directories and files +.vscode/* +!.vscode/extensions.json +.idea +.DS_Store +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? diff --git a/external/Quant.ai/frontend/README.md b/external/Quant.ai/frontend/README.md new file mode 100644 index 0000000000000000000000000000000000000000..7dbf7ebf3b2a3d84ad526bc47810d1d211331b8b --- /dev/null +++ b/external/Quant.ai/frontend/README.md @@ -0,0 +1,73 @@ +# React + TypeScript + Vite + +This template provides a minimal setup to get React working in Vite with HMR and some ESLint rules. + +Currently, two official plugins are available: + +- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs) +- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/) + +## React Compiler + +The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation). + +## Expanding the ESLint configuration + +If you are developing a production application, we recommend updating the configuration to enable type-aware lint rules: + +```js +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + + // Remove tseslint.configs.recommended and replace with this + tseslint.configs.recommendedTypeChecked, + // Alternatively, use this for stricter rules + tseslint.configs.strictTypeChecked, + // Optionally, add this for stylistic rules + tseslint.configs.stylisticTypeChecked, + + // Other configs... + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` + +You can also install [eslint-plugin-react-x](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-x) and [eslint-plugin-react-dom](https://github.com/Rel1cx/eslint-react/tree/main/packages/plugins/eslint-plugin-react-dom) for React-specific lint rules: + +```js +// eslint.config.js +import reactX from 'eslint-plugin-react-x' +import reactDom from 'eslint-plugin-react-dom' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + // Other configs... + // Enable lint rules for React + reactX.configs['recommended-typescript'], + // Enable lint rules for React DOM + reactDom.configs.recommended, + ], + languageOptions: { + parserOptions: { + project: ['./tsconfig.node.json', './tsconfig.app.json'], + tsconfigRootDir: import.meta.dirname, + }, + // other options... + }, + }, +]) +``` diff --git a/external/Quant.ai/frontend/eslint.config.js b/external/Quant.ai/frontend/eslint.config.js new file mode 100644 index 0000000000000000000000000000000000000000..ef614d25c11dd1e89a8df0b2eaf934170b44daa8 --- /dev/null +++ b/external/Quant.ai/frontend/eslint.config.js @@ -0,0 +1,22 @@ +import js from '@eslint/js' +import globals from 'globals' +import reactHooks from 'eslint-plugin-react-hooks' +import reactRefresh from 'eslint-plugin-react-refresh' +import tseslint from 'typescript-eslint' +import { defineConfig, globalIgnores } from 'eslint/config' + +export default defineConfig([ + globalIgnores(['dist']), + { + files: ['**/*.{ts,tsx}'], + extends: [ + js.configs.recommended, + tseslint.configs.recommended, + reactHooks.configs.flat.recommended, + reactRefresh.configs.vite, + ], + languageOptions: { + globals: globals.browser, + }, + }, +]) diff --git a/external/Quant.ai/frontend/index.html b/external/Quant.ai/frontend/index.html new file mode 100644 index 0000000000000000000000000000000000000000..0fca6f0434183b2c6f46d5336c59f6954c56b470 --- /dev/null +++ b/external/Quant.ai/frontend/index.html @@ -0,0 +1,13 @@ + + + + + + + frontend + + +
+ + + diff --git a/external/Quant.ai/frontend/package-lock.json b/external/Quant.ai/frontend/package-lock.json new file mode 100644 index 0000000000000000000000000000000000000000..1aa74e02defbfae04d183928a75042215080c1be --- /dev/null +++ b/external/Quant.ai/frontend/package-lock.json @@ -0,0 +1,2757 @@ +{ + "name": "frontend", + "version": "0.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "frontend", + "version": "0.0.0", + "dependencies": { + "lightweight-charts": "^4.1.3", + "react": "^19.2.6", + "react-dom": "^19.2.6" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@types/node": "^24.12.3", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "eslint": "^10.3.0", + "eslint-plugin-react-hooks": "^7.1.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.6.0", + "typescript": "~6.0.2", + "typescript-eslint": "^8.59.2", + "vite": "^8.0.12" + } + }, + "node_modules/@babel/code-frame": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.29.7.tgz", + "integrity": "sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-validator-identifier": "^7.29.7", + "js-tokens": "^4.0.0", + "picocolors": "^1.1.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/compat-data": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/compat-data/-/compat-data-7.29.7.tgz", + "integrity": "sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/core": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/core/-/core-7.29.7.tgz", + "integrity": "sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-compilation-targets": "^7.29.7", + "@babel/helper-module-transforms": "^7.29.7", + "@babel/helpers": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/remapping": "^2.3.5", + "convert-source-map": "^2.0.0", + "debug": "^4.1.0", + "gensync": "^1.0.0-beta.2", + "json5": "^2.2.3", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/babel" + } + }, + "node_modules/@babel/generator": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/generator/-/generator-7.29.7.tgz", + "integrity": "sha512-DkXD5OJQaAQIdZ1bt3UZdEnHAn9Imd3IVBdX03UFe+ony9Ojw5pzr9YVKGDY1jt+Gcn/FnGkNf8r+Vj5NOJWtQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7", + "@jridgewell/gen-mapping": "^0.3.12", + "@jridgewell/trace-mapping": "^0.3.28", + "jsesc": "^3.0.2" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-compilation-targets": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz", + "integrity": "sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/compat-data": "^7.29.7", + "@babel/helper-validator-option": "^7.29.7", + "browserslist": "^4.24.0", + "lru-cache": "^5.1.1", + "semver": "^6.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-globals": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-globals/-/helper-globals-7.29.7.tgz", + "integrity": "sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-imports": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz", + "integrity": "sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/traverse": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-module-transforms": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz", + "integrity": "sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-module-imports": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7", + "@babel/traverse": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + }, + "peerDependencies": { + "@babel/core": "^7.0.0" + } + }, + "node_modules/@babel/helper-string-parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz", + "integrity": "sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-identifier": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz", + "integrity": "sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helper-validator-option": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz", + "integrity": "sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/helpers": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/helpers/-/helpers-7.29.7.tgz", + "integrity": "sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/parser": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.29.7.tgz", + "integrity": "sha512-hnORnjP/1P/zFEndoeX+n+t1RwWRJiJpM/jO7FW32Kn9r5+sJB2JWOdYo4L6k78j15eCwY3Gm/7364B1EMwtNg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/types": "^7.29.7" + }, + "bin": { + "parser": "bin/babel-parser.js" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@babel/template": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/template/-/template-7.29.7.tgz", + "integrity": "sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/types": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/traverse": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/traverse/-/traverse-7.29.7.tgz", + "integrity": "sha512-EhlfNQtZ+NK22w5BM61ciuiq1m58ed33Wr1Xan//ZRTy6hgjnwyCffRYwzsGXdASJSUJ1guZILsErh1eQcl+zw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/code-frame": "^7.29.7", + "@babel/generator": "^7.29.7", + "@babel/helper-globals": "^7.29.7", + "@babel/parser": "^7.29.7", + "@babel/template": "^7.29.7", + "@babel/types": "^7.29.7", + "debug": "^4.3.1" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@babel/types": { + "version": "7.29.7", + "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.29.7.tgz", + "integrity": "sha512-4zBIxpPzowiZpusoFkyGVwakdRJUyuH5PxQ/PrqghfdFWWasvnCdPfQXHrenDai+gyLARulZjZowCOj6fjT4pA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/helper-string-parser": "^7.29.7", + "@babel/helper-validator-identifier": "^7.29.7" + }, + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/@emnapi/core": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/core/-/core-1.10.0.tgz", + "integrity": "sha512-yq6OkJ4p82CAfPl0u9mQebQHKPJkY7WrIuk205cTYnYe+k2Z8YBh11FrbRG/H6ihirqcacOgl2BIO8oyMQLeXw==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.1", + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/runtime": { + "version": "1.10.0", + "resolved": "https://registry.npmjs.org/@emnapi/runtime/-/runtime-1.10.0.tgz", + "integrity": "sha512-ewvYlk86xUoGI0zQRNq/mC+16R1QeDlKQy21Ki3oSYXNgLb45GV1P6A0M+/s6nyCuNDqe5VpaY84BzXGwVbwFA==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@emnapi/wasi-threads": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@emnapi/wasi-threads/-/wasi-threads-1.2.1.tgz", + "integrity": "sha512-uTII7OYF+/Mes/MrcIOYp5yOtSMLBWSIoLPpcgwipoiKbli6k322tcoFsxoIIxPDqW01SQGAgko4EzZi2BNv2w==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@eslint-community/eslint-utils": { + "version": "4.9.1", + "resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.9.1.tgz", + "integrity": "sha512-phrYmNiYppR7znFEdqgfWHXR6NCkZEK7hwWDHZUjit/2/U0r6XvkDl0SYnoM51Hq7FhCGdLDT6zxCCOY1hexsQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "eslint-visitor-keys": "^3.4.3" + }, + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + }, + "peerDependencies": { + "eslint": "^6.0.0 || ^7.0.0 || >=8.0.0" + } + }, + "node_modules/@eslint-community/eslint-utils/node_modules/eslint-visitor-keys": { + "version": "3.4.3", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz", + "integrity": "sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^12.22.0 || ^14.17.0 || >=16.0.0" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/@eslint-community/regexpp": { + "version": "4.12.2", + "resolved": "https://registry.npmjs.org/@eslint-community/regexpp/-/regexpp-4.12.2.tgz", + "integrity": "sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^12.0.0 || ^14.0.0 || >=16.0.0" + } + }, + "node_modules/@eslint/config-array": { + "version": "0.23.5", + "resolved": "https://registry.npmjs.org/@eslint/config-array/-/config-array-0.23.5.tgz", + "integrity": "sha512-Y3kKLvC1dvTOT+oGlqNQ1XLqK6D1HU2YXPc52NmAlJZbMMWDzGYXMiPRJ8TYD39muD/OTjlZmNJ4ib7dvSrMBA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/object-schema": "^3.0.5", + "debug": "^4.3.1", + "minimatch": "^10.2.4" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/config-helpers": { + "version": "0.6.0", + "resolved": "https://registry.npmjs.org/@eslint/config-helpers/-/config-helpers-0.6.0.tgz", + "integrity": "sha512-ii6Bw9jJ2zi2cWA2Z+9/QZ/+3DX6kwaV5Q986D/CdP3Lap3w/pgQZ373FV7byY/i7L4IRH/G43I5dz1ClsCbpA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/core": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/@eslint/core/-/core-1.2.1.tgz", + "integrity": "sha512-MwcE1P+AZ4C6DWlpin/OmOA54mmIZ/+xZuJiQd4SyB29oAJjN30UW9wkKNptW2ctp4cEsvhlLY/CsQ1uoHDloQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@types/json-schema": "^7.0.15" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/js": { + "version": "10.0.1", + "resolved": "https://registry.npmjs.org/@eslint/js/-/js-10.0.1.tgz", + "integrity": "sha512-zeR9k5pd4gxjZ0abRoIaxdc7I3nDktoXZk2qOv9gCNWx3mVwEn32VRhyLaRsDiJjTs0xq/T8mfPtyuXu7GWBcA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "eslint": "^10.0.0" + }, + "peerDependenciesMeta": { + "eslint": { + "optional": true + } + } + }, + "node_modules/@eslint/object-schema": { + "version": "3.0.5", + "resolved": "https://registry.npmjs.org/@eslint/object-schema/-/object-schema-3.0.5.tgz", + "integrity": "sha512-vqTaUEgxzm+YDSdElad6PiRoX4t8VGDjCtt05zn4nU810UIx/uNEV7/lZJ6KwFThKZOzOxzXy48da+No7HZaMw==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@eslint/plugin-kit": { + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/@eslint/plugin-kit/-/plugin-kit-0.7.2.tgz", + "integrity": "sha512-+CNAzxglkrpNf/kKywqQfk74QjtceuOE7Qm+AF8miRvPF/wmmK5+OJOgVh3AVTT3RP2mH3+FOaxlE5v72owk0A==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@eslint/core": "^1.2.1", + "levn": "^0.4.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + } + }, + "node_modules/@humanfs/core": { + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/@humanfs/core/-/core-0.19.2.tgz", + "integrity": "sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/types": "^0.15.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/node": { + "version": "0.16.8", + "resolved": "https://registry.npmjs.org/@humanfs/node/-/node-0.16.8.tgz", + "integrity": "sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ==", + "dev": true, + "license": "Apache-2.0", + "dependencies": { + "@humanfs/core": "^0.19.2", + "@humanfs/types": "^0.15.0", + "@humanwhocodes/retry": "^0.4.0" + }, + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanfs/types": { + "version": "0.15.0", + "resolved": "https://registry.npmjs.org/@humanfs/types/-/types-0.15.0.tgz", + "integrity": "sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18.0" + } + }, + "node_modules/@humanwhocodes/module-importer": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz", + "integrity": "sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=12.22" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@humanwhocodes/retry": { + "version": "0.4.3", + "resolved": "https://registry.npmjs.org/@humanwhocodes/retry/-/retry-0.4.3.tgz", + "integrity": "sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=18.18" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/nzakas" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz", + "integrity": "sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.5.5", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz", + "integrity": "sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og==", + "dev": true, + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@napi-rs/wasm-runtime": { + "version": "1.1.5", + "resolved": "https://registry.npmjs.org/@napi-rs/wasm-runtime/-/wasm-runtime-1.1.5.tgz", + "integrity": "sha512-AWPoBRJ9tsnVhor4sjO7rkni+7p+2IAEFj6cx06UgP10jkQHqay/36uRV/bFkgrh18D9vb4cr8Q0Pthskgzy+Q==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1", + "@emnapi/runtime": "^1.7.1" + } + }, + "node_modules/@oxc-project/types": { + "version": "0.133.0", + "resolved": "https://registry.npmjs.org/@oxc-project/types/-/types-0.133.0.tgz", + "integrity": "sha512-KzkdCd6Uxqnf6l3HOw1xfatAlUURA0g14cvBYFyJ5SaNOQbOUvBr9PKArcPcrNIeRsBdgcUzOGrhKveVpvOIGA==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/Boshen" + } + }, + "node_modules/@rolldown/binding-android-arm64": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-android-arm64/-/binding-android-arm64-1.0.3.tgz", + "integrity": "sha512-454rs7jHngixp/NMxd5srYD57OnzSlZ/eFTETjORQHLwJG1lRtmNOJcBerZlfu4GjKqeq8aCCIQrMdHyhI51Hw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-arm64": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-arm64/-/binding-darwin-arm64-1.0.3.tgz", + "integrity": "sha512-PcAhP+ynjURNyy8SKGl5DQP94aGuB/7JrXJb/t7P+hanXvQVMWzUvRRhBAcg/lNRadBhoUPqSoP4xw5tR/KBEA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-darwin-x64": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-darwin-x64/-/binding-darwin-x64-1.0.3.tgz", + "integrity": "sha512-9YpfeUvSE2RS7wysJ81uOZkXJz7f7Q55H2Gvp3VEw/EsahqDtrphrZ0EwDLK5vvKOzaCrBsjF8JmnMLcUt78Gg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-freebsd-x64": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-freebsd-x64/-/binding-freebsd-x64-1.0.3.tgz", + "integrity": "sha512-yB1IlAsSNHncV6SCTL27/MVGR5htvQsoGxIv5KMGXALp+Ll1wYsn+x98M9MW7qa+NdSbvrrY7ANI4wLJ0n1e6g==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm-gnueabihf": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm-gnueabihf/-/binding-linux-arm-gnueabihf-1.0.3.tgz", + "integrity": "sha512-Yi30IVAAfLUCy2MseFjbB1jAMDl1VMCAas5StnYp8da9+CKvMd2H2cbEjWcw5NPaPqzvYkVIaF1nNUG+b7u/sw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-gnu": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-gnu/-/binding-linux-arm64-gnu-1.0.3.tgz", + "integrity": "sha512-jsO7R8To+AdlYgUmN5sHSCZbfhtMBkO0WUx8iORQnPcMMdgr7qM2DQmMwgabs3GhNztdmoKkMKQFHD6DTMCIQw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-arm64-musl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-arm64-musl/-/binding-linux-arm64-musl-1.0.3.tgz", + "integrity": "sha512-VWkUHwWriDciit80wleYwKILoR/KMvxh/IdwS/paX+ZgpuRpCrKLUdadJbc0NpBEiyhpYawsJ73j9aCvOH+f7Q==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-ppc64-gnu": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-ppc64-gnu/-/binding-linux-ppc64-gnu-1.0.3.tgz", + "integrity": "sha512-5f1laC0SlIR0yDbFCd8acUhvJIag6N3zC5P7oUPN6wX0aOma+uKJ0wBDH5aq7I1PVI2ttTlhJwzwRIBnLiSGEg==", + "cpu": [ + "ppc64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-s390x-gnu": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-s390x-gnu/-/binding-linux-s390x-gnu-1.0.3.tgz", + "integrity": "sha512-Iq4ko0r4XsgbrF/LunNgHtAGLRRVE2kXonAXQ/MV0mC6jQpMOhW1SvtZja2EhC/kd05++bP78dsqBeIQyYJ6Yg==", + "cpu": [ + "s390x" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-gnu": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-gnu/-/binding-linux-x64-gnu-1.0.3.tgz", + "integrity": "sha512-B8m6tD5+/N5FeNQFbKlLA/2yVq9ycQP1SeedyEYYKWBNR3ZQbkvIUcNnDNM03lO1l5F2roiiFJGgvoLLyZXtSg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-linux-x64-musl": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-linux-x64-musl/-/binding-linux-x64-musl-1.0.3.tgz", + "integrity": "sha512-pSdpdUJHkuCxun9LE7jvgUB9qsRgaiyNNCX7m/AvHTcq67AiT/Yhoxvw5zPfhrM8k/BfP8ce/hMOpthKDpEUow==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-openharmony-arm64": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-openharmony-arm64/-/binding-openharmony-arm64-1.0.3.tgz", + "integrity": "sha512-OXXS3RKJgX2uLwM+gYyuH5omcH8fL1LJs96pZGgtetVCahON57+d4SJHzTgZiOjxgGkSnpXpOsWuPDGAKAigEg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "openharmony" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-wasm32-wasi": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-wasm32-wasi/-/binding-wasm32-wasi-1.0.3.tgz", + "integrity": "sha512-JTtb8BWFynicNSoPrehsCzBtOKjZ6jhMiPFEmOiuXg1Fl8dn2KHQob+GuPSGR0dryQa1PQJbzjF3dqO/whhjLg==", + "cpu": [ + "wasm32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "1.10.0", + "@emnapi/runtime": "1.10.0", + "@napi-rs/wasm-runtime": "^1.1.4" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-arm64-msvc": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-arm64-msvc/-/binding-win32-arm64-msvc-1.0.3.tgz", + "integrity": "sha512-gEdFFEN70A/jxb2svrWsN3aDL7OUtmvlOy+6fa2jxG8K0wQ1ZbdeLGnidov6Yu5/733dI5ySfzFlQ/cb0bSz1g==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/binding-win32-x64-msvc": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@rolldown/binding-win32-x64-msvc/-/binding-win32-x64-msvc-1.0.3.tgz", + "integrity": "sha512-eXB7CHuaQdqmJcc3koCNtNPmT/bj2gc999kUFgBxG8Ac0NdgXc4rkCHhqrgrhN3zddvvvrgzj1e90SuSfmyIXA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": "^20.19.0 || >=22.12.0" + } + }, + "node_modules/@rolldown/pluginutils": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@rolldown/pluginutils/-/pluginutils-1.0.1.tgz", + "integrity": "sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@tybys/wasm-util": { + "version": "0.10.2", + "resolved": "https://registry.npmjs.org/@tybys/wasm-util/-/wasm-util-0.10.2.tgz", + "integrity": "sha512-RoBvJ2X0wuKlWFIjrwffGw1IqZHKQqzIchKaadZZfnNpsAYp2mM0h36JtPCjNDAHGgYez/15uMBpfGwchhiMgg==", + "dev": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@types/esrecurse": { + "version": "4.3.1", + "resolved": "https://registry.npmjs.org/@types/esrecurse/-/esrecurse-4.3.1.tgz", + "integrity": "sha512-xJBAbDifo5hpffDBuHl0Y8ywswbiAp/Wi7Y/GtAgSlZyIABppyurxVueOPE8LUQOxdlgi6Zqce7uoEpqNTeiUw==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/estree": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz", + "integrity": "sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/json-schema": { + "version": "7.0.15", + "resolved": "https://registry.npmjs.org/@types/json-schema/-/json-schema-7.0.15.tgz", + "integrity": "sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==", + "dev": true, + "license": "MIT" + }, + "node_modules/@types/node": { + "version": "24.13.2", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.2.tgz", + "integrity": "sha512-fRa09kZTgu8o71KFcDjUFuc7F+dEbZYZmkI0mg5YBTRs0yMKjYHsq/c0urDKeDb+D5qVgXOdFcuu+DZPKOITwA==", + "dev": true, + "license": "MIT", + "dependencies": { + "undici-types": "~7.18.0" + } + }, + "node_modules/@types/react": { + "version": "19.2.17", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.17.tgz", + "integrity": "sha512-MXfmqaVPEVgkBT/aY0aGCkRWWtByiYQXo3xdQ8r5RzuFrPiRn8Gar2tQdXSUQ2GKV3bkXckek89V8wQBY2Q/Aw==", + "dev": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, + "node_modules/@types/react-dom": { + "version": "19.2.3", + "resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-19.2.3.tgz", + "integrity": "sha512-jp2L/eY6fn+KgVVQAOqYItbF0VY/YApe5Mz2F0aykSO8gx31bYCZyvSeYxCHKvzHG5eZjc+zyaS5BrBWya2+kQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "@types/react": "^19.2.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.61.0.tgz", + "integrity": "sha512-bFNvl9ZczlVb+wR2Akszf3gHfKVj/8WanXaGJ3UstTA7brNKg0cNdk6X1Psu5V7MZ2oQtzZKOEzIUehaoxbDGw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/regexpp": "^4.12.2", + "@typescript-eslint/scope-manager": "8.61.0", + "@typescript-eslint/type-utils": "8.61.0", + "@typescript-eslint/utils": "8.61.0", + "@typescript-eslint/visitor-keys": "8.61.0", + "ignore": "^7.0.5", + "natural-compare": "^1.4.0", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "@typescript-eslint/parser": "^8.61.0", + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/eslint-plugin/node_modules/ignore": { + "version": "7.0.5", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-7.0.5.tgz", + "integrity": "sha512-Hs59xBNfUIunMFgWAbGX5cq6893IbWg4KnrjbYwX3tx0ztorVgTDA6B2sxf8ejHJ4wz8BqGUMYlnzNBer5NvGg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/@typescript-eslint/parser": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/parser/-/parser-8.61.0.tgz", + "integrity": "sha512-5B7PfA2e1NQGCnDHd/0lW7W3gvp3d59Ryw54FYO8Uswxo9f6ikw3AZV+Xj/TvpImmpsiYyUqAfhC6kJID1jF6w==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/scope-manager": "8.61.0", + "@typescript-eslint/types": "8.61.0", + "@typescript-eslint/typescript-estree": "8.61.0", + "@typescript-eslint/visitor-keys": "8.61.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/project-service": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/project-service/-/project-service-8.61.0.tgz", + "integrity": "sha512-DV42F7MLJO6Rax7SK1yg43tcnEfGUrurSpSxKuVX+a3RCTzBlH3fuxprrOJXKCJGAaw82xXocikJ0uQaqwXgGA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/tsconfig-utils": "^8.61.0", + "@typescript-eslint/types": "^8.61.0", + "debug": "^4.4.3" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/scope-manager": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/scope-manager/-/scope-manager-8.61.0.tgz", + "integrity": "sha512-IWdXFHFSb6mlC3HPc7QsLDm5zYEbUla6trDEHf32D3/dnuUyXd87plScSNXSbm0/RxMvObpI17sv/EDTGrGZkA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.61.0", + "@typescript-eslint/visitor-keys": "8.61.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/tsconfig-utils": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.61.0.tgz", + "integrity": "sha512-O5Amvdv9ztMpxpf+vmFULGG78IE6Qwdr3bCGvqwG4nwc9H2qXkOYJJnRbRHyMkQTjv1d03olqwwwzHLMqpFePQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/type-utils": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/type-utils/-/type-utils-8.61.0.tgz", + "integrity": "sha512-TuBiQYIkd97yBfInHCTKVYMbX4kvEmpOEuixIuzCU9p8BGT1SfyyO0d0IfDMbPIHcjn/hWnusUX5e8v5Xg+X8A==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.61.0", + "@typescript-eslint/typescript-estree": "8.61.0", + "@typescript-eslint/utils": "8.61.0", + "debug": "^4.4.3", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/types": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/types/-/types-8.61.0.tgz", + "integrity": "sha512-9QTQpZ5Iin4CdIodfbDQFSeiSJKidgYJYug1P9CC2xWgUTvlmixViqDZNciMjwLBZyJnG4tGmPl97rVAFb1AJg==", + "dev": true, + "license": "MIT", + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@typescript-eslint/typescript-estree": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/typescript-estree/-/typescript-estree-8.61.0.tgz", + "integrity": "sha512-42zatd5qSvvcV1JdDBCLxYRznvP4eIHpPoZXdkPFnAmanA4FuZ5dibSnCBggY8hQnqajPpoGjXFdZ7fIJKQnlA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/project-service": "8.61.0", + "@typescript-eslint/tsconfig-utils": "8.61.0", + "@typescript-eslint/types": "8.61.0", + "@typescript-eslint/visitor-keys": "8.61.0", + "debug": "^4.4.3", + "minimatch": "^10.2.2", + "semver": "^7.7.3", + "tinyglobby": "^0.2.15", + "ts-api-utils": "^2.5.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/typescript-estree/node_modules/semver": { + "version": "7.8.4", + "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.4.tgz", + "integrity": "sha512-rUCObTnP32Q08R2uuIrt7r9PlEonuTmtuXYcW6s5kjdlj3xbnwe+21yXptAUYcMAABLkYYTtnmzb3w3EDZfueA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/@typescript-eslint/utils": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/utils/-/utils-8.61.0.tgz", + "integrity": "sha512-3bzFt7ImFMW/jVYwJamDoe/dMOdFLSC6pom6rRjdh4SZJEYupyMzem8e7vKZLclLfpHjlwSAXOUxtKxGXUiLqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "@eslint-community/eslint-utils": "^4.9.1", + "@typescript-eslint/scope-manager": "8.61.0", + "@typescript-eslint/types": "8.61.0", + "@typescript-eslint/typescript-estree": "8.61.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/@typescript-eslint/visitor-keys": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/@typescript-eslint/visitor-keys/-/visitor-keys-8.61.0.tgz", + "integrity": "sha512-QVLZu3ZPQEE+HICQyAMZ2yLQhxf0meY/wx6Hx14YcTNj13JB3qHlX3lJ02L3fLGHgERRH71kvYDwiXIguT3AjQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/types": "8.61.0", + "eslint-visitor-keys": "^5.0.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + } + }, + "node_modules/@vitejs/plugin-react": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/@vitejs/plugin-react/-/plugin-react-6.0.2.tgz", + "integrity": "sha512-DlSMqo4WhThw4vB8Mpn0Woe9J+Jfq1geJ61AKW0QEgLzGMNwtIMdxbDUzLxcun8W7NbJO0e2Jg/Nxm3cCSVzzg==", + "dev": true, + "license": "MIT", + "dependencies": { + "@rolldown/pluginutils": "^1.0.0" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "peerDependencies": { + "@rolldown/plugin-babel": "^0.1.7 || ^0.2.0", + "babel-plugin-react-compiler": "^1.0.0", + "vite": "^8.0.0" + }, + "peerDependenciesMeta": { + "@rolldown/plugin-babel": { + "optional": true + }, + "babel-plugin-react-compiler": { + "optional": true + } + } + }, + "node_modules/acorn": { + "version": "8.17.0", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.17.0.tgz", + "integrity": "sha512-xRQbDb9BnwDafYNn6Vwl839DYVjqXYb1XVGtWAZ1kcDc6iwAL4hg3B1dZlRiuENFeO2H53gFG3in621AdERVAg==", + "dev": true, + "license": "MIT", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/acorn-jsx": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/acorn-jsx/-/acorn-jsx-5.3.2.tgz", + "integrity": "sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" + } + }, + "node_modules/ajv": { + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/ajv/-/ajv-6.15.0.tgz", + "integrity": "sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw==", + "dev": true, + "license": "MIT", + "dependencies": { + "fast-deep-equal": "^3.1.1", + "fast-json-stable-stringify": "^2.0.0", + "json-schema-traverse": "^0.4.1", + "uri-js": "^4.2.2" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/epoberezkin" + } + }, + "node_modules/balanced-match": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-4.0.4.tgz", + "integrity": "sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==", + "dev": true, + "license": "MIT", + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/baseline-browser-mapping": { + "version": "2.10.37", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.10.37.tgz", + "integrity": "sha512-girxaJ7WZssDOFhzCGZTDKoTa1gk6A1TbflaYTpykLJ4UU9Fz9kx1aREM8JCuoVHbL8X8T/mJg7w2oYSq72Oig==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "baseline-browser-mapping": "dist/cli.cjs" + }, + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/brace-expansion": { + "version": "5.0.6", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-5.0.6.tgz", + "integrity": "sha512-kLpxurY4Z4r9sgMsyG0Z9uzsBlgiU/EFKhj/h91/8yHu0edo7XuixOIH3VcJ8kkxs6/jPzoI6U9Vj3WqbMQ94g==", + "dev": true, + "license": "MIT", + "dependencies": { + "balanced-match": "^4.0.2" + }, + "engines": { + "node": "18 || 20 || >=22" + } + }, + "node_modules/browserslist": { + "version": "4.28.2", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.2.tgz", + "integrity": "sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "baseline-browser-mapping": "^2.10.12", + "caniuse-lite": "^1.0.30001782", + "electron-to-chromium": "^1.5.328", + "node-releases": "^2.0.36", + "update-browserslist-db": "^1.2.3" + }, + "bin": { + "browserslist": "cli.js" + }, + "engines": { + "node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7" + } + }, + "node_modules/caniuse-lite": { + "version": "1.0.30001799", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001799.tgz", + "integrity": "sha512-hG1bReV+OUU+MOqK4t/ZWI0tZOyz3rqS9XuhOUz1cIcbwBKjOyJEJuw9ER5JuNyqxNk8u/JUVbGibBOL1yrjFw==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/caniuse-lite" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "CC-BY-4.0" + }, + "node_modules/convert-source-map": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz", + "integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==", + "dev": true, + "license": "MIT" + }, + "node_modules/cross-spawn": { + "version": "7.0.6", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", + "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "dev": true, + "license": "MIT", + "dependencies": { + "path-key": "^3.1.0", + "shebang-command": "^2.0.0", + "which": "^2.0.1" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/debug": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", + "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", + "dev": true, + "license": "MIT", + "dependencies": { + "ms": "^2.1.3" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/deep-is": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz", + "integrity": "sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/electron-to-chromium": { + "version": "1.5.372", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.372.tgz", + "integrity": "sha512-M3yhbAlilnwqC8D21t28UCDGHyitShTmmLRU/H+b74P6Ski16Nb9HONYEaVpMj/pwC7BEo5B95FpjODLCWbtfA==", + "dev": true, + "license": "ISC" + }, + "node_modules/escalade": { + "version": "3.2.0", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz", + "integrity": "sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/eslint": { + "version": "10.5.0", + "resolved": "https://registry.npmjs.org/eslint/-/eslint-10.5.0.tgz", + "integrity": "sha512-1y+7C+vi12bUK1IpZeaV3gsH9fHLBmPvYmPx42pvT/E9yG0IC8g3PUZZgp0+JLJl7ZDK0flc2gc+Aw9dpCvIsQ==", + "dev": true, + "license": "MIT", + "workspaces": [ + "packages/*" + ], + "dependencies": { + "@eslint-community/eslint-utils": "^4.8.0", + "@eslint-community/regexpp": "^4.12.2", + "@eslint/config-array": "^0.23.5", + "@eslint/config-helpers": "^0.6.0", + "@eslint/core": "^1.2.1", + "@eslint/plugin-kit": "^0.7.2", + "@humanfs/node": "^0.16.6", + "@humanwhocodes/module-importer": "^1.0.1", + "@humanwhocodes/retry": "^0.4.2", + "@types/estree": "^1.0.6", + "ajv": "^6.14.0", + "cross-spawn": "^7.0.6", + "debug": "^4.3.2", + "escape-string-regexp": "^4.0.0", + "eslint-scope": "^9.1.2", + "eslint-visitor-keys": "^5.0.1", + "espree": "^11.2.0", + "esquery": "^1.7.0", + "esutils": "^2.0.2", + "fast-deep-equal": "^3.1.3", + "file-entry-cache": "^8.0.0", + "find-up": "^5.0.0", + "glob-parent": "^6.0.2", + "ignore": "^5.2.0", + "imurmurhash": "^0.1.4", + "is-glob": "^4.0.0", + "json-stable-stringify-without-jsonify": "^1.0.1", + "minimatch": "^10.2.4", + "natural-compare": "^1.4.0", + "optionator": "^0.9.3" + }, + "bin": { + "eslint": "bin/eslint.js" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://eslint.org/donate" + }, + "peerDependencies": { + "jiti": "*" + }, + "peerDependenciesMeta": { + "jiti": { + "optional": true + } + } + }, + "node_modules/eslint-plugin-react-hooks": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz", + "integrity": "sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@babel/core": "^7.24.4", + "@babel/parser": "^7.24.4", + "hermes-parser": "^0.25.1", + "zod": "^3.25.0 || ^4.0.0", + "zod-validation-error": "^3.5.0 || ^4.0.0" + }, + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "eslint": "^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0-0 || ^9.0.0 || ^10.0.0" + } + }, + "node_modules/eslint-plugin-react-refresh": { + "version": "0.5.2", + "resolved": "https://registry.npmjs.org/eslint-plugin-react-refresh/-/eslint-plugin-react-refresh-0.5.2.tgz", + "integrity": "sha512-hmgTH57GfzoTFjVN0yBwTggnsVUF2tcqi7RJZHqi9lIezSs4eFyAMktA68YD4r5kNw1mxyY4dmkyoFDb3FIqrA==", + "dev": true, + "license": "MIT", + "peerDependencies": { + "eslint": "^9 || ^10" + } + }, + "node_modules/eslint-scope": { + "version": "9.1.2", + "resolved": "https://registry.npmjs.org/eslint-scope/-/eslint-scope-9.1.2.tgz", + "integrity": "sha512-xS90H51cKw0jltxmvmHy2Iai1LIqrfbw57b79w/J7MfvDfkIkFZ+kj6zC3BjtUwh150HsSSdxXZcsuv72miDFQ==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "@types/esrecurse": "^4.3.1", + "@types/estree": "^1.0.8", + "esrecurse": "^4.3.0", + "estraverse": "^5.2.0" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/eslint-visitor-keys": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz", + "integrity": "sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA==", + "dev": true, + "license": "Apache-2.0", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/espree": { + "version": "11.2.0", + "resolved": "https://registry.npmjs.org/espree/-/espree-11.2.0.tgz", + "integrity": "sha512-7p3DrVEIopW1B1avAGLuCSh1jubc01H2JHc8B4qqGblmg5gI9yumBgACjWo4JlIc04ufug4xJ3SQI8HkS/Rgzw==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "acorn": "^8.16.0", + "acorn-jsx": "^5.3.2", + "eslint-visitor-keys": "^5.0.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=24" + }, + "funding": { + "url": "https://opencollective.com/eslint" + } + }, + "node_modules/esquery": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/esquery/-/esquery-1.7.0.tgz", + "integrity": "sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g==", + "dev": true, + "license": "BSD-3-Clause", + "dependencies": { + "estraverse": "^5.1.0" + }, + "engines": { + "node": ">=0.10" + } + }, + "node_modules/esrecurse": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/esrecurse/-/esrecurse-4.3.0.tgz", + "integrity": "sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "estraverse": "^5.2.0" + }, + "engines": { + "node": ">=4.0" + } + }, + "node_modules/estraverse": { + "version": "5.3.0", + "resolved": "https://registry.npmjs.org/estraverse/-/estraverse-5.3.0.tgz", + "integrity": "sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=4.0" + } + }, + "node_modules/esutils": { + "version": "2.0.3", + "resolved": "https://registry.npmjs.org/esutils/-/esutils-2.0.3.tgz", + "integrity": "sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g==", + "dev": true, + "license": "BSD-2-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/fancy-canvas": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fancy-canvas/-/fancy-canvas-2.1.0.tgz", + "integrity": "sha512-nifxXJ95JNLFR2NgRV4/MxVP45G9909wJTEKz5fg/TZS20JJZA6hfgRVh/bC9bwl2zBtBNcYPjiBE4njQHVBwQ==", + "license": "MIT" + }, + "node_modules/fast-deep-equal": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz", + "integrity": "sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-json-stable-stringify": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz", + "integrity": "sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fast-levenshtein": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz", + "integrity": "sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw==", + "dev": true, + "license": "MIT" + }, + "node_modules/fdir": { + "version": "6.5.0", + "resolved": "https://registry.npmjs.org/fdir/-/fdir-6.5.0.tgz", + "integrity": "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12.0.0" + }, + "peerDependencies": { + "picomatch": "^3 || ^4" + }, + "peerDependenciesMeta": { + "picomatch": { + "optional": true + } + } + }, + "node_modules/file-entry-cache": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/file-entry-cache/-/file-entry-cache-8.0.0.tgz", + "integrity": "sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "flat-cache": "^4.0.0" + }, + "engines": { + "node": ">=16.0.0" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dev": true, + "license": "MIT", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat-cache": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/flat-cache/-/flat-cache-4.0.1.tgz", + "integrity": "sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw==", + "dev": true, + "license": "MIT", + "dependencies": { + "flatted": "^3.2.9", + "keyv": "^4.5.4" + }, + "engines": { + "node": ">=16" + } + }, + "node_modules/flatted": { + "version": "3.4.2", + "resolved": "https://registry.npmjs.org/flatted/-/flatted-3.4.2.tgz", + "integrity": "sha512-PjDse7RzhcPkIJwy5t7KPWQSZ9cAbzQXcafsetQoD7sOJRQlGikNbx7yZp2OotDnJyrDcbyRq3Ttb18iYOqkxA==", + "dev": true, + "license": "ISC" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "dev": true, + "hasInstallScript": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/gensync": { + "version": "1.0.0-beta.2", + "resolved": "https://registry.npmjs.org/gensync/-/gensync-1.0.0-beta.2.tgz", + "integrity": "sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6.9.0" + } + }, + "node_modules/glob-parent": { + "version": "6.0.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", + "integrity": "sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A==", + "dev": true, + "license": "ISC", + "dependencies": { + "is-glob": "^4.0.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/globals": { + "version": "17.6.0", + "resolved": "https://registry.npmjs.org/globals/-/globals-17.6.0.tgz", + "integrity": "sha512-sepffkT8stwnIYbsMBpoCHJuJM5l98FUF2AnE07hfvE0m/qp3R586hw4jF4uadbhvg1ooIdzuu7CsfD2jzCaNA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/hermes-estree": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-estree/-/hermes-estree-0.25.1.tgz", + "integrity": "sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw==", + "dev": true, + "license": "MIT" + }, + "node_modules/hermes-parser": { + "version": "0.25.1", + "resolved": "https://registry.npmjs.org/hermes-parser/-/hermes-parser-0.25.1.tgz", + "integrity": "sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA==", + "dev": true, + "license": "MIT", + "dependencies": { + "hermes-estree": "0.25.1" + } + }, + "node_modules/ignore": { + "version": "5.3.2", + "resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz", + "integrity": "sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 4" + } + }, + "node_modules/imurmurhash": { + "version": "0.1.4", + "resolved": "https://registry.npmjs.org/imurmurhash/-/imurmurhash-0.1.4.tgz", + "integrity": "sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.8.19" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dev": true, + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/isexe": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", + "integrity": "sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==", + "dev": true, + "license": "ISC" + }, + "node_modules/js-tokens": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz", + "integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/jsesc": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/jsesc/-/jsesc-3.1.0.tgz", + "integrity": "sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==", + "dev": true, + "license": "MIT", + "bin": { + "jsesc": "bin/jsesc" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/json-buffer": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz", + "integrity": "sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-schema-traverse": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz", + "integrity": "sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg==", + "dev": true, + "license": "MIT" + }, + "node_modules/json-stable-stringify-without-jsonify": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz", + "integrity": "sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw==", + "dev": true, + "license": "MIT" + }, + "node_modules/json5": { + "version": "2.2.3", + "resolved": "https://registry.npmjs.org/json5/-/json5-2.2.3.tgz", + "integrity": "sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==", + "dev": true, + "license": "MIT", + "bin": { + "json5": "lib/cli.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/keyv": { + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/keyv/-/keyv-4.5.4.tgz", + "integrity": "sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw==", + "dev": true, + "license": "MIT", + "dependencies": { + "json-buffer": "3.0.1" + } + }, + "node_modules/levn": { + "version": "0.4.1", + "resolved": "https://registry.npmjs.org/levn/-/levn-0.4.1.tgz", + "integrity": "sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1", + "type-check": "~0.4.0" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/lightningcss": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.32.0.tgz", + "integrity": "sha512-NXYBzinNrblfraPGyrbPoD19C1h9lfI/1mzgWYvXUTe414Gz/X1FD2XBZSZM7rRTrMA8JL3OtAaGifrIKhQ5yQ==", + "dev": true, + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.32.0", + "lightningcss-darwin-arm64": "1.32.0", + "lightningcss-darwin-x64": "1.32.0", + "lightningcss-freebsd-x64": "1.32.0", + "lightningcss-linux-arm-gnueabihf": "1.32.0", + "lightningcss-linux-arm64-gnu": "1.32.0", + "lightningcss-linux-arm64-musl": "1.32.0", + "lightningcss-linux-x64-gnu": "1.32.0", + "lightningcss-linux-x64-musl": "1.32.0", + "lightningcss-win32-arm64-msvc": "1.32.0", + "lightningcss-win32-x64-msvc": "1.32.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.32.0.tgz", + "integrity": "sha512-YK7/ClTt4kAK0vo6w3X+Pnm0D2cf2vPHbhOXdoNti1Ga0al1P4TBZhwjATvjNwLEBCnKvjJc2jQgHXH0NEwlAg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.32.0.tgz", + "integrity": "sha512-RzeG9Ju5bag2Bv1/lwlVJvBE3q6TtXskdZLLCyfg5pt+HLz9BqlICO7LZM7VHNTTn/5PRhHFBSjk5lc4cmscPQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.32.0.tgz", + "integrity": "sha512-U+QsBp2m/s2wqpUYT/6wnlagdZbtZdndSmut/NJqlCcMLTWp5muCrID+K5UJ6jqD2BFshejCYXniPDbNh73V8w==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.32.0.tgz", + "integrity": "sha512-JCTigedEksZk3tHTTthnMdVfGf61Fky8Ji2E4YjUTEQX14xiy/lTzXnu1vwiZe3bYe0q+SpsSH/CTeDXK6WHig==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.32.0.tgz", + "integrity": "sha512-x6rnnpRa2GL0zQOkt6rts3YDPzduLpWvwAF6EMhXFVZXD4tPrBkEFqzGowzCsIWsPjqSK+tyNEODUBXeeVHSkw==", + "cpu": [ + "arm" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.32.0.tgz", + "integrity": "sha512-0nnMyoyOLRJXfbMOilaSRcLH3Jw5z9HDNGfT/gwCPgaDjnx0i8w7vBzFLFR1f6CMLKF8gVbebmkUN3fa/kQJpQ==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.32.0.tgz", + "integrity": "sha512-UpQkoenr4UJEzgVIYpI80lDFvRmPVg6oqboNHfoH4CQIfNA+HOrZ7Mo7KZP02dC6LjghPQJeBsvXhJod/wnIBg==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.32.0.tgz", + "integrity": "sha512-V7Qr52IhZmdKPVr+Vtw8o+WLsQJYCTd8loIfpDaMRWGUZfBOYEJeyJIkqGIDMZPwPx24pUMfwSxxI8phr/MbOA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.32.0.tgz", + "integrity": "sha512-bYcLp+Vb0awsiXg/80uCRezCYHNg1/l3mt0gzHnWV9XP1W5sKa5/TCdGWaR/zBM2PeF/HbsQv/j2URNOiVuxWg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.32.0.tgz", + "integrity": "sha512-8SbC8BR40pS6baCM8sbtYDSwEVQd4JlFTOlaD3gWGHfThTcABnNDBda6eTZeqbofalIJhFx0qKzgHJmcPTnGdw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.32.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.32.0.tgz", + "integrity": "sha512-Amq9B/SoZYdDi1kFrojnoqPLxYhQ4Wo5XiL8EVJrVsB8ARoC1PWW6VGtT0WKCemjy8aC+louJnjS7U18x3b06Q==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightweight-charts": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/lightweight-charts/-/lightweight-charts-4.1.3.tgz", + "integrity": "sha512-SJacmEyx3LmT2Qsc7Kq7cEX7nEHtQv0MOlujhRlcDxhW62pG6nkBlcM52/jNqkq8B28KQeVmgOQ7zrdJ4BCPDw==", + "license": "Apache-2.0", + "dependencies": { + "fancy-canvas": "2.1.0" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/lru-cache": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-5.1.1.tgz", + "integrity": "sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==", + "dev": true, + "license": "ISC", + "dependencies": { + "yallist": "^3.0.2" + } + }, + "node_modules/minimatch": { + "version": "10.2.5", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-10.2.5.tgz", + "integrity": "sha512-MULkVLfKGYDFYejP07QOurDLLQpcjk7Fw+7jXS2R2czRQzR56yHRveU5NDJEOviH+hETZKSkIk5c+T23GjFUMg==", + "dev": true, + "license": "BlueOak-1.0.0", + "dependencies": { + "brace-expansion": "^5.0.5" + }, + "engines": { + "node": "18 || 20 || >=22" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", + "dev": true, + "license": "MIT" + }, + "node_modules/nanoid": { + "version": "3.3.12", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz", + "integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==", + "dev": true, + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/natural-compare": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/natural-compare/-/natural-compare-1.4.0.tgz", + "integrity": "sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==", + "dev": true, + "license": "MIT" + }, + "node_modules/node-releases": { + "version": "2.0.47", + "resolved": "https://registry.npmjs.org/node-releases/-/node-releases-2.0.47.tgz", + "integrity": "sha512-Uzmd6LXpouKo8EUK68IjH4+E01w/hXyV3R3g/geCJo+rXLNfh1xucB+LOzYEOQPSiUK3h/xZf0cQGcSsmyL2Og==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + } + }, + "node_modules/optionator": { + "version": "0.9.4", + "resolved": "https://registry.npmjs.org/optionator/-/optionator-0.9.4.tgz", + "integrity": "sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g==", + "dev": true, + "license": "MIT", + "dependencies": { + "deep-is": "^0.1.3", + "fast-levenshtein": "^2.0.6", + "levn": "^0.4.1", + "prelude-ls": "^1.2.1", + "type-check": "^0.4.0", + "word-wrap": "^1.2.5" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dev": true, + "license": "MIT", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dev": true, + "license": "MIT", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-key": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/path-key/-/path-key-3.1.1.tgz", + "integrity": "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "dev": true, + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.4.tgz", + "integrity": "sha512-QP88BAKvMam/3NxH6vj2o21R6MjxZUAd6nlwAS/pnGvN9IVLocLHxGYIzFhg6fUQ+5th6P4dv4eW9jX3DSIj7A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/postcss": { + "version": "8.5.15", + "resolved": "https://registry.npmjs.org/postcss/-/postcss-8.5.15.tgz", + "integrity": "sha512-FfR8sjd4em2T6fb3I2MwAJU7HWVMr9zba+enmQeeWFfCbm+UOC/0X4DS8XtpUTMwWMGbjKYP7xjfNekzyGmB3A==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/postcss/" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/postcss" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "nanoid": "^3.3.12", + "picocolors": "^1.1.1", + "source-map-js": "^1.2.1" + }, + "engines": { + "node": "^10 || ^12 || >=14" + } + }, + "node_modules/prelude-ls": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/prelude-ls/-/prelude-ls-1.2.1.tgz", + "integrity": "sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/punycode": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz", + "integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=6" + } + }, + "node_modules/react": { + "version": "19.2.7", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.7.tgz", + "integrity": "sha512-HNe9WslTbXmFK8o8cmwgAeJFSBvt1bPdHCVKtaaV+WlAN36mpT4hcRpwbf3fY56ar2oIXzsBpOAiIRHAdY0OlQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-dom": { + "version": "19.2.7", + "resolved": "https://registry.npmjs.org/react-dom/-/react-dom-19.2.7.tgz", + "integrity": "sha512-t0BRVXvbiE/o20Hfw669rLbMCDWtYZLvmJigy2f0MxsXF+71pxhR3xOkspmsO8h3ZlNzyibAmtCa3l4lYKk6gQ==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "peerDependencies": { + "react": "^19.2.7" + } + }, + "node_modules/rolldown": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/rolldown/-/rolldown-1.0.3.tgz", + "integrity": "sha512-i00lAJ2ks1BYr7rjNjKC7BcqAS7nVfiT3QX1SI5aY+AFHblCmaUf9OE9dbdzDvW6dJxbi2ZCZiy9v3CcwOiX3g==", + "dev": true, + "license": "MIT", + "dependencies": { + "@oxc-project/types": "=0.133.0", + "@rolldown/pluginutils": "^1.0.0" + }, + "bin": { + "rolldown": "bin/cli.mjs" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "optionalDependencies": { + "@rolldown/binding-android-arm64": "1.0.3", + "@rolldown/binding-darwin-arm64": "1.0.3", + "@rolldown/binding-darwin-x64": "1.0.3", + "@rolldown/binding-freebsd-x64": "1.0.3", + "@rolldown/binding-linux-arm-gnueabihf": "1.0.3", + "@rolldown/binding-linux-arm64-gnu": "1.0.3", + "@rolldown/binding-linux-arm64-musl": "1.0.3", + "@rolldown/binding-linux-ppc64-gnu": "1.0.3", + "@rolldown/binding-linux-s390x-gnu": "1.0.3", + "@rolldown/binding-linux-x64-gnu": "1.0.3", + "@rolldown/binding-linux-x64-musl": "1.0.3", + "@rolldown/binding-openharmony-arm64": "1.0.3", + "@rolldown/binding-wasm32-wasi": "1.0.3", + "@rolldown/binding-win32-arm64-msvc": "1.0.3", + "@rolldown/binding-win32-x64-msvc": "1.0.3" + } + }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, + "node_modules/semver": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", + "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", + "dev": true, + "license": "ISC", + "bin": { + "semver": "bin/semver.js" + } + }, + "node_modules/shebang-command": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/shebang-command/-/shebang-command-2.0.0.tgz", + "integrity": "sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA==", + "dev": true, + "license": "MIT", + "dependencies": { + "shebang-regex": "^3.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/shebang-regex": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/shebang-regex/-/shebang-regex-3.0.0.tgz", + "integrity": "sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=8" + } + }, + "node_modules/source-map-js": { + "version": "1.2.1", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", + "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "dev": true, + "license": "BSD-3-Clause", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/tinyglobby": { + "version": "0.2.17", + "resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz", + "integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==", + "dev": true, + "license": "MIT", + "dependencies": { + "fdir": "^6.5.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">=12.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/SuperchupuDev" + } + }, + "node_modules/ts-api-utils": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/ts-api-utils/-/ts-api-utils-2.5.0.tgz", + "integrity": "sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.12" + }, + "peerDependencies": { + "typescript": ">=4.8.4" + } + }, + "node_modules/tslib": { + "version": "2.8.1", + "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", + "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", + "dev": true, + "license": "0BSD", + "optional": true + }, + "node_modules/type-check": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/type-check/-/type-check-0.4.0.tgz", + "integrity": "sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew==", + "dev": true, + "license": "MIT", + "dependencies": { + "prelude-ls": "^1.2.1" + }, + "engines": { + "node": ">= 0.8.0" + } + }, + "node_modules/typescript": { + "version": "6.0.3", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz", + "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==", + "dev": true, + "license": "Apache-2.0", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/typescript-eslint": { + "version": "8.61.0", + "resolved": "https://registry.npmjs.org/typescript-eslint/-/typescript-eslint-8.61.0.tgz", + "integrity": "sha512-8y31Rd0eGTrDKqhy6vT0HtzhN+YLjQizwX3aA3hPXP/ynSfnrBXcQY5IzsP9/DM7+klX4IUncZZjkchP0z+rUw==", + "dev": true, + "license": "MIT", + "dependencies": { + "@typescript-eslint/eslint-plugin": "8.61.0", + "@typescript-eslint/parser": "8.61.0", + "@typescript-eslint/typescript-estree": "8.61.0", + "@typescript-eslint/utils": "8.61.0" + }, + "engines": { + "node": "^18.18.0 || ^20.9.0 || >=21.1.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/typescript-eslint" + }, + "peerDependencies": { + "eslint": "^8.57.0 || ^9.0.0 || ^10.0.0", + "typescript": ">=4.8.4 <6.1.0" + } + }, + "node_modules/undici-types": { + "version": "7.18.2", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz", + "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==", + "dev": true, + "license": "MIT" + }, + "node_modules/update-browserslist-db": { + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", + "dev": true, + "funding": [ + { + "type": "opencollective", + "url": "https://opencollective.com/browserslist" + }, + { + "type": "tidelift", + "url": "https://tidelift.com/funding/github/npm/browserslist" + }, + { + "type": "github", + "url": "https://github.com/sponsors/ai" + } + ], + "license": "MIT", + "dependencies": { + "escalade": "^3.2.0", + "picocolors": "^1.1.1" + }, + "bin": { + "update-browserslist-db": "cli.js" + }, + "peerDependencies": { + "browserslist": ">= 4.21.0" + } + }, + "node_modules/uri-js": { + "version": "4.4.1", + "resolved": "https://registry.npmjs.org/uri-js/-/uri-js-4.4.1.tgz", + "integrity": "sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg==", + "dev": true, + "license": "BSD-2-Clause", + "dependencies": { + "punycode": "^2.1.0" + } + }, + "node_modules/vite": { + "version": "8.0.16", + "resolved": "https://registry.npmjs.org/vite/-/vite-8.0.16.tgz", + "integrity": "sha512-h9bXPmJichP5fLmVQo3PyaGSDE2n3aPuomeAlVRm0JLmt4rY6zmPKd59HYI4LNW8oTK7tlTsuC7l/m7awx9Jcw==", + "dev": true, + "license": "MIT", + "dependencies": { + "lightningcss": "^1.32.0", + "picomatch": "^4.0.4", + "postcss": "^8.5.15", + "rolldown": "1.0.3", + "tinyglobby": "^0.2.17" + }, + "bin": { + "vite": "bin/vite.js" + }, + "engines": { + "node": "^20.19.0 || >=22.12.0" + }, + "funding": { + "url": "https://github.com/vitejs/vite?sponsor=1" + }, + "optionalDependencies": { + "fsevents": "~2.3.3" + }, + "peerDependencies": { + "@types/node": "^20.19.0 || >=22.12.0", + "@vitejs/devtools": "^0.1.18", + "esbuild": "^0.27.0 || ^0.28.0", + "jiti": ">=1.21.0", + "less": "^4.0.0", + "sass": "^1.70.0", + "sass-embedded": "^1.70.0", + "stylus": ">=0.54.8", + "sugarss": "^5.0.0", + "terser": "^5.16.0", + "tsx": "^4.8.1", + "yaml": "^2.4.2" + }, + "peerDependenciesMeta": { + "@types/node": { + "optional": true + }, + "@vitejs/devtools": { + "optional": true + }, + "esbuild": { + "optional": true + }, + "jiti": { + "optional": true + }, + "less": { + "optional": true + }, + "sass": { + "optional": true + }, + "sass-embedded": { + "optional": true + }, + "stylus": { + "optional": true + }, + "sugarss": { + "optional": true + }, + "terser": { + "optional": true + }, + "tsx": { + "optional": true + }, + "yaml": { + "optional": true + } + } + }, + "node_modules/which": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz", + "integrity": "sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA==", + "dev": true, + "license": "ISC", + "dependencies": { + "isexe": "^2.0.0" + }, + "bin": { + "node-which": "bin/node-which" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/word-wrap": { + "version": "1.2.5", + "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", + "integrity": "sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/yallist": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yallist/-/yallist-3.1.1.tgz", + "integrity": "sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==", + "dev": true, + "license": "ISC" + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/zod": { + "version": "4.4.3", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.4.3.tgz", + "integrity": "sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==", + "dev": true, + "license": "MIT", + "funding": { + "url": "https://github.com/sponsors/colinhacks" + } + }, + "node_modules/zod-validation-error": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/zod-validation-error/-/zod-validation-error-4.0.2.tgz", + "integrity": "sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18.0.0" + }, + "peerDependencies": { + "zod": "^3.25.0 || ^4.0.0" + } + } + } +} diff --git a/external/Quant.ai/frontend/package.json b/external/Quant.ai/frontend/package.json new file mode 100644 index 0000000000000000000000000000000000000000..5e39da403b22aaa07b04e96e6ac462ed77f07f55 --- /dev/null +++ b/external/Quant.ai/frontend/package.json @@ -0,0 +1,31 @@ +{ + "name": "frontend", + "private": true, + "version": "0.0.0", + "type": "module", + "scripts": { + "dev": "vite", + "build": "tsc -b && vite build", + "lint": "eslint .", + "preview": "vite preview" + }, + "dependencies": { + "lightweight-charts": "^4.1.3", + "react": "^19.2.6", + "react-dom": "^19.2.6" + }, + "devDependencies": { + "@eslint/js": "^10.0.1", + "@types/node": "^24.12.3", + "@types/react": "^19.2.14", + "@types/react-dom": "^19.2.3", + "@vitejs/plugin-react": "^6.0.1", + "eslint": "^10.3.0", + "eslint-plugin-react-hooks": "^7.1.1", + "eslint-plugin-react-refresh": "^0.5.2", + "globals": "^17.6.0", + "typescript": "~6.0.2", + "typescript-eslint": "^8.59.2", + "vite": "^8.0.12" + } +} diff --git a/external/Quant.ai/frontend/public/favicon.svg b/external/Quant.ai/frontend/public/favicon.svg new file mode 100644 index 0000000000000000000000000000000000000000..6893eb13237060adc0c968a690149a49faa2d7d3 --- /dev/null +++ b/external/Quant.ai/frontend/public/favicon.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/external/Quant.ai/frontend/public/icons.svg b/external/Quant.ai/frontend/public/icons.svg new file mode 100644 index 0000000000000000000000000000000000000000..e9522193d9f796a9748e9ad8c952a5df73c87db9 --- /dev/null +++ b/external/Quant.ai/frontend/public/icons.svg @@ -0,0 +1,24 @@ + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/external/Quant.ai/frontend/src/App.css b/external/Quant.ai/frontend/src/App.css new file mode 100644 index 0000000000000000000000000000000000000000..f90339d8f765fa2c69d9a341959a8ddb9fff5720 --- /dev/null +++ b/external/Quant.ai/frontend/src/App.css @@ -0,0 +1,184 @@ +.counter { + font-size: 16px; + padding: 5px 10px; + border-radius: 5px; + color: var(--accent); + background: var(--accent-bg); + border: 2px solid transparent; + transition: border-color 0.3s; + margin-bottom: 24px; + + &:hover { + border-color: var(--accent-border); + } + &:focus-visible { + outline: 2px solid var(--accent); + outline-offset: 2px; + } +} + +.hero { + position: relative; + + .base, + .framework, + .vite { + inset-inline: 0; + margin: 0 auto; + } + + .base { + width: 170px; + position: relative; + z-index: 0; + } + + .framework, + .vite { + position: absolute; + } + + .framework { + z-index: 1; + top: 34px; + height: 28px; + transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg) + scale(1.4); + } + + .vite { + z-index: 0; + top: 107px; + height: 26px; + width: auto; + transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg) + scale(0.8); + } +} + +#center { + display: flex; + flex-direction: column; + gap: 25px; + place-content: center; + place-items: center; + flex-grow: 1; + + @media (max-width: 1024px) { + padding: 32px 20px 24px; + gap: 18px; + } +} + +#next-steps { + display: flex; + border-top: 1px solid var(--border); + text-align: left; + + & > div { + flex: 1 1 0; + padding: 32px; + @media (max-width: 1024px) { + padding: 24px 20px; + } + } + + .icon { + margin-bottom: 16px; + width: 22px; + height: 22px; + } + + @media (max-width: 1024px) { + flex-direction: column; + text-align: center; + } +} + +#docs { + border-right: 1px solid var(--border); + + @media (max-width: 1024px) { + border-right: none; + border-bottom: 1px solid var(--border); + } +} + +#next-steps ul { + list-style: none; + padding: 0; + display: flex; + gap: 8px; + margin: 32px 0 0; + + .logo { + height: 18px; + } + + a { + color: var(--text-h); + font-size: 16px; + border-radius: 6px; + background: var(--social-bg); + display: flex; + padding: 6px 12px; + align-items: center; + gap: 8px; + text-decoration: none; + transition: box-shadow 0.3s; + + &:hover { + box-shadow: var(--shadow); + } + .button-icon { + height: 18px; + width: 18px; + } + } + + @media (max-width: 1024px) { + margin-top: 20px; + flex-wrap: wrap; + justify-content: center; + + li { + flex: 1 1 calc(50% - 8px); + } + + a { + width: 100%; + justify-content: center; + box-sizing: border-box; + } + } +} + +#spacer { + height: 88px; + border-top: 1px solid var(--border); + @media (max-width: 1024px) { + height: 48px; + } +} + +.ticks { + position: relative; + width: 100%; + + &::before, + &::after { + content: ''; + position: absolute; + top: -4.5px; + border: 5px solid transparent; + } + + &::before { + left: 0; + border-left-color: var(--border); + } + &::after { + right: 0; + border-right-color: var(--border); + } +} diff --git a/external/Quant.ai/frontend/src/App.tsx b/external/Quant.ai/frontend/src/App.tsx new file mode 100644 index 0000000000000000000000000000000000000000..32fe6db84a89679fccb31d2e915d732db9fbf77e --- /dev/null +++ b/external/Quant.ai/frontend/src/App.tsx @@ -0,0 +1,932 @@ +// frontend/src/App.tsx + +import React, { useState, useEffect, useRef } from 'react'; +import { StockChart } from './components/StockChart'; +import { PortfolioStats } from './components/PortfolioStats'; +import { LedgerTable, type LedgerItem } from './components/LedgerTable'; +import { IntradayZoomChart } from './components/IntradayZoomChart'; +import { StrategySettings, type StrategyParams } from './components/StrategySettings'; +import { CompanyInfoCard } from './components/CompanyInfoCard'; +import { PatternLog } from './components/PatternLog'; +import { ScannerPanel } from './components/ScannerPanel'; +import { ChatPanel } from './components/ChatPanel'; +import { EquityCurve } from './components/EquityCurve'; +import { RegimeBreakdown } from './components/RegimeBreakdown'; +import { ResearchReportPanel } from './components/ResearchReportPanel'; +import { WalkForwardPanel } from './components/WalkForwardPanel'; +import { ExperimentCompare } from './components/ExperimentCompare'; +import { BrokerPanel } from './components/BrokerPanel'; +import { SameDayReplayPanel } from './components/SameDayReplayPanel'; + +interface SummaryData { + initial_cash: number; + final_equity: number; + net_pnl: number; + pnl_pct: number; + total_trades: number; + round_trips: number; + win_rate: number; + commission: number; + max_drawdown: number; + sharpe: number; + calmar: number; + cagr: number; + profit_factor: number; + gross_profit: number; + gross_loss: number; +} + +interface CandleData { + time: number; + open: number; + high: number; + low: number; + close: number; + volume: number; + vwap: number | null; + ema_9: number | null; + ema_21: number | null; + ema_50: number | null; + rsi: number | null; + squeeze: boolean; +} + + + +interface ChartMarker { + time: number; + position: 'aboveBar' | 'belowBar'; + color: string; + shape: 'arrowUp' | 'arrowDown'; + text: string; +} + +interface PatternEvent { + time: string; + ticker: string; + pattern: string; + type: 'bullish' | 'bearish'; + price: number; + desc: string; +} + +interface RegimeData { + regime: string; + total_pnl: number; + trade_count: number; + win_rate: number; + wins: number; + losses: number; + commission: number; +} + + + +interface BacktestResponse { + success: boolean; + ticker: string; + period: string; + interval: string; + summary: SummaryData; + ledger: LedgerItem[]; + candles: CandleData[]; + markers: ChartMarker[]; + equity_curve: { time: number; value: number }[]; + drawdown_curve: { time: number; value: number }[]; + regime_breakdown: RegimeData[]; + regime_distribution: Record; + patterns_log: PatternEvent[]; + error?: string; +} + +interface CompanyInfo { + name: string; + sector: string; + industry: string; + market_cap: number; + description: string; +} + +const DEFAULT_STRATEGY_PARAMS: StrategyParams = { + strategy_mode: 'opening_breakout', + stop_loss_pct: 0.015, + profit_target_pct: 0.030, + trailing_stop_mode: 'atr', + trailing_stop_atr_mult: 2.0, + rsi_threshold_buy: 65, + risk_per_trade_pct: 0.01, + max_position_size_pct: 0.50, + position_sizing_mode: 'atr', + commission_per_share: 0.005, + slippage_rate: 0.0003, + market_open_focus: true +}; + +const INTERVAL_LABELS: Record = { + "1m": "1 Min", + "5m": "5 Min", + "15m": "15 Min", + "30m": "30 Min", + "1h": "1 Hour", + "1d": "Daily" +}; + +type ActiveTab = 'dashboard' | 'research' | 'report' | 'walkforward' | 'experiments' | 'replay' | 'broker'; + +function App() { + const [watchlist, setWatchlist] = useState(["TSLA", "NVDA", "AAPL", "MSFT", "AMD"]); + const [newTickerInput, setNewTickerInput] = useState(''); + + const [activeTicker, setActiveTicker] = useState('TSLA'); + const [activeInterval, setActiveInterval] = useState('1d'); + const [strategyParams, setStrategyParams] = useState(DEFAULT_STRATEGY_PARAMS); + const [activeTab, setActiveTab] = useState('broker'); + + const [loading, setLoading] = useState(true); + const [data, setData] = useState(null); + const [sidebarPrices, setSidebarPrices] = useState>({}); + + // 公司元数据状态 + const [companyInfo, setCompanyInfo] = useState(null); + const [infoLoading, setInfoLoading] = useState(false); + + // AI 智能托管托管状态 + const [aiAutoPilot, setAiAutoPilot] = useState(true); + const [tuningLoading, setTuningLoading] = useState(false); + const [tuningReport, setTuningReport] = useState(null); + const [tuningMetrics, setTuningMetrics] = useState(null); + + // Intraday Zoom Panel states + const [zoomTradeItem, setZoomTradeItem] = useState(null); + const [zoomCandles, setZoomCandles] = useState([]); + const [zoomLoading, setZoomLoading] = useState(false); + const [focusTime, setFocusTime] = useState(undefined); + + // Replay Simulator states + const [availableDates, setAvailableDates] = useState([]); + const [replayDate, setReplayDate] = useState(''); + const [replayLoading, setReplayLoading] = useState(false); + const [replayData, setReplayData] = useState(null); + const [replayIndex, setReplayIndex] = useState(0); + const [isPlaying, setIsPlaying] = useState(false); + const [replaySpeed, setReplaySpeed] = useState(300); + + // Workflow Guide visibility + const [showGuide, setShowGuide] = useState(true); + + // AI 智能调参逻辑 + useEffect(() => { + if (!aiAutoPilot) { + setTuningReport(null); + setTuningMetrics(null); + return; + } + + const runAiTuning = async () => { + setTuningLoading(true); + try { + const response = await fetch('http://127.0.0.1:8000/api/ai_tune', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ + ticker: activeTicker.toUpperCase(), + interval: activeInterval, + period: activeInterval === '1m' ? '5d' : '1mo' + }) + }); + const json = await response.json(); + if (json.success) { + // 应用 AI 调参最优值 + setStrategyParams(prev => ({ + ...prev, + ...json.best_params + })); + setTuningReport(json.reasoning); + setTuningMetrics(json.metrics); + } + } catch (e) { + console.error("AI dynamic tuning call failed:", e); + } finally { + setTuningLoading(false); + } + }; + + runAiTuning(); + }, [aiAutoPilot, activeTicker, activeInterval]); + + // 1. 获取回测仿真数据 (参数改变自动重算) + useEffect(() => { + const fetchBacktestData = async () => { + setLoading(true); + try { + const queryParams = new URLSearchParams({ + ticker: activeTicker, + interval: activeInterval, + strategy_mode: strategyParams.strategy_mode, + stop_loss_pct: String(strategyParams.stop_loss_pct), + profit_target_pct: String(strategyParams.profit_target_pct), + trailing_stop_mode: strategyParams.trailing_stop_mode, + trailing_stop_atr_mult: String(strategyParams.trailing_stop_atr_mult), + rsi_threshold_buy: String(strategyParams.rsi_threshold_buy), + risk_per_trade_pct: String(strategyParams.risk_per_trade_pct), + max_position_size_pct: String(strategyParams.max_position_size_pct), + position_sizing_mode: strategyParams.position_sizing_mode, + commission_per_share: String(strategyParams.commission_per_share), + slippage_rate: String(strategyParams.slippage_rate), + market_open_focus: String(strategyParams.market_open_focus) + }); + + const res = await fetch(`http://127.0.0.1:8000/api/backtest?${queryParams.toString()}`); + const json: BacktestResponse = await res.json(); + + if (json.success) { + setData(json); + // 更新侧边栏收盘价 + if (json.candles.length > 0) { + const lastCandle = json.candles[json.candles.length - 1]; + setSidebarPrices(prev => ({ + ...prev, + [activeTicker]: lastCandle.close + })); + } + } else { + console.error("Backtest failed:", json.error); + } + } catch (e) { + console.error("API connection failed:", e); + } finally { + setLoading(false); + } + }; + + // 如果 AI 调参中,等待调参完成再拉取数据以防止触发多次不一致的请求 + if (!tuningLoading) { + fetchBacktestData(); + } + }, [activeTicker, activeInterval, strategyParams, tuningLoading]); + + // 2. 获取公司详情介绍 + useEffect(() => { + const fetchCompanyDetails = async () => { + setInfoLoading(true); + try { + const res = await fetch(`http://127.0.0.1:8000/api/company_info?ticker=${activeTicker}`); + const json = await res.json(); + setCompanyInfo(json); + } catch (e) { + console.error("Company info fetch failed:", e); + } finally { + setInfoLoading(false); + } + }; + + fetchCompanyDetails(); + }, [activeTicker]); + + // 3. 异步获取侧边栏其它股票的基本收盘价 + useEffect(() => { + const fetchInitialPrices = async () => { + for (const ticker of watchlist) { + if (ticker === activeTicker) continue; + try { + const res = await fetch(`http://127.0.0.1:8000/api/backtest?ticker=${ticker}&interval=1d`); + const json: BacktestResponse = await res.json(); + if (json.success && json.candles.length > 0) { + const lastCandle = json.candles[json.candles.length - 1]; + setSidebarPrices(prev => ({ + ...prev, + [ticker]: lastCandle.close + })); + } + } catch (e) {} + } + }; + fetchInitialPrices(); + }, [watchlist]); + + const handleTickerChange = (ticker: string) => { + setActiveTicker(ticker); + }; + + const handleIntervalChange = (interval: string) => { + setActiveInterval(interval); + }; + + // Handle AI agent backtest request + const handleAgentBacktest = (config: Record) => { + const newParams: StrategyParams = { + ...DEFAULT_STRATEGY_PARAMS, + ...config as Partial + }; + const ticker = (config.ticker as string) || activeTicker; + const interval = (config.interval as string) || activeInterval; + + setActiveTicker(ticker.toUpperCase()); + setActiveInterval(interval); + setStrategyParams(newParams); + }; + + // available dates fetch side-effect + useEffect(() => { + if (activeTab === 'replay') { + const fetchDates = async () => { + try { + const res = await fetch(`http://127.0.0.1:8000/api/replay/available_dates?ticker=${activeTicker}`); + const json = await res.json(); + if (json.success && json.dates.length > 0) { + setAvailableDates(json.dates); + setReplayDate(json.dates[0]); // default to latest day + } + } catch (e) { + console.error("Failed to fetch available dates:", e); + } + }; + fetchDates(); + } + }, [activeTab, activeTicker]); + + // load replay data + const handleLoadReplay = async () => { + if (!replayDate) return; + setReplayLoading(true); + setIsPlaying(false); + setReplayIndex(0); + setReplayData(null); + try { + const params = new URLSearchParams({ + ticker: activeTicker.toUpperCase(), + date: replayDate, + strategy_mode: strategyParams.strategy_mode, + stop_loss_pct: String(strategyParams.stop_loss_pct), + profit_target_pct: String(strategyParams.profit_target_pct), + trailing_stop_mode: strategyParams.trailing_stop_mode, + trailing_stop_atr_mult: String(strategyParams.trailing_stop_atr_mult), + rsi_threshold_buy: String(strategyParams.rsi_threshold_buy), + risk_per_trade_pct: String(strategyParams.risk_per_trade_pct), + max_position_size_pct: String(strategyParams.max_position_size_pct), + commission_per_share: String(strategyParams.commission_per_share), + slippage_rate: String(strategyParams.slippage_rate), + market_open_focus: String(strategyParams.market_open_focus), + }); + const res = await fetch(`http://127.0.0.1:8000/api/replay/data?${params.toString()}`); + const json = await res.json(); + if (json.success) { + setReplayData(json); + setReplayIndex(0); + } else { + alert("加载复盘数据失败: " + json.error); + } + } catch (e) { + console.error(e); + alert("网络请求失败"); + } finally { + setReplayLoading(false); + } + }; + + const playbackTimerRef = useRef(null); + + // Playback timer loop + useEffect(() => { + if (isPlaying && replayData && replayIndex < replayData.candles.length - 1) { + playbackTimerRef.current = setInterval(() => { + setReplayIndex((prev) => { + if (prev >= replayData.candles.length - 1) { + setIsPlaying(false); + clearInterval(playbackTimerRef.current); + return prev; + } + return prev + 1; + }); + }, replaySpeed); + } else { + if (playbackTimerRef.current) { + clearInterval(playbackTimerRef.current); + } + } + + return () => { + if (playbackTimerRef.current) { + clearInterval(playbackTimerRef.current); + } + }; + }, [isPlaying, replayData, replayIndex, replaySpeed]); + + // Ledger row click handler + const handleLedgerRowClick = async (item: LedgerItem) => { + if (activeInterval === '1d') { + setZoomLoading(true); + setZoomTradeItem(item); + setZoomCandles([]); + try { + const dateStr = item.timestamp.split(' ')[0]; // YYYY-MM-DD + const res = await fetch(`http://127.0.0.1:8000/api/intraday_data?ticker=${item.ticker}&date=${dateStr}`); + const json = await res.json(); + if (json.success) { + setZoomCandles(json.candles); + } else { + alert("加载日内数据失败: " + json.error); + } + } catch (e) { + console.error(e); + } finally { + setZoomLoading(false); + } + } else { + const t = Math.floor(new Date(item.timestamp).getTime() / 1000); + setFocusTime(t); + const chartEl = document.getElementById('main-chart-card'); + chartEl?.scrollIntoView({ behavior: 'smooth' }); + } + }; + + // Replay live state calculations + const slicedCandles = replayData ? replayData.candles.slice(0, replayIndex + 1) : []; + const currentTimestamp = slicedCandles.length > 0 ? slicedCandles[slicedCandles.length - 1].time : 0; + + const slicedLedger = replayData + ? replayData.ledger.filter((item: any) => { + const t = Math.floor(new Date(item.timestamp).getTime() / 1000); + return t <= currentTimestamp; + }) + : []; + + const slicedMarkers = replayData + ? replayData.markers.filter((m: any) => m.time <= currentTimestamp) + : []; + + const getLiveReplayStats = () => { + if (!replayData || slicedCandles.length === 0) return { cash: 100000, shares: 0, positionValue: 0, equity: 100000, pnl: 0, pnlPct: 0 }; + + let cash = 100000; + let shares = 0; + + for (const item of slicedLedger) { + cash = item.cash_remaining; + if (item.action === 'BUY') { + shares += item.shares; + } else { + shares -= item.shares; + } + } + + const lastCandle = slicedCandles[slicedCandles.length - 1]; + const currentPrice = lastCandle.close; + const positionValue = shares * currentPrice; + const equity = cash + positionValue; + const netPnL = equity - 100000; + const pnlPct = (netPnL / 100000) * 100; + + return { + cash, + shares, + positionValue, + equity, + pnl: netPnL, + pnlPct, + currentPrice + }; + }; + + const liveStats = getLiveReplayStats(); + + // 添加自选股 + const handleAddTicker = (e: React.FormEvent) => { + e.preventDefault(); + const cleanTicker = newTickerInput.trim().toUpperCase(); + if (cleanTicker && !watchlist.includes(cleanTicker)) { + setWatchlist([...watchlist, cleanTicker]); + setActiveTicker(cleanTicker); + setNewTickerInput(''); + } + }; + + // 删除自选股 + const handleRemoveTicker = (tickerToRemove: string, e: React.MouseEvent) => { + e.stopPropagation(); + const newWatchlist = watchlist.filter(t => t !== tickerToRemove); + setWatchlist(newWatchlist); + if (activeTicker === tickerToRemove && newWatchlist.length > 0) { + setActiveTicker(newWatchlist[0]); + } + }; + + const resetStrategyParams = () => { + setStrategyParams(DEFAULT_STRATEGY_PARAMS); + }; + + // 盈亏汇总 + const hasPnL = data && data.summary; + const netPnL = hasPnL ? data.summary.net_pnl : 0; + const isPnLUp = netPnL >= 0; + const pnlColorClass = isPnLUp ? 'up' : 'down'; + const pnlSign = isPnLUp ? '+' : ''; + + return ( +
+ {/* 顶部标题栏 */} +
+
+ Quant.ai +
+ + {/* Simplified Two Core Modes Navigation */} +
+ + + + {/* Optional Advanced Tools */} + +
+ +
+ Quant.ai +
+
+ + {/* 主布局网格 */} +
+ {/* 左侧内容区 */} +
+ {/* Deep Research Tab */} + {activeTab === 'report' && ( + { + setStrategyParams(prev => ({ ...prev, ...config })); + setActiveTab(tab); + }} + activeTicker={activeTicker} + /> + )} + + {/* AI Research Tab */} + {activeTab === 'research' && ( + + )} + + {/* Walk-Forward Tab */} + {activeTab === 'walkforward' && ( + + )} + + {/* Experiments Tab */} + {activeTab === 'experiments' && ( + + )} + + {/* Alpaca Live Tab (Mode 1) */} + {activeTab === 'broker' && ( + + )} + + {/* Replay Simulator Tab (Mode 2) */} + {activeTab === 'replay' && ( + + )} + + {(activeTab === 'dashboard' || activeTab === 'research') && ( + loading ? ( +
+ Simulating {activeTicker} ({INTERVAL_LABELS[activeInterval] || activeInterval}) backtest... +
+ ) : data ? ( + <> + {/* 账户资产价值计数器 */} +
+
+
+ ${data.summary.final_equity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} +
+
+ {pnlSign}${data.summary.net_pnl.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} ({pnlSign}{data.summary.pnl_pct.toFixed(2)}%) +
+
+ + {/* 周期切换器 */} +
+
+ {Object.entries(INTERVAL_LABELS).map(([key]) => ( + + ))} +
+
+
+ + {/* 核心 K 线图表 */} +
+ +
+ + {/* Equity & Drawdown Curves */} + + + {/* Regime Breakdown */} + + + {/* AI 托管微调状态报告 */} + {activeTab === 'dashboard' && tuningLoading && ( +
+
+
+

AI 托管机器学习模型正在自动优化最佳参数...

+

正在对 {activeTicker} 近期 5 天的高频 1m 波动率和突破阻力位进行量化网格搜索。

+
+
+ )} + + {activeTab === 'dashboard' && aiAutoPilot && tuningReport && !tuningLoading && ( +
+
+ 🛡️ +

AI 智能托管报告 (AI Auto-Pilot Tuning Report)

+
+
+

+ {tuningReport} +

+ + {tuningMetrics && ( +
+
+
回测总盈亏
+
= 0 ? 'var(--color-green)' : 'var(--color-red)' }}> + ${tuningMetrics.net_pnl.toFixed(2)} +
+
+
+
测算胜率
+
+ {tuningMetrics.win_rate.toFixed(1)}% +
+
+
+
最大回撤
+
+ {(tuningMetrics.max_drawdown * 100).toFixed(2)}% +
+
+
+
测算交易数
+
+ {tuningMetrics.round_trips} 笔 +
+
+
+ )} +
+
+ )} + + {/* 策略设置与形态识别日志 并排展示 */} + {activeTab === 'dashboard' && ( + <> +
+ + +
+ + {/* 选股扫描面板 */} + + + )} + + {/* 账户业绩统计 */} + + + {/* 交易明细账本 */} + + + {/* 日内 1分钟 交易微观透视 */} + {zoomLoading && ( +
+
+ + 正在拉取 {zoomTradeItem?.ticker} 日内高频分时数据并进行 1分钟 细节对齐... + +
+ )} + {!zoomLoading && zoomTradeItem && zoomCandles.length > 0 && ( + { + setZoomTradeItem(null); + setZoomCandles([]); + }} + /> + )} + + ) : ( +
+ Cannot connect to backend. Please ensure FastAPI is running on http://127.0.0.1:8000 +
+ ) + )} +
+ + {/* 右侧边栏自选股列表 & 公司档案 */} + +
+
+ ); +} + +export default App; diff --git a/external/Quant.ai/frontend/src/assets/hero.png b/external/Quant.ai/frontend/src/assets/hero.png new file mode 100644 index 0000000000000000000000000000000000000000..9b398ea2e359990a6a52f6d4c5efb8d7cb3f51ca --- /dev/null +++ b/external/Quant.ai/frontend/src/assets/hero.png @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:881ffbcaafc212e49addad08846a5b82761355fa20624253af3477ba33262c5c +size 13057 diff --git a/external/Quant.ai/frontend/src/assets/react.svg b/external/Quant.ai/frontend/src/assets/react.svg new file mode 100644 index 0000000000000000000000000000000000000000..6c87de9bb3358469122cc991d5cf578927246184 --- /dev/null +++ b/external/Quant.ai/frontend/src/assets/react.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/external/Quant.ai/frontend/src/assets/vite.svg b/external/Quant.ai/frontend/src/assets/vite.svg new file mode 100644 index 0000000000000000000000000000000000000000..5101b674df391399da71c767aa5c976426c9dc7a --- /dev/null +++ b/external/Quant.ai/frontend/src/assets/vite.svg @@ -0,0 +1 @@ +Vite diff --git a/external/Quant.ai/frontend/src/components/BrokerPanel.tsx b/external/Quant.ai/frontend/src/components/BrokerPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..5f5f1b5adca702805d2203015da885ba346c332e --- /dev/null +++ b/external/Quant.ai/frontend/src/components/BrokerPanel.tsx @@ -0,0 +1,404 @@ +// frontend/src/components/BrokerPanel.tsx + +import React, { useState, useEffect } from 'react'; + +interface AccountSummary { + success: boolean; + account_number: string; + status: string; + cash: number; + portfolio_value: number; + buying_power: number; + equity: number; +} + +interface BrokerPosition { + ticker: string; + shares: number; + avg_entry_price: number; + market_value: number; + current_price: number; + unrealized_pnl: number; + unrealized_pnl_pct: number; +} + +export function BrokerPanel() { + const [account, setAccount] = useState(null); + const [positions, setPositions] = useState([]); + const [isBotRunning, setIsBotRunning] = useState(false); + const [logs, setLogs] = useState([]); + const [loading, setLoading] = useState(true); + const [actionLoading, setActionLoading] = useState(null); + const [errorMsg, setErrorMsg] = useState(null); + + // Poll status, account, and positions + const fetchBrokerData = async () => { + try { + // 1. Fetch account stats + const accRes = await fetch('http://127.0.0.1:8000/api/broker/account'); + const accJson = await accRes.json(); + if (accJson.success !== false) { + setAccount(accJson); + setErrorMsg(null); + } else { + setErrorMsg(accJson.error || "无法获取 Alpaca 账户信息,请检查 Keys 配置。"); + } + + // 2. Fetch positions + const posRes = await fetch('http://127.0.0.1:8000/api/broker/positions'); + const posJson = await posRes.json(); + if (posJson.success) { + setPositions(posJson.positions); + } + + // 3. Fetch bot status and logs + const statusRes = await fetch('http://127.0.0.1:8000/api/live/status'); + const statusJson = await statusRes.json(); + if (statusJson.success) { + setIsBotRunning(statusJson.status.is_running); + setLogs(statusJson.logs); + } + + } catch (e) { + console.error("Error fetching broker data:", e); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchBrokerData(); + const interval = setInterval(fetchBrokerData, 3000); // Poll every 3 seconds + return () => clearInterval(interval); + }, []); + + const handleStartBot = async () => { + setActionLoading("start"); + try { + const res = await fetch('http://127.0.0.1:8000/api/live/start', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ ignore_market_hours: true }) + }); + const json = await res.json(); + if (json.success) { + setIsBotRunning(json.status.is_running); + setLogs(json.logs || []); + } else { + alert("启动失败: " + (json.status?.logs?.[json.status.logs.length - 1] || "错误。")); + } + } catch (e) { + alert("请求失败"); + } finally { + setActionLoading(null); + fetchBrokerData(); + } + }; + + const handleStopBot = async () => { + setActionLoading("stop"); + try { + const res = await fetch('http://127.0.0.1:8000/api/live/stop', { method: 'POST' }); + const json = await res.json(); + setIsBotRunning(json.status.is_running); + } catch (e) { + alert("请求失败"); + } finally { + setActionLoading(null); + fetchBrokerData(); + } + }; + + const handleCancelAllOrders = async () => { + if (!window.confirm("确定要撤销 Alpaca 账户中的所有未成交挂单吗?")) return; + setActionLoading("cancel_orders"); + try { + const res = await fetch('http://127.0.0.1:8000/api/broker/cancel_orders', { method: 'POST' }); + const json = await res.json(); + alert(json.message || "撤单请求已发送"); + } catch (e) { + alert("撤单失败"); + } finally { + setActionLoading(null); + fetchBrokerData(); + } + }; + + const handleForceLiquidate = async () => { + if (!window.confirm("🚨 警告:这会以市价立即平仓所有股票持仓!确定继续吗?")) return; + setActionLoading("liquidate"); + try { + const res = await fetch('http://127.0.0.1:8000/api/broker/close_positions', { method: 'POST' }); + const json = await res.json(); + alert(json.message || "清仓请求已发送"); + } catch (e) { + alert("平仓失败"); + } finally { + setActionLoading(null); + fetchBrokerData(); + } + }; + + // Extract key action events for clean visual feed + const getActionFeeds = () => { + const actionLogs = logs.filter(l => + l.includes('触发买入') || l.includes('触发卖出') || l.includes('买单提交') || l.includes('平仓单提交') || l.includes('开始新一轮') + ); + return actionLogs.slice(-6).reverse(); // Latest 6 events + }; + + const actionFeeds = getActionFeeds(); + + if (loading && !account) { + return ( +
+ 正在连接 Alpaca 账户... +
+ ); + } + + if (errorMsg) { + return ( +
+

🔌 Alpaca 账户未连接

+

{errorMsg}

+
+ 请在配置文件 backend/.env 中添加您的 Alpaca API Key。 +
+
+ ); + } + + return ( +
+ {/* 顶部一键托管大操作卡片 */} +
+
+
+
+

+ {isBotRunning ? '⚡ AI 量化托管交易中' : '⏸️ 托管交易已暂停'} +

+
+

+ {isBotRunning + ? '系统正在后台以 1分钟 频率高频评估行情,满足形态与突破信号时将直接提交订单至您的 Alpaca 账户。' + : '点击右侧按钮启动 AI 托管。开启后无需手动干预,全自动执行买卖与动态风控。'} +

+
+ +
+ {!isBotRunning ? ( + + ) : ( + + )} +
+
+ + {/* 极简资产大字报 */} + {account && ( +
+
+ 总资产净值 (Equity) + + ${account.equity.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} + +
+
+ 可用现金 (Cash) + + ${account.cash.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} + +
+
+ 持仓证券总额 + + ${(account.equity - account.cash).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} + +
+
+ 可用购买力 (4x Power) + + ${account.buying_power.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })} + +
+
+ )} + + {/* 持仓卡片 + 交易动态卡片 */} +
+ + {/* Alpaca 持仓大盘 */} +
+
+

+ 📋 Alpaca 账户当前持仓 (Live Positions) +

+ + 模拟盘账号: {account?.account_number} + +
+ + {positions.length === 0 ? ( +
+ 目前保持空仓防守中。当机器人检测到突破买入信号时,会自动建立仓位并在此展示。 +
+ ) : ( + + + + + + + + + + + + {positions.map((pos) => { + const isUp = pos.unrealized_pnl >= 0; + return ( + + + + + + + + ); + })} + +
代码持股数建仓均价最新现价浮动盈亏
{pos.ticker}{pos.shares} 股${pos.avg_entry_price.toFixed(2)}${pos.current_price.toFixed(2)} + {isUp ? '+' : ''}${pos.unrealized_pnl.toFixed(2)} ({isUp ? '+' : ''}{pos.unrealized_pnl_pct.toFixed(2)}%) +
+ )} +
+ + {/* 极简最新交易买卖动态 (Feed) */} +
+
+

+ ⚡ 机器人最新买卖动态 (Action Feed) +

+ + {actionFeeds.length === 0 ? ( +
+ 启动 AI 托管后,最新的买卖通知卡片将在此实时呈现。 +
+ ) : ( +
+ {actionFeeds.map((feed, idx) => ( +
+ {feed} +
+ ))} +
+ )} +
+ + {/* 底部应急操作按钮区 */} +
+ + +
+
+ +
+
+ ); +} diff --git a/external/Quant.ai/frontend/src/components/ChatPanel.tsx b/external/Quant.ai/frontend/src/components/ChatPanel.tsx new file mode 100644 index 0000000000000000000000000000000000000000..b1ea732c573549007d5232380cd3503377745b17 --- /dev/null +++ b/external/Quant.ai/frontend/src/components/ChatPanel.tsx @@ -0,0 +1,302 @@ +// frontend/src/components/ChatPanel.tsx + +import React, { useState, useRef, useEffect } from 'react'; + +interface ChatMessage { + id: string; + role: 'user' | 'assistant' | 'system'; + content: string; + timestamp: Date; + strategyConfig?: Record; + executionPlan?: Array<{ step: number; tool: string; desc: string }>; + riskReport?: RiskReport | null; +} + +interface RiskReport { + ticker: string; + strategy: string; + interval: string; + risk_score: number; + sections: Array<{ + title: string; + icon: string; + insights: string[]; + severity: string; + }>; +} + +interface ChatPanelProps { + onRunBacktest: (config: Record) => void; + isLoading: boolean; + activeTicker: string; +} + +const EXAMPLE_PROMPTS = [ + "Backtest TSLA with dynamic routing strategy on daily bars", + "Test NVDA with EMA crossover on 5-minute bars, ATR stop 1.5x", + "Run mean reversion on SPY with RSI oversold at 10", + "用日线回测 AAPL 的突破策略,ATR 止损 2.5 倍", + "Compare Donchian breakout on AMD with 2x ATR trailing stop", +]; + +export const ChatPanel: React.FC = ({ onRunBacktest, isLoading, activeTicker }) => { + const [messages, setMessages] = useState([ + { + id: 'welcome', + role: 'system', + content: `Welcome to Quant.ai Research Agent. Describe your trading research in natural language — I'll parse it into a strategy config, run the backtest, and generate a risk analysis report.\n\nTry: "Backtest TSLA with dynamic routing strategy on daily bars"`, + timestamp: new Date() + } + ]); + const [input, setInput] = useState(''); + const [reportLoading, setReportLoading] = useState(false); + const messagesEndRef = useRef(null); + + useEffect(() => { + messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); + }, [messages]); + + const handleSend = async () => { + const trimmed = input.trim(); + if (!trimmed || isLoading) return; + + const userMsg: ChatMessage = { + id: Date.now().toString(), + role: 'user', + content: trimmed, + timestamp: new Date() + }; + setMessages(prev => [...prev, userMsg]); + setInput(''); + + try { + // Step 1: Parse prompt → strategy config + const parseRes = await fetch('http://127.0.0.1:8000/api/agent/research', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify({ prompt: trimmed }) + }); + const parseData = await parseRes.json(); + + if (!parseData.success) { + setMessages(prev => [...prev, { + id: Date.now().toString(), + role: 'assistant', + content: `❌ Failed to parse: ${parseData.error}`, + timestamp: new Date() + }]); + return; + } + + const config = parseData.strategy_config; + const plan = parseData.execution_plan; + + // Step 2: Show parsed config and plan + const configMsg: ChatMessage = { + id: (Date.now() + 1).toString(), + role: 'assistant', + content: `**${parseData.parsed_intent}**\n\nI've parsed your request into the following configuration. Click "Run Backtest" to execute, or modify the parameters in the settings panel.`, + timestamp: new Date(), + strategyConfig: config, + executionPlan: plan + }; + setMessages(prev => [...prev, configMsg]); + + // Step 3: Auto-run backtest + onRunBacktest(config); + + // Step 4: Generate risk report + setReportLoading(true); + try { + const reportRes = await fetch('http://127.0.0.1:8000/api/report/generate', { + method: 'POST', + headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(config) + }); + const reportData = await reportRes.json(); + + if (reportData.success && reportData.report) { + const reportMsg: ChatMessage = { + id: (Date.now() + 2).toString(), + role: 'assistant', + content: '', + timestamp: new Date(), + riskReport: reportData.report + }; + setMessages(prev => [...prev, reportMsg]); + } + } catch { + // Risk report is optional — backtest still succeeded + } finally { + setReportLoading(false); + } + + } catch (e) { + setMessages(prev => [...prev, { + id: Date.now().toString(), + role: 'assistant', + content: `❌ Connection failed: ${e}. Make sure the backend is running on http://127.0.0.1:8000`, + timestamp: new Date() + }]); + } + }; + + const handleKeyDown = (e: React.KeyboardEvent) => { + if (e.key === 'Enter' && !e.shiftKey) { + e.preventDefault(); + handleSend(); + } + }; + + const renderRiskScore = (score: number) => { + const color = score >= 70 ? 'var(--color-green)' : score >= 40 ? '#f5a623' : 'var(--color-red)'; + const label = score >= 70 ? 'Low Risk' : score >= 40 ? 'Moderate Risk' : 'High Risk'; + return ( +
+
{score}
+
{label}
+
+ ); + }; + + return ( +
+
+
+ 🤖 + AI Research Agent +
+ {isLoading || reportLoading ? '● Analyzing...' : '● Ready'} +
+ +
+ {messages.map(msg => ( +
+ {msg.role === 'user' && ( +
+ {msg.content} +
+ )} + {msg.role === 'system' && ( +
+ {msg.content.split('\n').map((line, i) => ( + {line}
+ ))} +
+ )} + {msg.role === 'assistant' && ( +
+ {msg.content && msg.content.split('\n').map((line, i) => ( + + {line.startsWith('**') && line.endsWith('**') + ? {line.replace(/\*\*/g, '')} + : line} +
+
+ ))} + + {msg.strategyConfig && ( +
+
📋 Strategy Configuration
+
+ {Object.entries(msg.strategyConfig).map(([key, val]) => ( +
+ {key} + {String(val)} +
+ ))} +
+
+ )} + + {msg.executionPlan && ( +
+
🔧 Execution Plan
+ {msg.executionPlan.map(step => ( +
+ {step.step} +
+ {step.tool} + {step.desc} +
+
+ ))} +
+ )} + + {msg.riskReport && ( +
+
+
📊 AI Risk Analysis Report
+ {renderRiskScore(msg.riskReport.risk_score)} +
+ {msg.riskReport.sections.map((section, i) => ( +
+
+ {section.icon} {section.title} +
+
    + {section.insights.map((insight, j) => ( +
  • $1') + .replace(/`(.*?)`/g, '$1') + }} /> + ))} +
+
+ ))} +
+ )} +
+ )} +
+ ))} + {(isLoading || reportLoading) && ( +
+
+ + + +
+
+ )} +
+
+ + {/* Example prompts */} + {messages.length <= 1 && ( +
+ {EXAMPLE_PROMPTS.map((prompt, i) => ( + + ))} +
+ )} + +
+ +
-
- - + + +
@@ -951,6 +1083,224 @@ paramVal.innerText = val.toFixed(2); }); + // Tab Switchers + const tabChat = document.getElementById('tabChat'); + const tabPlugins = document.getElementById('tabPlugins'); + const chatTabContent = document.getElementById('chatTabContent'); + const pluginsTabContent = document.getElementById('pluginsTabContent'); + + tabChat.addEventListener('click', () => { + tabChat.classList.add('active'); + tabChat.style.borderBottomColor = 'var(--accent-violet)'; + tabChat.style.color = 'var(--text-primary)'; + + tabPlugins.classList.remove('active'); + tabPlugins.style.borderBottomColor = 'transparent'; + tabPlugins.style.color = 'var(--text-secondary)'; + + chatTabContent.style.display = 'flex'; + pluginsTabContent.style.display = 'none'; + }); + + tabPlugins.addEventListener('click', () => { + tabPlugins.classList.add('active'); + tabPlugins.style.borderBottomColor = 'var(--accent-violet)'; + tabPlugins.style.color = 'var(--text-primary)'; + + tabChat.classList.remove('active'); + tabChat.style.borderBottomColor = 'transparent'; + tabChat.style.color = 'var(--text-secondary)'; + + chatTabContent.style.display = 'none'; + pluginsTabContent.style.display = 'flex'; + }); + + // OCR Submit Handler + const ocrSubmit = document.getElementById('ocrSubmit'); + ocrSubmit.addEventListener('click', async () => { + const fileInput = document.getElementById('ocrFile'); + const langSelect = document.getElementById('ocrLang'); + const resultContainer = document.getElementById('ocrResultContainer'); + const resultPre = document.getElementById('ocrResult'); + const metaSpan = document.getElementById('ocrMeta'); + + if (!fileInput.files.length) { + alert("Please select an image file first."); + return; + } + + ocrSubmit.innerText = "Processing..."; + ocrSubmit.disabled = true; + resultContainer.style.display = 'none'; + + const formData = new FormData(); + formData.append("image", fileInput.files[0]); + formData.append("language", langSelect.value); + + try { + resetPipeline(); + activateStep('stepInput', 'success'); + activateStep('stepCache', 'active'); + + const authHeader = `sk-inferroute-demo`; + const userKey = apiKeyInput.value.trim() || authHeader; + + const res = await fetch('/v1/plugins/ocr', { + method: 'POST', + headers: { 'Authorization': `Bearer ${userKey}` }, + body: formData + }); + + if (!res.ok) { + const errorMsg = await res.text(); + throw new Error(errorMsg || "OCR server error"); + } + + const data = await res.json(); + resultContainer.style.display = 'flex'; + resultPre.innerText = data.extracted_text; + metaSpan.innerText = `⏱️ ${data.latency_ms} ms | Cost: $${data.estimated_cost_usd.toFixed(5)}`; + + activateStep('stepCache', 'success', 'Bypassed Cache'); + activateStep('stepLimit', 'success'); + activateStep('stepExecute', 'success', 'Gemini Multi-Modal Done'); + activateStep('stepValidate', 'success'); + activateStep('stepCascade', 'success', 'OCR Completed'); + + sessionTotalRequests++; + updateDashboardUI(data.latency_ms, data.latency_ms, false, 'gemini-1.5-flash'); + setTimeout(fetchWalletBalance, 500); + + } catch (err) { + alert("OCR Failed: " + err.message); + } finally { + ocrSubmit.innerText = "Extract Text"; + ocrSubmit.disabled = false; + } + }); + + // Summarize Handler + const summarizeSubmit = document.getElementById('summarizeSubmit'); + summarizeSubmit.addEventListener('click', async () => { + const textVal = document.getElementById('summarizeText').value.trim(); + const maxWords = document.getElementById('summarizeMax').value; + const resultContainer = document.getElementById('summarizeResultContainer'); + const resultDiv = document.getElementById('summarizeResult'); + const metaSpan = document.getElementById('summarizeMeta'); + + if (!textVal) { + alert("Please enter some text to summarize."); + return; + } + + summarizeSubmit.innerText = "Summarizing..."; + summarizeSubmit.disabled = true; + resultContainer.style.display = 'none'; + + const formData = new FormData(); + formData.append("text", textVal); + formData.append("max_length", maxWords); + + try { + resetPipeline(); + activateStep('stepInput', 'success'); + activateStep('stepCache', 'active'); + + const authHeader = `sk-inferroute-demo`; + const userKey = apiKeyInput.value.trim() || authHeader; + + const res = await fetch('/v1/plugins/summarize', { + method: 'POST', + headers: { 'Authorization': `Bearer ${userKey}` }, + body: formData + }); + + if (!res.ok) throw new Error("Summarization failed"); + + const data = await res.json(); + resultContainer.style.display = 'flex'; + resultDiv.innerText = data.summary; + metaSpan.innerText = `⏱️ ${data.latency_ms} ms | Cost: $${data.estimated_cost_usd.toFixed(5)}`; + + activateStep('stepCache', 'success'); + activateStep('stepLimit', 'success'); + activateStep('stepExecute', 'success', 'Gemini Summarized'); + activateStep('stepValidate', 'success'); + activateStep('stepCascade', 'success'); + + sessionTotalRequests++; + updateDashboardUI(data.latency_ms, data.latency_ms, false, 'gemini-1.5-flash'); + setTimeout(fetchWalletBalance, 500); + + } catch (err) { + alert("Summarization failed: " + err.message); + } finally { + summarizeSubmit.innerText = "Generate Summary"; + summarizeSubmit.disabled = false; + } + }); + + // Translate Handler + const translateSubmit = document.getElementById('translateSubmit'); + translateSubmit.addEventListener('click', async () => { + const textVal = document.getElementById('translateText').value.trim(); + const targetLang = document.getElementById('translateLang').value; + const resultContainer = document.getElementById('translateResultContainer'); + const resultDiv = document.getElementById('translateResult'); + const metaSpan = document.getElementById('translateMeta'); + + if (!textVal) { + alert("Please enter text to translate."); + return; + } + + translateSubmit.innerText = "Translating..."; + translateSubmit.disabled = true; + resultContainer.style.display = 'none'; + + const formData = new FormData(); + formData.append("text", textVal); + formData.append("target_lang", targetLang); + + try { + resetPipeline(); + activateStep('stepInput', 'success'); + activateStep('stepCache', 'active'); + + const authHeader = `sk-inferroute-demo`; + const userKey = apiKeyInput.value.trim() || authHeader; + + const res = await fetch('/v1/plugins/translate', { + method: 'POST', + headers: { 'Authorization': `Bearer ${userKey}` }, + body: formData + }); + + if (!res.ok) throw new Error("Translation failed"); + + const data = await res.json(); + resultContainer.style.display = 'flex'; + resultDiv.innerText = data.translated_text; + metaSpan.innerText = `⏱️ ${data.latency_ms} ms | Cost: $${data.estimated_cost_usd.toFixed(5)}`; + + activateStep('stepCache', 'success'); + activateStep('stepLimit', 'success'); + activateStep('stepExecute', 'success', 'Gemini Translated'); + activateStep('stepValidate', 'success'); + activateStep('stepCascade', 'success'); + + sessionTotalRequests++; + updateDashboardUI(data.latency_ms, data.latency_ms, false, 'gemini-1.5-flash'); + setTimeout(fetchWalletBalance, 500); + + } catch (err) { + alert("Translation failed: " + err.message); + } finally { + translateSubmit.innerText = "Translate"; + translateSubmit.disabled = false; + } + }); + // Event hooks sendBtn.addEventListener('click', sendMessage); document.getElementById('rechargeBtn').addEventListener('click', rechargeWallet); diff --git a/requirements.txt b/requirements.txt index ebcb4e9bd11bfef9ebe9845941bf66defe0a595f..86eb97f34779b49d437fbc999a8c9af9d2642578 100644 --- a/requirements.txt +++ b/requirements.txt @@ -20,4 +20,6 @@ pytest>=8.2.2 pytest-asyncio>=0.23.7 locust>=2.28.0 aiosqlite>=0.20.0 +python-multipart>=0.0.9 + diff --git a/tests/test_plugins.py b/tests/test_plugins.py new file mode 100644 index 0000000000000000000000000000000000000000..fdd7ed8ce2aac413bdebb998df3cf2a2d4f5f7b9 --- /dev/null +++ b/tests/test_plugins.py @@ -0,0 +1,47 @@ +import pytest +from fastapi.testclient import TestClient +from inferroute.main import app + +client = TestClient(app) + +def test_plugin_summarize_mock(): + # Test text summarization in mock mode + response = client.post( + "/v1/plugins/summarize", + data={"text": "This is a long test text that we want to summarize using our smart router.", "max_length": 150}, + headers={"Authorization": "Bearer sk-inferroute-demo"} + ) + assert response.status_code == 200 + data = response.json() + assert data["success"] is True + assert data["plugin"] == "summarize" + assert "summary" in data + +def test_plugin_translate_mock(): + # Test translation in mock mode + response = client.post( + "/v1/plugins/translate", + data={"text": "Hello world", "target_lang": "Chinese"}, + headers={"Authorization": "Bearer sk-inferroute-demo"} + ) + assert response.status_code == 200 + data = response.json() + assert data["success"] is True + assert data["plugin"] == "translate" + assert "translated_text" in data + +def test_plugin_ocr_mock(): + # Test OCR plugin with a mock file upload + import io + file_data = b"fake-image-bytes" + response = client.post( + "/v1/plugins/ocr", + files={"image": ("test.png", io.BytesIO(file_data), "image/png")}, + data={"language": "auto"}, + headers={"Authorization": "Bearer sk-inferroute-demo"} + ) + assert response.status_code == 200 + data = response.json() + assert data["success"] is True + assert data["plugin"] == "ocr" + assert "extracted_text" in data diff --git a/tests/test_quant_plugin.py b/tests/test_quant_plugin.py new file mode 100644 index 0000000000000000000000000000000000000000..64f1e6890664e248dad531394ccf8fd55d44280e --- /dev/null +++ b/tests/test_quant_plugin.py @@ -0,0 +1,69 @@ +""" +Unit tests for InferRoute Quant.ai and Paper Reader plugins. +""" +import pytest +from fastapi.testclient import TestClient +from inferroute.main import app + +client = TestClient(app) + +def test_quant_analyze_endpoint(): + payload = { + "ticker": "AAPL", + "timeframe": "daily", + "technical_indicators": {"RSI": 65.0, "MACD": "bullish"} + } + response = client.post( + "/v1/plugins/quant/analyze", + json=payload, + headers={"Authorization": "Bearer sk-inferroute-demo"} + ) + assert response.status_code == 200 + data = response.json() + assert data["success"] is True + assert data["plugin"] == "quant_analyze" + assert data["ticker"] == "AAPL" + assert "bullish_score" in data + + +def test_quant_news_sentiment_endpoint(): + payload = { + "text": "Apple announced record quarterly revenue exceeding analyst expectations.", + "company_context": "Apple Inc." + } + response = client.post( + "/v1/plugins/quant/news-sentiment", + json=payload, + headers={"Authorization": "Bearer sk-inferroute-demo"} + ) + assert response.status_code == 200 + data = response.json() + assert data["success"] is True + assert data["plugin"] == "quant_news_sentiment" + assert "sentiment_score" in data + + +def test_paper_summarize_endpoint(): + payload = { + "title": "ROUTERBENCH", + "paper_text": "This paper formalizes multi-LLM routing as a multi-objective optimization problem." + } + response = client.post( + "/v1/plugins/paper/summarize", + json=payload, + headers={"Authorization": "Bearer sk-inferroute-demo"} + ) + assert response.status_code == 200 + data = response.json() + assert data["success"] is True + assert data["plugin"] == "paper_summarize" + assert "summary" in data + + +def test_analytics_summary_endpoint(): + response = client.get("/v1/analytics/summary") + assert response.status_code == 200 + data = response.json() + assert "total_requests" in data + assert "total_cost_saved_usd" in data + assert "circuit_breakers" in data