RussellFeinstein/WoW-Economy-Forecaster

GitHub: RussellFeinstein/WoW-Economy-Forecaster

一个基于 LightGBM 与原型迁移学习的本地机器学习系统,用于预测《魔兽世界》拍卖行的物品价格与市场波动趋势。

Stars: 0 | Forks: 0

# WoW 经济预测器 [![CI](https://static.pigsec.cn/wp-content/uploads/repos/cas/ad/ad5834178f7599af9fdda11629d49cae07f2997beec49821b2920eff5bfd50e7.svg)](https://github.com/RussellFeinstein/WoW-Economy-Forecaster/actions/workflows/ci.yml) ![Python 3.11+](https://img.shields.io/badge/python-3.11%2B-blue) ![测试](https://img.shields.io/badge/tests-1%2C200%2B%20passing-brightgreen) ![许可证](https://img.shields.io/badge/license-personal%20research-orange) 一个用于《魔兽世界》拍卖行经济研究的**本地优先 ML 预测系统**。 使用来自**地心之战 (TWW)** 的历史数据来学习经济模式,然后应用基于类别/原型的迁移学习,为即将上线和成熟期的**午夜 (Midnight)** 生成价格、波动率和销售速度预测。 ## 关键技术亮点 - **基于原型的迁移学习** — 经济行为原型(而非物品 ID)支持跨资料片预测,能够对从未见过的物品进行首日预测 - **带有无泄漏事件处理的步进式回测** — `WoWEvent.is_known_at()` 可防止前瞻偏差 - **5 组件推荐评分** — opportunity、liquidity、volatility、event_boost、uncertainty,具备原则性阈值 - **自适应置信区间** — 当市场条件发生变化时,漂移检测会扩大 CI;冷启动混合将预测锚定在源资料片价格上 - **生产级 pipeline** — 36 个 CLI 命令、21 个 SQLite 表、1,200 多个测试、每小时自动化 ## 架构 ``` graph LR A[Blizzard API] -->|OAuth2| B[Ingest + Normalize] B --> C[Feature Engineering
48 features] C --> D[LightGBM Training
1d / 7d / 28d] D --> E[Forecast + CI] E --> F[Recommendation
Scoring] F --> G[Streamlit Dashboard
8 tabs] F --> H[CLI Reports] F --> I[Power BI / Tableau
Star Schema Export] B --> J[Drift Detection] J -->|Widens CI| E F --> K[Portfolio Charts
matplotlib + Plotly] ``` ## 项目状态 **生产就绪的 pipeline** | 层级 | 版本 | 状态 | |---|---|---| | v0.1.0 — 脚手架 | 模型、分类法、schema、CLI 接口 | 完成 | | v0.2.0 — 接入 | BlizzardClient(实时 OAuth2)、快照写入器、物品引导程序 | 完成 | | v0.3.0 — 特征 | 48 列训练 Parquet、lag/rolling/event/archetype 特征 | 完成 | | v0.4.0 — 回测 | 步进式回测、4 个基线模型、CSV/DB 结果 | 完成 | | v0.5.0 — ML + 推荐 | LightGBM 预测器、5 组件评分、买入/卖出/持有排名 | 完成 | | v0.6.0 — 监控 | 漂移检测、自适应 CI、溯源、每小时编排 | 完成 | | v0.7.0 — 报告 | CLI 报告命令、导出层、可选的 Streamlit 仪表板 | 完成 | | v0.8.0 — 来源治理 | 来源策略、预检、新鲜度验证 | 完成 | | v0.9.0 — 种子事件 | 28 个 TWW 种子事件、类别级别影响记录 | 完成 | | v1.0.0 — 自动化 | 调度守护进程、Windows Task Scheduler 集成 | 完成 | | v1.1.0 — 归一化 | 滚动 z-score 归一化,带冷启动回退 | 完成 | | v1.5.0 — 制造顾问 | 配方种子生成器、利润压缩/扩张、6 窗口时间分析 | 完成 | | v2.0.0 — 执行层 | TSM 导出、check-data-health、每小时退出代码 | 完成 | | v2.2.0 — 投资组合展示 | 可视化层、BI 导出、Jupyter 笔记本、CI pipeline | 完成 | ## 架构概述 ``` wow_forecaster/ ├── taxonomy/ # Pure enums: EventType, ArchetypeCategory, ArchetypeTag ├── models/ # Pydantic v2 domain models (frozen/immutable value objects) ├── db/ # SQLite: connection, schema DDL (21 tables), migrations, repos ├── pipeline/ # 7 stages: ingest, normalize, feature_build, train, │ # forecast, recommend, orchestrator (backtest separate) ├── ingestion/ # Blizzard live client, snapshot writer, item bootstrapper, │ # auctionator importer (backfill), cloud fetcher (GitHub Actions) ├── features/ # Daily agg, lag/rolling, event features, archetype features, │ # dataset builder → 48-col training / 45-col inference Parquet ├── backtest/ # Walk-forward splits, baseline models, metrics, reporter ├── ml/ # LightGBM: feature selector (37 cols), trainer, predictor ├── recipes/ # Blizzard recipe client, seeder, repo, margin calculator ├── recommendations/ # Scorer (5-component formula), ranker, reporter (CSV/JSON) │ # crafting_advisor: 6-window margin compression/expansion ├── monitoring/ # Drift detection, adaptive policy, health, provenance, reporter ├── reporting/ # Reader (file discovery + freshness), formatters (ASCII tables), │ # export (flat CSV/JSON for Power BI), BI star-schema export ├── governance/ # Source policy registry, preflight checks, freshness validation ├── viz/ # Publication-quality charts (matplotlib/seaborn/Plotly) │ ├── theme.py # WoW dark palette, apply_wow_theme(), Plotly template │ ├── data_queries.py # SQL/file -> pandas DataFrame fetchers │ └── charts/ # 6 chart modules: forecast, backtest, feature, recommendation, drift, transfer ├── scheduler.py # SchedulerDaemon (stdlib only) — hourly + daily automation └── cli.py # Typer CLI: 36 commands config/ ├── default.toml # Static defaults (committed) ├── sources.toml # 3 active source policies (blizzard_api, blizzard_news, auctionator) └── events/ ├── tww_events.json # 28 TWW seed events └── tww_event_impacts.json # 56 category-level impact records data/ ├── raw/snapshots/ # Hourly ingestion snapshots (JSON, gitignored) │ ├── blizzard_api/YYYY/MM/DD/realm_{realm}_{ts}Z.json │ ├── blizzard_news/YYYY/MM/DD/news_{ts}Z.json ├── processed/features/ # Training + inference Parquet + manifests ├── outputs/forecasts/ # forecast_{realm}_{date}.csv ├── outputs/recommendations/ # recommendations_{realm}_{date}.csv/.json ├── outputs/model_artifacts/ # LightGBM .pkl + .json artifacts ├── outputs/monitoring/ # drift_status, model_health, provenance JSON ├── outputs/backtest/ # Per-horizon backtest CSV + manifest ├── db/ # wow_forecaster.db (SQLite) └── logs/ # forecaster.log dashboard/ # Optional Streamlit analysis UI ├── app.py # 8-tab dashboard (Top Picks/Forecasts/Volatility/Health/ │ # Status/Backtest/Feature Insights/Crafting) └── data_loader.py # Cached file loaders + DB queries notebooks/ # Jupyter analysis notebooks (portfolio narratives) ├── 01_eda_and_data_exploration.ipynb ├── 02_model_development.ipynb └── 03_backtest_and_evaluation.ipynb scripts/ ├── run_daily.bat # Daily pipeline wrapper (freshness gate + build + forecast) ├── run_healthcheck.bat # Scheduled health check + failure alerting ├── run_hourly.bat # Hourly refresh wrapper (stale-lock takeover guard) └── setup_tasks.bat # One-shot Windows Task Scheduler registration tests/ ├── test_backtest/ # Splits, models, metrics (60 tests) ├── test_cli/ # CLI smoke tests (54 tests) ├── test_db/ # Schema + repositories + migrations (37 tests) ├── test_events/ # Seed loader, event imports (24 tests) ├── test_features/ # Feature engineering, no-leakage (81 tests) ├── test_governance/ # Source policies, preflight, freshness (84 tests) ├── test_ingestion/ # Snapshots, event CSV, persistence (73 tests) ├── test_ml/ # Feature selector, LightGBM (44 tests) ├── test_models/ # Pydantic validation (61 tests) ├── test_monitoring/ # Drift, adaptive, orchestrator (73 tests) ├── test_pipeline/ # Pipeline interfaces, normalize (36 tests) ├── test_recipes/ # Recipe repo, seeder, margin calculator (21 tests) ├── test_recommendations/ # Scorer, ranker, item overlay, crafting (133 tests) ├── test_reporting/ # Reader, formatters, export (86 tests) ├── test_scheduler/ # Scheduler daemon (26 tests) ├── test_scripts/ # Bat wrappers: hourly lock guard, daily gate, health alerting, Windows-only (17 tests) └── test_taxonomy/ # Taxonomy integrity (30 tests) ``` ### 关键设计决策 | 关注点 | 选择 | 原因 | |---|---|---| | 数据模型 | **Pydantic v2** (frozen) | 运行时验证、不可变值对象、清晰的序列化 | | 数据库 | **原生 sqlite3** (无 ORM) | 单进程本地工具;保持 SQL 的直观性 | | CLI | **Typer** | 类型注解驱动、自动帮助、基于 Click 构建 | | 配置 | **tomllib + python-dotenv** | TOML 用于静态配置,.env 用于机密信息 | | ML | **LightGBM** | 训练快、处理混合类型、特征重要性可解释 | | HTTP | **httpx** | 支持异步,用于 Blizzard OAuth2 + API 调用 | | 报告 | **CLI 优先 + 可选 Streamlit** | 终端报告可在无头模式下运行;Streamlit 在不需要时零成本 | | 测试 | **pytest** | 标准工具;跨 20 个组的 1,000 多个测试 | ### 迁移学习架构 该系统**不会**进行简单的 TWW 物品 → Midnight 物品的映射。相反: 1. **原型分类法** (`wow_forecaster/taxonomy/archetype_taxonomy.py`) 定义了 36 个经济行为标签(例如 `consumable.flask.stat`、`mat.ore.common`)。 2. **TWW 物品**通过物品引导程序映射到这些原型。 3. **模型训练**基于来自 TWW 的原型级别时间序列。 4. **原型映射**(`archetype_mappings` 表)将每个 TWW 原型正式映射到其对应的 Midnight 等效项,并附带置信度分数和所需的根据。 5. 随着 **Midnight 数据不断积累**,将训练物品级模型,原型回退机制将逐渐被淘汰。 ### 事件感知预测 `WoWEvent.is_known_at(as_of: datetime)` 是防范前瞻偏差的卫士: - 如果 `announced_at is None`,则返回 `False`(保守默认值)。 - 如果 `as_of < announced_at`,则返回 `False`。 - 预测仅包含在预测时已公开知晓的事件。 ## 设置 ### 要求 - Python 3.11+ - Git - Blizzard API 凭据(Client ID + Client Secret) ### 安装 ``` git clone https://github.com/RussellFeinstein/WoW-Economy-Forecaster.git cd WoW-Economy-Forecaster python -m venv .venv .venv\Scripts\activate # Windows # source .venv/bin/activate # macOS / Linux pip install -e ".[dev]" ``` ### 初始设置流程 ``` # 1. Copy the env template and add your Blizzard API credentials cp .env.example .env # 2. Initialize the database (creates data/db/wow_forecaster.db) wow-forecaster init-db # 3. Validate your config wow-forecaster validate-config # 4. Fetch first commodity snapshot (required before item bootstrap) wow-forecaster run-hourly-refresh # 5. Seed item registry from Blizzard API (~2-5 min, ~9,950 items) wow-forecaster bootstrap-items # 6. Second refresh now inserts market observations (items table is populated) wow-forecaster run-hourly-refresh # 7. (Optional) Backfill 6-12 months of price history from Auctionator wow-forecaster import-auctionator # 8. Import TWW seed events (28 events) and build event features wow-forecaster import-events wow-forecaster build-events # 9. Build feature datasets (requires build-events first) wow-forecaster build-datasets ``` ## CLI 参考 ``` wow-forecaster --help wowfc --help # alias ``` ### 数据库与配置 ``` wow-forecaster init-db [--db-path PATH] [--config PATH] wow-forecaster validate-config [--config PATH] [--full] ``` ### 数据接入 ``` # Fetch live commodity AH snapshot from Blizzard API wow-forecaster run-hourly-refresh [--realm SLUG] [--check-drift/--no-check-drift] # Seed item registry from Blizzard Item API (~9,950 items; run once after first snapshot) wow-forecaster bootstrap-items [--concurrency N] [--db-path PATH] # Import TWW seed events into wow_events table wow-forecaster import-events [--file PATH] [--dry-run] # Backfill historical price history from Auctionator.lua SavedVariables wow-forecaster import-auctionator [--path PATH] [--realm SLUG] ``` ### 事件与特征数据集 ``` # Build event features: seeds events + impacts -> DB + Parquet (run before build-datasets) wow-forecaster build-events [--realm SLUG ...] [--start-date DATE] [--end-date DATE] # List events currently in the database wow-forecaster list-events [--limit N] [--expansion SLUG] # Build training + inference Parquet datasets (requires build-events first) wow-forecaster build-datasets [--realm SLUG ...] [--start-date DATE] [--end-date DATE] # Validate a dataset manifest wow-forecaster validate-datasets --manifest PATH [--strict] ``` ### 预测 Pipeline ``` # Full daily pipeline: train -> forecast -> recommend # Freshness gate: refuses to run when the newest observation is older than # 26 hours ([forecast] max_data_age_hours in config; 0 disables the gate) wow-forecaster run-daily-forecast [--realm SLUG] [--skip-train] [--skip-recommend] # Train only wow-forecaster train-model [--realm SLUG ...] # Forecast + recommend only (requires trained model) wow-forecaster recommend-top-items [--realm SLUG] [--top-n N] [--forecast-run-id ID] ``` ### 回测 ``` wow-forecaster backtest --start-date DATE --end-date DATE [--realm SLUG] \ [--window-days N] [--step-days N] [--horizons 1,3] wow-forecaster report-backtest [--realm SLUG] [--run-id ID] [--horizon N] ``` ### 监控 ``` wow-forecaster check-drift [--realm SLUG] [--output-json/--no-output-json] wow-forecaster evaluate-live-forecast [--realm SLUG] [--window-days N] ``` ### 报告 所有报告命令都会读取已经生成的输出文件——它们绝不会重新运行 pipeline。 每个报告都会打印一个 `[FRESH]` 或 `[STALE]` 横幅,以便您一眼就能判断数据的时效性。 ``` # Top-N buy/sell/hold recommendations per category wow-forecaster report-top-items [--realm SLUG] [--horizon 1d|7d|28d] [--expansion SLUG] [--export PATH] # Full forecast summary sorted by score wow-forecaster report-forecasts [--realm SLUG] [--horizon HORIZ] [--top-n N] [--export PATH] # Volatility watchlist: items with widest CI bands (highest uncertainty) wow-forecaster report-volatility [--realm SLUG] [--top-n N] [--export PATH] # Drift level + model health (retrain flag, MAE ratio per horizon) wow-forecaster report-drift [--realm SLUG] [--export PATH] # Source freshness: per-source snapshot counts, success rates, stale flags wow-forecaster report-status [--realm SLUG] [--export PATH] # LightGBM feature importance ranked by gain or split count wow-forecaster report-feature-importance [--realm SLUG] [--horizon 1d|7d|28d] \ [--top-n N] [--importance-type gain|split] \ [--export PATH] # DB-backed data collection health: coverage, gaps, freshness, plus a stale # hourly-lock check and a retention sentinel (oldest raw row vs the 30-day # ToS window). Exits 1 when any check fails. wow-forecaster check-data-health [--realm SLUG] [--lookback-days 14] \ [--stale-hours 4] ``` **所有报告命令的通用选项:** - `--freshness-hours N` — `[STALE]` 横幅的阈值(默认 4 小时)。 - `--export PATH` — 将扁平化的 CSV 或 JSON 写入 *PATH*,供 Power BI / Excel 使用。 ### 来源治理 ``` # List configured data sources and their enabled/disabled status wow-forecaster list-sources # Validate all source policies are internally consistent wow-forecaster validate-source-policies # Check freshness of each source's last successful snapshot wow-forecaster check-source-freshness [--realm SLUG] [--export PATH] # Delete raw API data older than retention window (Blizzard API ToS §2.r — 30-day TTL) wow-forecaster prune-snapshots [--days N] [--dry-run] ``` ### 制造利润顾问 ``` # Seed recipe data from Blizzard static API # Default: most recent expansion (transfer_target in config, currently "midnight") wow-forecaster seed-recipes [--expansion SLUG] [--all] [--professions SLUG,...] # Compute daily craft cost vs output price -> crafting_margin_snapshots wow-forecaster build-margins [--realm SLUG] [--days N] # Report top crafting opportunities with 6 temporal windows wow-forecaster report-crafting [--realm SLUG] [--top-n N] [--export PATH] # Recipe seeding status: counts by expansion+profession, reagent coverage, margin snapshot freshness wow-forecaster report-recipe-status [--expansion SLUG] # Export item buy signals as a TSM import string (paste into TradeSkillMaster) wow-forecaster export-tsm [--realm SLUG] [--horizon 1d|7d|28d] \ [--min-roi 0.10] [--output PATH] ``` **制造窗口**(使用现有的 1d/7d/28d 预测的所有有效的 买入 <= 卖出 组合): - `now -> now` — 今天制造并出售 - `now -> +7d` — 今天购买材料,下周出售 - `now -> +28d` — 今天购买材料,4 周后出售 - `+7d -> +7d` — 下周购买材料,下周出售 - `+7d -> +28d` — 下周购买材料,4 周后出售 - `+28d -> +28d` — 4 周后购买材料,届时出售 ### 自动化 ``` # Start foreground scheduler daemon (hourly refresh + daily forecast) wow-forecaster start-scheduler [--config PATH] # Register Windows Task Scheduler tasks for unattended operation # Tasks run silently (no visible cmd.exe window) via run_silent.vbs: # WoWForecaster-Hourly run_hourly.bat, hourly at :16 # WoWForecaster-Daily run_daily.bat, daily at 07:00 # WoWForecaster-HealthCheck run_healthcheck.bat, every 6h at :45 scripts/setup_tasks.bat ``` 锚定分钟数是经过精心设计的:每小时的 :16 避开了与日常任务的冲突以及 Blizzard 在整点的快照刷新,而健康检查的 :45 确保它避开数据接入,从而两者绝不会同时读取数据库。重新运行 setup_tasks.bat 是安全的:它会固定这些锚点,并保留操作员关闭的任何任务的 Disabled 状态。 日常任务根据数据新鲜度进行自我门控:run_daily.bat 首先运行 `check-data-health --stale-hours 26`,如果数据接入过时,则非零退出且不进行预测,因此 Task Scheduler 会记录失败,而不是默默地基于冻结的数据进行预测。Streamlit 仪表板在相同条件下,会在每个选项卡上显示红色的数据接入警报横幅。 独立的健康检查使失败变得不容错过,且无需电子邮件基础设施:`scripts/run_healthcheck.bat` 运行 `check-data-health --stale-hours 4`,将输出追加到 logs/health.log,并在失败时写入 `data/outputs/monitoring/health_alert.json` 并弹出一个持久的红色控制台窗口(每 24 小时最多一次)。健康的运行会清除警报。其退出代码与 check-data-health 保持一致,因此 Task Scheduler 的 Last Run Result 也充当持久的警报平台。setup_tasks.bat 将其注册为 WoWForecaster-HealthCheck 任务。 ### 云端快照捕获 (GitHub Actions) 不依赖于桌面机开启的每小时捕获。一个预定的 workflow ([.github/workflows/cloud-snapshot.yml](.github/workflows/cloud-snapshot.yml)) 获取 商品快照,将其 gzip 压缩(~59 MB 原始文件 -> ~2.2 MiB),并上传到私有的 兼容 S3 的存储桶 (Cloudflare R2),该存储桶的 30 天生命周期规则强制执行 Blizzard API ToS 的删除窗口。设计记录、测量的大小调整及故障模式详见: [docs/cloud-capture.md](docs/cloud-capture.md)。 一次性设置(仓库所有者): 1. 创建一个具有 30 天删除生命周期规则的私有 R2 存储桶,以及一个 限定于该存储桶并具有读写权限的 API token。 2. 添加仓库密钥:`BLIZZARD_CLIENT_ID`、`BLIZZARD_CLIENT_SECRET`、 `SNAPSHOT_S3_ENDPOINT`、`SNAPSHOT_S3_BUCKET`、`SNAPSHOT_S3_ACCESS_KEY_ID`、 `SNAPSHOT_S3_SECRET_ACCESS_KEY`。 3. 启用 workflow,它在密钥存在之前将保持禁用状态 (`gh workflow enable "Cloud snapshot capture"` 或通过 Actions 标签页), 手动触发首次运行 (Run workflow),并确认有一个约 2.2 MiB 的对象存入存储桶。 失败的运行会向仓库所有者发送电子邮件;健康的运行还会验证过去 24 小时的对象,如果缺少某些小时的数据则会明确报错。云端积压数据的本地追赶接入作为 issue #43 (`sync-snapshots`) 进行跟踪。 ## 主要工作流程 ``` run-hourly-refresh # Blizzard API ingest -> normalize -> drift -> provenance build-datasets # feature engineering -> Parquet (requires build-events first) run-daily-forecast # train -> forecast -> recommend ``` `import-auctionator` = 仅用于历史数据回填,持续的每小时操作不需要它。 ## 报告层 ### 报告的工作原理 `wow_forecaster/reporting/` 模块包含三个组件: | 模块 | 用途 | |---|---| | `reader.py` | 文件发现 (`find_latest_file`)、新鲜度检查 (`check_freshness`)、各种报告类型的加载器 | | `formatters.py` | ASCII 终端表格格式化器 — 无第三方依赖 | | `export.py` | 扁平化 CSV/JSON 导出助手;`flatten_recommendations_for_export()` 将嵌套的评分组件展开为 `sc_*` 列 | 文件发现机制会查找符合预期命名模式的**最近修改的**文件,因此当存在更新的文件时,绝不会默默使用前几天生成的报告。 ### 新鲜度与陈旧度 每个格式化器都会打印一个来源横幅: ``` [FRESH] Generated 1.2h ago [STALE] Generated 26.4h ago -- data may not reflect current market [AGE UNKNOWN] generated_at not available ``` ### 导出格式 `--export PATH.csv` 会写入不带嵌套字典的扁平化行数据,可直接用于 Power BI 或 pandas: - **推荐**:`realm_slug, generated_at, run_slug, category, rank, archetype_id, horizon, target_date, current_price, predicted_price, ci_lower, ci_upper, roi_pct, score, action, reasoning, sc_opportunity, sc_liquidity, sc_volatility, sc_event_boost, sc_uncertainty, model_slug` - **预测**:与预测 CSV 相同 + 派生列 `ci_width_gold`、`ci_pct_of_price` - **漂移**:原始 JSON 透传(用于编程式调用) ## 可选的 Streamlit 仪表板 `dashboard/` 目录包含一个可选的本地分析 UI,它读取与 CLI 命令相同的 `data/outputs/` 文件。 ``` pip install -e ".[dashboard]" streamlit run dashboard/app.py # Override default realm: streamlit run dashboard/app.py -- --realm area-52 ``` **五个选项卡:** | 选项卡 | 内容 | 数据来源 | |---|---|---| | 精选推荐 (Top Picks) | 每个类别的排名推荐、评分明细、类别/时间范围过滤器 | `recommendations_{realm}_{date}.json` | | 预测 | 带有 CI 宽度的完整预测表;包含历史价格折线和预测覆盖层的原型选择器 | `forecast_{realm}_{date}.csv` + SQLite | | 波动率 | 按 CI 宽度排序的物品,CI% 条形图 | `forecast_{realm}_{date}.csv` | | 模健康 | 漂移级别、不确定性乘数、每个时间范围的 MAE 比率、重新训练标志 | `drift_status_*.json` + `model_health_*.json` | | 来源状态 | 各来源的快照计数、成功率、数据新鲜度与报告生成时间的对比 | `provenance_{realm}_{date}.json` | 新鲜度徽章:每个选项卡都会显示一个绿色/橙色/红色徽章(`FRESH` / `STALE` / `NO DATA`)。阈值可在侧边栏中配置。 ## 运行测试 ``` # All 1,000+ tests pytest # With coverage pytest --cov=wow_forecaster --cov-report=term-missing # By group pytest tests/test_recommendations/ # Scorer, ranker, item overlay, crafting advisor (160 tests) pytest tests/test_cli/ # CLI smoke tests (54 tests) pytest tests/test_governance/ # Source policies, preflight, freshness, pruner (100 tests) pytest tests/test_reporting/ # Reader, formatters, export, TSM export, health (125 tests) pytest tests/test_monitoring/ # Drift, adaptive, orchestrator (73 tests) pytest tests/test_ingestion/ # Ingestion + snapshots (73 tests) pytest tests/test_features/ # Feature engineering (81 tests) pytest tests/test_backtest/ # Backtest framework (60 tests) pytest tests/test_models/ # Pydantic validation (61 tests) pytest tests/test_pipeline/ # Pipeline interfaces, normalize, item forecasts (68 tests) pytest tests/test_ml/ # LightGBM training, inference, cold-start blending (81 tests) pytest tests/test_scheduler/ # Scheduler daemon (26 tests) pytest tests/test_db/ # Schema + repositories + migrations (37 tests) pytest tests/test_events/ # Seed loader, event imports (24 tests) pytest tests/test_taxonomy/ # Taxonomy integrity (30 tests) pytest tests/test_recipes/ # Recipe repo, seeder, margin calculator (21 tests) pytest tests/test_scripts/ # Bat wrappers: hourly lock guard, daily gate, health alerting, Windows-only (17 tests) ``` ## 数据模型 ### 市场观察 | 模型 | 存储 | 描述 | |---|---|---| | `RawMarketObservation` | SQLite + Parquet | 收到的原始价格数据(铜币整数) | | `NormalizedMarketObservation` | SQLite + Parquet | 转换为金币、滚动 z-score 处理、标记异常值 | ### 分类法 | 模型 | 描述 | |---|---| | `EventType` | 26 个事件类别(从资料片上线到内容长草期) | | `EventScope` | 4 个范围(全局、区域、服务器集群、阵营) | | `EventSeverity` | 5 个严重性级别(从严重到可忽略) | | `ArchetypeCategory` | 10 个顶级经济类别 | | `ArchetypeTag` | 36 个特定行为标签,带类别前缀验证 | ### 核心实体 | 模型 | 关键字段 | 描述 | |---|---|---| | `WoWEvent` | `announced_at` | 影响经济的事件,带前瞻偏差防范 | | `EconomicArchetype` | `transfer_confidence` | 用于跨资料片迁移的行为分组 | | `ArchetypeMapping` | `mapping_rationale` (必填) | 显式的 TWW→Midnight 迁移映射 | | `ForecastOutput` | `confidence_lower/upper` | 带 CI 的点预测 | | `RecommendationOutput` | `action`, `priority` | 带紧急程度排名的 买入/卖出/持有/避开 | | `RunMetadata` | `config_snapshot` | 用于可复现性的完整审计记录 | ## SQLite Schema(21 个表) ``` item_categories Item hierarchy (slug-based, expansion-aware) economic_archetypes 36 behavior tags with transfer_confidence items WoW item registry (item_id -> archetype_id FK) market_observations_raw Raw AH snapshots (copper, pre-normalization) market_observations_normalized Gold-converted, rolling z-scored, outlier-flagged archetype_mappings TWW -> Midnight transfer map (rationale required) wow_events Economy events with announced_at bias guard event_archetype_impacts Event x archetype impact direction/magnitude/lag event_category_impacts Event x category impact (no archetype FK; uses category string) model_metadata Trained model registry (slug, type, artifact_path) run_metadata Pipeline execution audit (config_snapshot, status) forecast_outputs Point forecasts with CI bounds recommendation_outputs buy/sell/hold/avoid with score components ingestion_snapshots Snapshot metadata (source, hash, record_count) backtest_runs Backtest invocation metadata (window, folds) backtest_fold_results Per-prediction backtest results drift_check_results Drift detection results (level, uncertainty_mult) model_health_snapshots Live MAE vs backtest baseline per horizon recipes Blizzard recipe registry (profession, output item, expansion) recipe_reagents Required reagents per recipe (qty, required type only) crafting_margin_snapshots Daily craft cost vs sell price margin per recipe+realm ``` ## 评分公式 推荐按 5 组件综合评分进行排名: ``` score = 0.35 x opportunity + 0.20 x liquidity - 0.20 x volatility + 0.15 x event_boost - 0.10 x uncertainty ``` 操作: - **buy** — 预测 ROI >= 10% - **sell** — 预测 ROI <= -10% - **avoid** — CI 宽度 > 价格的 80% 或变异系数 > 80% - **hold** — 其他情况 `event_boost` 被限制在 `[-100, 100]` 之间 — 负面影响会惩罚分数。 `top_n_per_category` 去重:每个 archetype_id 取最高分的时间范围(平局时:较短的时间范围胜出)。 ## 特征列 数据集构建器每次运行生成两个 Parquet 文件: | 文件 | 列数 | 描述 | |---|---|---| | 训练集 | 48 | 所有特征 + 3 个前瞻性目标列 (`target_price_1d/7d/28d`) | | 推理集 | 45 | 同上但减去目标列(无泄漏) | **特征组:** 价格 (9)、成交量 (3)、lag (5)、rolling (6)、动量 (3)、时间 (4)、事件 (8)、原型 (5)、迁移 (2)、目标 (3 — 仅限训练集)。 ML 模型使用 **37 个输入特征**(推理列的子集,由 `wow_forecaster/ml/feature_selector.py` 选择)。 ## Pipeline 阶段 | 阶段 | 类 | 描述 | |---|---|---| | 接入 | `IngestStage` | 实时 Blizzard API -> 原始观察结果 -> 快照 | | 归一化 | `NormalizeStage` | 铜币->金币、滚动 z-score(30 天窗口)、异常值标记 | | 构建特征 | `FeatureBuildStage` | 48 列 Parquet(lag/rolling/event/archetype 特征) | | 训练 | `TrainStage` | 每个时间范围 (1d/7d/28d) 的 LightGBM 跨原型模型 | | 预测 | `ForecastStage` | 推理 + 启发式 CI,带自适应漂移乘数 | | 推荐 | `RecommendStage` | 5 组件评分、每个类别的前 N 个、CSV/JSON 输出 | | 回测 | `BacktestStage` | 带 4 个基线模型的步进式测试 | | 编排器 | `HourlyOrchestrator` | 带有漂移和溯源的 7 步每小时 pipeline | ## 来源治理 `config/sources.toml` 定义了 3 种来源策略: | 来源 | 状态 | 备注 | |---|---|---| | `blizzard_api` | **已启用** | 通过 OAuth2 获取实时商品和服务器 AH 数据 | | `blizzard_news` | 已启用 | 补丁说明 + 热修复 RSS 订阅源 | | `auctionator` | 已启用 | 本地 SavedVariables 回填(无 HTTP) | `wow_forecaster/governance/preflight.py` 在每次接入前运行 3 项检查:来源已启用、不在冷却时间内、未超过新鲜度阈值。 ## 种子事件 `config/events/tww_events.json` 包含 28 个 TWW 事件,涵盖资料片上线、赛季开始/结束、RTWFs、主要补丁、节日事件和内容长草期。 `config/events/tww_event_impacts.json` 包含 56 条类别级别的影响记录,将事件类型 + 类别映射到预期的价格变化幅度和方向。 在构建数据集之前,运行 `wow-forecaster build-events` 将这些数据加载到数据库中。 ## 配置 所有设置都在 `config/default.toml` 中。可通过以下方式在本地覆盖: 1. `config/local.toml` (已 gitignore) — 本地路径覆盖 2. `.env` (已 gitignore) — 机密信息和特定环境的覆盖 3. `WOW_FORECASTER_*` 环境变量 关键部分:`[database]`、`[expansions]`、`[realms]`、`[pipeline]`、`[forecast]`、`[features]`、`[model]`、`[monitoring]`、`[backtest]`、`[logging]`、`[governance]`、`[crafting]`。 ### 凭据 (.env) ``` BLIZZARD_CLIENT_ID=... # required for live Blizzard AH data BLIZZARD_CLIENT_SECRET=... # required for live Blizzard AH data ``` 如果没有 Blizzard 凭据,pipeline 将无法接入实时数据。 ## 相关项目 - **[alt-army-guide](https://github.com/RussellFeinstein/alt-army-guide)** — 分步指南,用于设置炼金术 + 附魔小号以执行此系统的推荐。制造目标(Light's Potential、Enchant Chest - Mark of the Worldsoul)是使用此预测器的利润分析选出的。 ## 尚未实现的功能 - `top_n_per_category` V2 改进:Pareto 前沿排名、用户画像权重设置、“禁止推荐”黑名单、A/B 测试支持。(跨时间范围去重已在 v0.9.1 中实现。) - 来源治理:各来源的冷却时间强制执行 — 冷却检查逻辑存在于 `preflight.py` 中,但 `orchestrator.py` 从不查询或传递 `last_call_at`,因此该检查总是被跳过。 - 实时新闻接入:`BlizzardNewsClient.fetch_recent_news()` 已实现,但 `IngestStage._fetch_news()` 无论凭据如何,总是调用 fixture 模式。 - 从新闻到事件的自动检测:`extract_wow_events()`(将接入的新闻项映射到 `WoWEvent` 候选项)尚未实现。 ## 开发 ``` # Install dev dependencies pip install -e ".[dev]" # Lint ruff check wow_forecaster/ tests/ # All tests with coverage pytest --cov=wow_forecaster --cov-report=term-missing # Run a specific test group pytest tests/test_recommendations/ -v ```
标签:Apex, Kubernetes, LightGBM, Python, Streamlit, 安全规则引擎, 数据工程, 无后门, 时间序列预测, 机器学习, 访问控制, 运行时操纵, 逆向工具, 量化交易