aria-code 0.52.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (478) hide show
  1. aria_code/__init__.py +42 -0
  2. aria_code/_version.py +20 -0
  3. aria_code/adk_apps/__init__.py +1 -0
  4. aria_code/adk_apps/aria_code_review/__init__.py +1 -0
  5. aria_code/adk_apps/aria_code_review/agent.py +32 -0
  6. aria_code/adk_apps/aria_research/__init__.py +1 -0
  7. aria_code/adk_apps/aria_research/agent.py +31 -0
  8. aria_code/agents/__init__.py +34 -0
  9. aria_code/agents/base.py +318 -0
  10. aria_code/agents/code_review.py +200 -0
  11. aria_code/agents/deep/__init__.py +37 -0
  12. aria_code/agents/deep/calibration_loop.py +144 -0
  13. aria_code/agents/deep/critic.py +125 -0
  14. aria_code/agents/deep/deepen.py +193 -0
  15. aria_code/agents/deep/models.py +149 -0
  16. aria_code/agents/deep/pipeline.py +164 -0
  17. aria_code/agents/deep/quant_fusion.py +192 -0
  18. aria_code/agents/deep/themes.py +95 -0
  19. aria_code/agents/deep/tiers.py +106 -0
  20. aria_code/agents/engineering/__init__.py +14 -0
  21. aria_code/agents/engineering/coder.py +222 -0
  22. aria_code/agents/engineering/tester.py +145 -0
  23. aria_code/agents/financial/__init__.py +21 -0
  24. aria_code/agents/financial/cashflow_burn.py +119 -0
  25. aria_code/agents/financial/catalyst.py +279 -0
  26. aria_code/agents/financial/corporate_finance.py +175 -0
  27. aria_code/agents/financial/debate.py +224 -0
  28. aria_code/agents/financial/earnings.py +303 -0
  29. aria_code/agents/financial/fundamental.py +191 -0
  30. aria_code/agents/financial/macro.py +99 -0
  31. aria_code/agents/financial/news.py +207 -0
  32. aria_code/agents/financial/risk.py +165 -0
  33. aria_code/agents/financial/sector.py +279 -0
  34. aria_code/agents/financial/strategist.py +121 -0
  35. aria_code/agents/financial/stripe_revenue.py +127 -0
  36. aria_code/agents/financial/synthesis.py +274 -0
  37. aria_code/agents/financial/technical.py +258 -0
  38. aria_code/agents/orchestrator.py +44 -0
  39. aria_code/agents/portfolio_agent.py +363 -0
  40. aria_code/agents/realty/__init__.py +62 -0
  41. aria_code/agents/realty/asset_diagnosis.py +152 -0
  42. aria_code/agents/realty/business_match.py +166 -0
  43. aria_code/agents/realty/cashflow_verify.py +209 -0
  44. aria_code/agents/realty/contract_rules.py +210 -0
  45. aria_code/agents/realty/energy_anomaly.py +189 -0
  46. aria_code/agents/realty/exit_settlement.py +208 -0
  47. aria_code/agents/realty/fulfillment_risk.py +206 -0
  48. aria_code/agents/realty/ops_optimize.py +160 -0
  49. aria_code/agents/realty/revenue_share.py +215 -0
  50. aria_code/agents/registry.py +158 -0
  51. aria_code/agents/signal_scheme.py +111 -0
  52. aria_code/agents/sports/__init__.py +0 -0
  53. aria_code/agents/sports/football_agent.py +197 -0
  54. aria_code/agents/supervisor.py +113 -0
  55. aria_code/agents/team.py +492 -0
  56. aria_code/agents/warehouse/__init__.py +25 -0
  57. aria_code/agents/warehouse/contracts.py +26 -0
  58. aria_code/agents/warehouse/dashboard.py +155 -0
  59. aria_code/agents/warehouse/fulfillment_leadtime.py +95 -0
  60. aria_code/agents/warehouse/inbound_exceptions.py +25 -0
  61. aria_code/agents/warehouse/inventory_health.py +24 -0
  62. aria_code/agents/warehouse/local_run.py +71 -0
  63. aria_code/agents/warehouse/local_snapshot.py +132 -0
  64. aria_code/agents/warehouse/logistics_cost.py +84 -0
  65. aria_code/agents/warehouse/logistics_sync.py +21 -0
  66. aria_code/agents/warehouse/workflow.py +31 -0
  67. aria_code/aliyun_data_client.py +4 -0
  68. aria_code/apps/README.md +12 -0
  69. aria_code/apps/__init__.py +2 -0
  70. aria_code/apps/channels/README.md +15 -0
  71. aria_code/apps/channels/__init__.py +17 -0
  72. aria_code/apps/channels/intake.py +92 -0
  73. aria_code/apps/channels/registry.py +95 -0
  74. aria_code/apps/channels/tradingview.py +94 -0
  75. aria_code/apps/cli/README.md +13 -0
  76. aria_code/apps/cli/__init__.py +2 -0
  77. aria_code/apps/cli/_optional.py +120 -0
  78. aria_code/apps/cli/bootstrap.py +145 -0
  79. aria_code/apps/cli/broker_render.py +206 -0
  80. aria_code/apps/cli/codegen_paths.py +29 -0
  81. aria_code/apps/cli/commands/__init__.py +16 -0
  82. aria_code/apps/cli/commands/_business_render.py +78 -0
  83. aria_code/apps/cli/commands/_ui.py +71 -0
  84. aria_code/apps/cli/commands/analysis_cmds.py +369 -0
  85. aria_code/apps/cli/commands/ashare_prediction_cmds.py +327 -0
  86. aria_code/apps/cli/commands/auth_cmds.py +239 -0
  87. aria_code/apps/cli/commands/backtest_cmds.py +2543 -0
  88. aria_code/apps/cli/commands/broker_cmds.py +1234 -0
  89. aria_code/apps/cli/commands/business_workflow_cmds.py +319 -0
  90. aria_code/apps/cli/commands/canvas_cmds.py +77 -0
  91. aria_code/apps/cli/commands/catalog.py +87 -0
  92. aria_code/apps/cli/commands/core_cmds.py +2520 -0
  93. aria_code/apps/cli/commands/data_cmds.py +457 -0
  94. aria_code/apps/cli/commands/diagnostic_cmds.py +230 -0
  95. aria_code/apps/cli/commands/diagnostic_ops_cmds.py +813 -0
  96. aria_code/apps/cli/commands/file_cmds.py +312 -0
  97. aria_code/apps/cli/commands/finance_service_cmds.py +60 -0
  98. aria_code/apps/cli/commands/fx_commodity_cmds.py +123 -0
  99. aria_code/apps/cli/commands/market.py +434 -0
  100. aria_code/apps/cli/commands/market_cmds.py +1381 -0
  101. aria_code/apps/cli/commands/market_context.py +425 -0
  102. aria_code/apps/cli/commands/market_render.py +7 -0
  103. aria_code/apps/cli/commands/model_cmds.py +2153 -0
  104. aria_code/apps/cli/commands/ops_cmds.py +721 -0
  105. aria_code/apps/cli/commands/orchestrator_cmds.py +179 -0
  106. aria_code/apps/cli/commands/pdf_export_cmds.py +125 -0
  107. aria_code/apps/cli/commands/portfolio_cmds.py +1278 -0
  108. aria_code/apps/cli/commands/report.py +437 -0
  109. aria_code/apps/cli/commands/scaffold_templates.py +617 -0
  110. aria_code/apps/cli/commands/session_cmds.py +236 -0
  111. aria_code/apps/cli/commands/session_ux_cmds.py +359 -0
  112. aria_code/apps/cli/commands/team.py +669 -0
  113. aria_code/apps/cli/commands/team_render.py +8 -0
  114. aria_code/apps/cli/commands/ui_cmds.py +401 -0
  115. aria_code/apps/cli/commands/warehouse_cmds.py +79 -0
  116. aria_code/apps/cli/commands/workflow_cmds.py +480 -0
  117. aria_code/apps/cli/commands/workspace_cmds.py +1494 -0
  118. aria_code/apps/cli/config_paths.py +73 -0
  119. aria_code/apps/cli/config_store.py +78 -0
  120. aria_code/apps/cli/constants.py +88 -0
  121. aria_code/apps/cli/context.py +34 -0
  122. aria_code/apps/cli/deterministic.py +191 -0
  123. aria_code/apps/cli/direct.py +48 -0
  124. aria_code/apps/cli/finance_service_catalog.py +111 -0
  125. aria_code/apps/cli/football_reports.py +231 -0
  126. aria_code/apps/cli/github_app_auth.py +135 -0
  127. aria_code/apps/cli/google_login.py +196 -0
  128. aria_code/apps/cli/handlers/__init__.py +11 -0
  129. aria_code/apps/cli/handlers/broker_handlers.py +122 -0
  130. aria_code/apps/cli/handlers/chart_handlers.py +1309 -0
  131. aria_code/apps/cli/handlers/market_handlers.py +2513 -0
  132. aria_code/apps/cli/handlers/realty_handlers.py +114 -0
  133. aria_code/apps/cli/handlers/sports_handlers.py +22 -0
  134. aria_code/apps/cli/handlers/strategy_advice.py +82 -0
  135. aria_code/apps/cli/helpers.py +302 -0
  136. aria_code/apps/cli/hooks.py +180 -0
  137. aria_code/apps/cli/i18n.py +297 -0
  138. aria_code/apps/cli/intent.py +136 -0
  139. aria_code/apps/cli/intent_router.py +276 -0
  140. aria_code/apps/cli/intent_signals.py +344 -0
  141. aria_code/apps/cli/lifecycle_hooks.py +48 -0
  142. aria_code/apps/cli/local_tool_schemas.py +536 -0
  143. aria_code/apps/cli/main.py +29 -0
  144. aria_code/apps/cli/market_metadata.py +135 -0
  145. aria_code/apps/cli/market_universe.py +487 -0
  146. aria_code/apps/cli/message_processing.py +310 -0
  147. aria_code/apps/cli/model_catalog.py +620 -0
  148. aria_code/apps/cli/pdf_report.py +977 -0
  149. aria_code/apps/cli/plan_mode.py +139 -0
  150. aria_code/apps/cli/plotly_html.py +15 -0
  151. aria_code/apps/cli/prediction_feedback.py +202 -0
  152. aria_code/apps/cli/preflight.py +502 -0
  153. aria_code/apps/cli/project_aria.py +60 -0
  154. aria_code/apps/cli/prompt_assembly.py +59 -0
  155. aria_code/apps/cli/prompts/__init__.py +0 -0
  156. aria_code/apps/cli/prompts/coding.py +53 -0
  157. aria_code/apps/cli/prompts/select.py +142 -0
  158. aria_code/apps/cli/prompts/system_prompts.py +552 -0
  159. aria_code/apps/cli/prompts/ui.py +436 -0
  160. aria_code/apps/cli/provider_endpoints.py +237 -0
  161. aria_code/apps/cli/provider_keys.py +73 -0
  162. aria_code/apps/cli/providers/__init__.py +1 -0
  163. aria_code/apps/cli/providers/base.py +521 -0
  164. aria_code/apps/cli/providers/chat_routing.py +128 -0
  165. aria_code/apps/cli/providers/collaboration.py +98 -0
  166. aria_code/apps/cli/providers/llm/__init__.py +1 -0
  167. aria_code/apps/cli/providers/llm/offline_responses.py +68 -0
  168. aria_code/apps/cli/providers/llm/ollama_stream.py +1594 -0
  169. aria_code/apps/cli/providers/llm/response_cache.py +60 -0
  170. aria_code/apps/cli/providers/llm/sse_stream.py +257 -0
  171. aria_code/apps/cli/providers/runtime_bridge.py +353 -0
  172. aria_code/apps/cli/providers/vertexai_stream.py +316 -0
  173. aria_code/apps/cli/runtime_consumer.py +657 -0
  174. aria_code/apps/cli/sandbox.py +32 -0
  175. aria_code/apps/cli/session_export.py +120 -0
  176. aria_code/apps/cli/session_jsonl.py +208 -0
  177. aria_code/apps/cli/session_store.py +112 -0
  178. aria_code/apps/cli/skills_catalog.py +273 -0
  179. aria_code/apps/cli/todo_tracker.py +190 -0
  180. aria_code/apps/cli/tool_executor.py +823 -0
  181. aria_code/apps/cli/tool_registry.py +34 -0
  182. aria_code/apps/cli/tool_scope.py +106 -0
  183. aria_code/apps/cli/tools/__init__.py +40 -0
  184. aria_code/apps/cli/tools/context.py +46 -0
  185. aria_code/apps/cli/tools/file_tools.py +180 -0
  186. aria_code/apps/cli/tools/market_tools.py +620 -0
  187. aria_code/apps/cli/tools/notebook_tools.py +111 -0
  188. aria_code/apps/cli/tools/system_tools.py +726 -0
  189. aria_code/apps/cli/tools/write_tools.py +845 -0
  190. aria_code/apps/cli/tradingview_bridge.py +529 -0
  191. aria_code/apps/cli/turn_planning.py +137 -0
  192. aria_code/apps/cli/update_check.py +153 -0
  193. aria_code/apps/cli/utils/__init__.py +0 -0
  194. aria_code/apps/cli/utils/market_detect.py +1597 -0
  195. aria_code/apps/daemon/README.md +14 -0
  196. aria_code/apps/vscode/README.md +115 -0
  197. aria_code/apps/vscode/package.json +70 -0
  198. aria_code/aria_cli.py +6743 -0
  199. aria_code/aria_daemon.py +1398 -0
  200. aria_code/aria_feishu_bot.py +1423 -0
  201. aria_code/aria_mcp_server.py +7 -0
  202. aria_code/aria_relay_client.py +4 -0
  203. aria_code/aria_relay_server.py +490 -0
  204. aria_code/aria_telegram_bot.py +202 -0
  205. aria_code/ariarc.py +385 -0
  206. aria_code/artifacts.py +581 -0
  207. aria_code/backtest_engine.py +4 -0
  208. aria_code/backtest_report.py +4 -0
  209. aria_code/brokers/__init__.py +78 -0
  210. aria_code/brokers/automation.py +193 -0
  211. aria_code/brokers/base.py +231 -0
  212. aria_code/brokers/capabilities.py +264 -0
  213. aria_code/brokers/cn/__init__.py +10 -0
  214. aria_code/brokers/cn/easytrader_broker.py +193 -0
  215. aria_code/brokers/cn/futu_broker.py +194 -0
  216. aria_code/brokers/cn/longbridge_broker.py +190 -0
  217. aria_code/brokers/cn/tiger_broker.py +196 -0
  218. aria_code/brokers/cn/xtquant_broker.py +225 -0
  219. aria_code/brokers/config.py +414 -0
  220. aria_code/brokers/intl/__init__.py +5 -0
  221. aria_code/brokers/intl/alpaca_broker.py +183 -0
  222. aria_code/brokers/intl/ibkr_broker.py +215 -0
  223. aria_code/brokers/intl/trading212_broker.py +183 -0
  224. aria_code/brokers/intl/webull_broker.py +156 -0
  225. aria_code/brokers/paper_broker.py +266 -0
  226. aria_code/brokers/planning.py +296 -0
  227. aria_code/brokers/registry.py +213 -0
  228. aria_code/brokers/trading.py +267 -0
  229. aria_code/canva_client.py +4 -0
  230. aria_code/change_store.py +127 -0
  231. aria_code/clients/__init__.py +0 -0
  232. aria_code/clients/aliyun_data_client.py +660 -0
  233. aria_code/clients/aria_relay_client.py +182 -0
  234. aria_code/clients/canva_client.py +284 -0
  235. aria_code/clients/figma_client.py +100 -0
  236. aria_code/clients/football_data_client.py +1671 -0
  237. aria_code/clients/kling_video_client.py +182 -0
  238. aria_code/clients/market_data_client.py +1976 -0
  239. aria_code/clients/openai_image_client.py +242 -0
  240. aria_code/clients/runway_video_client.py +157 -0
  241. aria_code/clients/warehouse_erp_client.py +105 -0
  242. aria_code/cloud_memory.py +181 -0
  243. aria_code/command_safety.py +19 -0
  244. aria_code/computer_use_tools.py +4 -0
  245. aria_code/dashboard_generator.py +579 -0
  246. aria_code/data_analysis_tools.py +4 -0
  247. aria_code/data_cleaner.py +483 -0
  248. aria_code/data_service.py +513 -0
  249. aria_code/datasources/__init__.py +23 -0
  250. aria_code/datasources/base.py +166 -0
  251. aria_code/datasources/router.py +253 -0
  252. aria_code/datasources/sources/__init__.py +15 -0
  253. aria_code/datasources/sources/akshare_source.py +269 -0
  254. aria_code/datasources/sources/alpha_vantage_source.py +203 -0
  255. aria_code/datasources/sources/edgar_source.py +219 -0
  256. aria_code/datasources/sources/finnhub_source.py +198 -0
  257. aria_code/datasources/sources/fred_source.py +223 -0
  258. aria_code/datasources/sources/tushare_source.py +143 -0
  259. aria_code/datasources/sources/web_scraper_source.py +278 -0
  260. aria_code/datasources/sources/world_bank_source.py +206 -0
  261. aria_code/datasources/sources/yfinance_source.py +152 -0
  262. aria_code/demo_player.py +207 -0
  263. aria_code/doctor.py +813 -0
  264. aria_code/domain/__init__.py +0 -0
  265. aria_code/domain/backtest_engine.py +354 -0
  266. aria_code/domain/backtest_report.py +472 -0
  267. aria_code/domain/finance_formulas.py +389 -0
  268. aria_code/domain/portfolio_ledger.py +307 -0
  269. aria_code/domain/strategy_vault.py +421 -0
  270. aria_code/evals/__init__.py +37 -0
  271. aria_code/evals/harness.py +598 -0
  272. aria_code/evals/runner.py +238 -0
  273. aria_code/external_agent_runner.py +115 -0
  274. aria_code/figma_client.py +4 -0
  275. aria_code/file_analysis_tools.py +4 -0
  276. aria_code/finance_formulas.py +4 -0
  277. aria_code/football_data_client.py +4 -0
  278. aria_code/image_gen_tools.py +4 -0
  279. aria_code/intent_classifier.py +386 -0
  280. aria_code/kling_video_client.py +4 -0
  281. aria_code/licensing.py +151 -0
  282. aria_code/local_finance_tools.py +4 -0
  283. aria_code/local_image_provider.py +4 -0
  284. aria_code/local_llm_provider.py +4 -0
  285. aria_code/macro_tools.py +4 -0
  286. aria_code/markdown_pdf.py +289 -0
  287. aria_code/market_data_client.py +4 -0
  288. aria_code/mcp_client.py +639 -0
  289. aria_code/memory_manager.py +246 -0
  290. aria_code/model_capability.py +486 -0
  291. aria_code/notification_tools.py +4 -0
  292. aria_code/openai_image_client.py +4 -0
  293. aria_code/packages/__init__.py +23 -0
  294. aria_code/packages/adk_bridge/__init__.py +11 -0
  295. aria_code/packages/adk_bridge/code_review_tools.py +49 -0
  296. aria_code/packages/adk_bridge/market_tools.py +125 -0
  297. aria_code/packages/aria_agents/__init__.py +5 -0
  298. aria_code/packages/aria_agents/manifest.py +78 -0
  299. aria_code/packages/aria_core/__init__.py +34 -0
  300. aria_code/packages/aria_core/architecture.py +269 -0
  301. aria_code/packages/aria_core/export.py +147 -0
  302. aria_code/packages/aria_core/manifest.py +65 -0
  303. aria_code/packages/aria_core/paths.py +57 -0
  304. aria_code/packages/aria_core/secure_file.py +68 -0
  305. aria_code/packages/aria_infra/__init__.py +15 -0
  306. aria_code/packages/aria_infra/arthera.py +52 -0
  307. aria_code/packages/aria_infra/doctor.py +246 -0
  308. aria_code/packages/aria_infra/product.py +40 -0
  309. aria_code/packages/aria_mcp/__init__.py +25 -0
  310. aria_code/packages/aria_mcp/bridge.py +201 -0
  311. aria_code/packages/aria_mcp/circuit.py +82 -0
  312. aria_code/packages/aria_mcp/config.py +111 -0
  313. aria_code/packages/aria_mcp/installer.py +95 -0
  314. aria_code/packages/aria_mcp/server.py +1550 -0
  315. aria_code/packages/aria_mcp/tools.py +81 -0
  316. aria_code/packages/aria_sdk/__init__.py +19 -0
  317. aria_code/packages/aria_sdk/client.py +396 -0
  318. aria_code/packages/aria_sdk/providers.py +70 -0
  319. aria_code/packages/aria_sdk/streaming.py +79 -0
  320. aria_code/packages/aria_sdk/types.py +86 -0
  321. aria_code/packages/aria_services/__init__.py +92 -0
  322. aria_code/packages/aria_services/cache.py +60 -0
  323. aria_code/packages/aria_services/context.py +356 -0
  324. aria_code/packages/aria_services/context_checkpoints.py +157 -0
  325. aria_code/packages/aria_services/data.py +11 -0
  326. aria_code/packages/aria_services/provider_health.py +268 -0
  327. aria_code/packages/aria_services/references.py +247 -0
  328. aria_code/packages/aria_services/registry.py +249 -0
  329. aria_code/packages/aria_services/research_protocol.py +57 -0
  330. aria_code/packages/aria_services/research_quality.py +186 -0
  331. aria_code/packages/aria_services/settings.py +157 -0
  332. aria_code/packages/aria_services/usage.py +151 -0
  333. aria_code/packages/aria_skills/__init__.py +46 -0
  334. aria_code/packages/aria_skills/catalog.py +149 -0
  335. aria_code/packages/aria_skills/loader.py +455 -0
  336. aria_code/packages/aria_skills/registry.py +84 -0
  337. aria_code/packages/aria_tools/__init__.py +5 -0
  338. aria_code/packages/aria_tools/financial/__init__.py +8 -0
  339. aria_code/packages/aria_tools/financial/_paths.py +130 -0
  340. aria_code/packages/aria_tools/financial/compliance.py +31 -0
  341. aria_code/packages/aria_tools/financial/factors.py +33 -0
  342. aria_code/packages/aria_tools/financial/risk_tools.py +33 -0
  343. aria_code/packages/aria_tools/financial/strategy.py +31 -0
  344. aria_code/packages/aria_tools/registry.py +128 -0
  345. aria_code/packages/quant_engine/__init__.py +34 -0
  346. aria_code/packages/quant_engine/_namespace.py +62 -0
  347. aria_code/packages/quant_engine/backtest/__init__.py +14 -0
  348. aria_code/packages/quant_engine/backtest/core.py +53 -0
  349. aria_code/packages/quant_engine/backtest/engine.py +96 -0
  350. aria_code/packages/quant_engine/portfolio/__init__.py +13 -0
  351. aria_code/packages/quant_engine/portfolio/optimizer.py +85 -0
  352. aria_code/packages/quant_engine/sports/__init__.py +80 -0
  353. aria_code/packages/quant_engine/sports/calibrator.py +354 -0
  354. aria_code/packages/quant_engine/sports/dixon_coles.py +234 -0
  355. aria_code/packages/quant_engine/sports/elo.py +300 -0
  356. aria_code/packages/quant_engine/sports/form.py +188 -0
  357. aria_code/packages/quant_engine/sports/h2h.py +195 -0
  358. aria_code/packages/quant_engine/sports/ml_model.py +377 -0
  359. aria_code/packages/quant_engine/sports/predictor.py +312 -0
  360. aria_code/packages/quant_engine/sports/tracker.py +665 -0
  361. aria_code/packages/quant_engine/stochastic/__init__.py +35 -0
  362. aria_code/packages/quant_engine/stochastic/gbm_enhanced.py +195 -0
  363. aria_code/packages/quant_engine/stochastic/ito_calculus.py +477 -0
  364. aria_code/packages/quant_engine/stochastic/kelly_criterion.py +181 -0
  365. aria_code/packages/quant_engine/stochastic/monte_carlo_advanced.py +95 -0
  366. aria_code/packages/quant_engine/stochastic/options_pricing.py +576 -0
  367. aria_code/packages/quant_engine/stochastic/stochastic_processes.py +90 -0
  368. aria_code/packs/__init__.py +85 -0
  369. aria_code/packs/base.py +168 -0
  370. aria_code/packs/finance/__init__.py +250 -0
  371. aria_code/packs/logistics/__init__.py +169 -0
  372. aria_code/packs/payments/__init__.py +139 -0
  373. aria_code/packs/realty/__init__.py +190 -0
  374. aria_code/packs/registry.py +202 -0
  375. aria_code/packs/rules.py +90 -0
  376. aria_code/plan_utils.py +194 -0
  377. aria_code/plugin_loader.py +328 -0
  378. aria_code/portfolio_ledger.py +4 -0
  379. aria_code/preview_server.py +449 -0
  380. aria_code/privacy/__init__.py +5 -0
  381. aria_code/privacy/feedback.py +123 -0
  382. aria_code/project_review.py +278 -0
  383. aria_code/project_review_api.py +235 -0
  384. aria_code/project_review_server.py +18 -0
  385. aria_code/project_tools.py +4 -0
  386. aria_code/providers/__init__.py +30 -0
  387. aria_code/providers/llm/__init__.py +19 -0
  388. aria_code/providers/llm/anthropic.py +184 -0
  389. aria_code/providers/llm/autoconfig.py +213 -0
  390. aria_code/providers/llm/base.py +139 -0
  391. aria_code/providers/llm/custom.py +158 -0
  392. aria_code/providers/llm/ollama.py +129 -0
  393. aria_code/providers/llm/openai_compat.py +313 -0
  394. aria_code/providers/llm/registry.py +444 -0
  395. aria_code/providers/local_image_provider.py +202 -0
  396. aria_code/providers/local_llm_provider.py +589 -0
  397. aria_code/realty_data_tools.py +4 -0
  398. aria_code/report_exporters.py +150 -0
  399. aria_code/report_generator.py +1764 -0
  400. aria_code/runtime/__init__.py +169 -0
  401. aria_code/runtime/acceptance.py +481 -0
  402. aria_code/runtime/agent_loop.py +1520 -0
  403. aria_code/runtime/approval.py +57 -0
  404. aria_code/runtime/budget.py +232 -0
  405. aria_code/runtime/checkpoints.py +432 -0
  406. aria_code/runtime/crash_report.py +174 -0
  407. aria_code/runtime/events.py +113 -0
  408. aria_code/runtime/gateway.py +150 -0
  409. aria_code/runtime/lsp.py +484 -0
  410. aria_code/runtime/orchestrator.py +55 -0
  411. aria_code/runtime/repo_map.py +700 -0
  412. aria_code/runtime/run_state.py +127 -0
  413. aria_code/runtime/run_store.py +450 -0
  414. aria_code/runtime/self_healing.py +422 -0
  415. aria_code/runtime/subagent.py +547 -0
  416. aria_code/runtime/task_ledger.py +86 -0
  417. aria_code/runtime/task_orchestrator.py +90 -0
  418. aria_code/runtime/tool_executor.py +217 -0
  419. aria_code/runtime/tool_policy.py +107 -0
  420. aria_code/runtime/worktrees.py +215 -0
  421. aria_code/runway_video_client.py +4 -0
  422. aria_code/safety/__init__.py +23 -0
  423. aria_code/safety/permissions.py +306 -0
  424. aria_code/safety/service.py +102 -0
  425. aria_code/setup_wizard.py +673 -0
  426. aria_code/spreadsheet_tools.py +4 -0
  427. aria_code/strategy_vault.py +4 -0
  428. aria_code/tools/__init__.py +0 -0
  429. aria_code/tools/artifact_tools.py +252 -0
  430. aria_code/tools/broker_tools.py +92 -0
  431. aria_code/tools/build_quant_engine.py +97 -0
  432. aria_code/tools/code_audit_tools.py +192 -0
  433. aria_code/tools/computer_use_tools.py +504 -0
  434. aria_code/tools/data_analysis_tools.py +809 -0
  435. aria_code/tools/enterprise_finance_tools.py +156 -0
  436. aria_code/tools/extended_tools.py +240 -0
  437. aria_code/tools/file_analysis_tools.py +885 -0
  438. aria_code/tools/image_gen_tools.py +114 -0
  439. aria_code/tools/local_finance_tools.py +3417 -0
  440. aria_code/tools/logistics_tools.py +135 -0
  441. aria_code/tools/macro_tools.py +369 -0
  442. aria_code/tools/notification_tools.py +249 -0
  443. aria_code/tools/project_tools.py +525 -0
  444. aria_code/tools/realty_data_tools.py +659 -0
  445. aria_code/tools/spreadsheet_tools.py +388 -0
  446. aria_code/tools/stripe_tools.py +115 -0
  447. aria_code/ui/__init__.py +105 -0
  448. aria_code/ui/banner.py +508 -0
  449. aria_code/ui/completer.py +501 -0
  450. aria_code/ui/console.py +281 -0
  451. aria_code/ui/image_render.py +243 -0
  452. aria_code/ui/input_box.py +488 -0
  453. aria_code/ui/picker.py +201 -0
  454. aria_code/ui/render/__init__.py +11 -0
  455. aria_code/ui/render/finance.py +1705 -0
  456. aria_code/ui/render/market.py +225 -0
  457. aria_code/ui/render/output.py +775 -0
  458. aria_code/ui/render/responsive.py +75 -0
  459. aria_code/ui/render/team.py +354 -0
  460. aria_code/ui/robot.py +235 -0
  461. aria_code/ui/startup_dashboard.py +109 -0
  462. aria_code/utils/vscode_uri.py +37 -0
  463. aria_code/video_analysis.py +147 -0
  464. aria_code/video_editor.py +271 -0
  465. aria_code/workspace/__init__.py +6 -0
  466. aria_code/workspace/files.py +193 -0
  467. aria_code/workspace/verify.py +113 -0
  468. aria_code/workspace_changes.py +199 -0
  469. aria_code/workspace_context.py +233 -0
  470. aria_code/workspace_service.py +196 -0
  471. aria_code/workspace_tools.py +150 -0
  472. aria_code-0.52.0.dist-info/METADATA +237 -0
  473. aria_code-0.52.0.dist-info/RECORD +478 -0
  474. aria_code-0.52.0.dist-info/WHEEL +5 -0
  475. aria_code-0.52.0.dist-info/entry_points.txt +3 -0
  476. aria_code-0.52.0.dist-info/licenses/LICENSE +201 -0
  477. aria_code-0.52.0.dist-info/licenses/NOTICE +49 -0
  478. aria_code-0.52.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,80 @@
1
+ # 让本子包也能穿透到私有 Arthera 仓的同名子包。
2
+ # 父层 (packages / quant_engine) 已经做了 __path__ 拼接,但 Python 找到
3
+ # 常规子包后就停止查找,不会继续看父包 __path__ 的其它条目——所以每一层
4
+ # 都得自己声明。规则:aria-code 自带的实现优先,Arthera 补齐缺口。
5
+ # 详见 packages/quant_engine/_namespace.py 的模块文档。
6
+ from .._namespace import extend as _extend_namespace
7
+ _extend_namespace(__path__, "sports")
8
+
9
+ """
10
+ packages/quant_engine/sports — 足球量化分析模块
11
+ ================================================
12
+ v2.0.0 — 2026-06
13
+
14
+ 模块组成:
15
+ elo — World Football Elo 动态评分系统(二次曲线攻防,GD K 因子)
16
+ dixon_coles — Dixon-Coles 比分预测(NB 分布,大比分悬殊自动启用)
17
+ form — 近期状态分析(指数衰减权重)
18
+ h2h — 历史交锋分析与调整
19
+ predictor — 统一预测引擎 v2(动态权重、赛事情境、ρ 校准)
20
+ tracker — 预测追踪、Brier Score、自动 Elo 同步、动态场均进球
21
+
22
+ 快速使用:
23
+ from packages.quant_engine.sports import quick_predict, get_elo
24
+
25
+ # 预测(含 NB 分布 + 动态权重)
26
+ result = quick_predict("germany", "curacao", league="wc")
27
+ print(f"德国赢率: {result['home_win']*100:.1f}%") # ~85%
28
+
29
+ # Elo 评分
30
+ elo = get_elo()
31
+ print(elo.get_rating("germany")) # ~1912(赛后更新)
32
+
33
+ # 自动同步已结束 WC 比赛 Elo
34
+ from packages.quant_engine.sports import sync_elo_from_wc
35
+ sync_elo_from_wc(api_get_fn)
36
+ """
37
+
38
+ from .elo import EloRatingSystem, get_elo, ranking_to_elo
39
+ from .dixon_coles import (
40
+ compute_match_probabilities,
41
+ predict_scoreline_matrix,
42
+ tau_correction,
43
+ estimate_rho_from_results,
44
+ format_dc_result,
45
+ )
46
+ from .form import analyze_form, parse_api_results, form_bar, momentum_label
47
+ from .h2h import analyze_h2h
48
+ from .predictor import FootballPredictor, get_predictor, quick_predict
49
+ from .tracker import (
50
+ record_prediction,
51
+ record_result,
52
+ get_accuracy_stats,
53
+ sync_elo_from_wc,
54
+ fetch_wc_league_avg,
55
+ fetch_wc_rho,
56
+ auto_calibrate,
57
+ backfill_score_metrics,
58
+ )
59
+ from .calibrator import (
60
+ get_calibrated_params,
61
+ get_team_goal_bias,
62
+ get_all_team_biases,
63
+ calibration_summary,
64
+ save_calibration,
65
+ )
66
+
67
+ __all__ = [
68
+ "EloRatingSystem", "get_elo", "ranking_to_elo",
69
+ "compute_match_probabilities", "predict_scoreline_matrix",
70
+ "tau_correction", "estimate_rho_from_results", "format_dc_result",
71
+ "analyze_form", "parse_api_results", "form_bar", "momentum_label",
72
+ "analyze_h2h",
73
+ "FootballPredictor", "get_predictor", "quick_predict",
74
+ "record_prediction", "record_result", "get_accuracy_stats",
75
+ "sync_elo_from_wc", "fetch_wc_league_avg", "fetch_wc_rho", "auto_calibrate",
76
+ "get_calibrated_params", "get_team_goal_bias", "get_all_team_biases",
77
+ "calibration_summary", "save_calibration",
78
+ ]
79
+
80
+ __version__ = "2.0.0"
@@ -0,0 +1,354 @@
1
+ """
2
+ sports/calibrator.py — 模型参数自动优化
3
+ =========================================
4
+ 基于历史预测 Brier Score 和实际进球,持续校准攻防斜率与 λ 偏差。
5
+
6
+ 自动优化流程(数据积累触发):
7
+ ≥ 5 场已结算 → λ 偏差修正(实际进球 / 预测 λ 的指数移动平均)
8
+ ≥ 10 场已结算 → 攻防斜率网格搜索(最小化 Brier Score)
9
+ ≥ 3 场单队数据 → 队伍专属进球偏差修正
10
+
11
+ 持久化:
12
+ ~/.arthera/wc_calibrated_params.json — 全局斜率 + λ 偏差
13
+ ~/.arthera/team_goal_bias.json — 各队进球偏差 EMA
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import json
19
+ import time
20
+ from pathlib import Path
21
+ from typing import Dict, List, Optional, Tuple
22
+ from aria_code.packages.aria_core.paths import aria_home
23
+
24
+ _PARAMS_PATH = aria_home() / "wc_calibrated_params.json"
25
+ _TEAM_BIAS_PATH = aria_home() / "team_goal_bias.json"
26
+
27
+ _DEFAULT_PARAMS = {
28
+ "a1": 1.05, "a2": 0.35, # 攻击斜率(线性 + 二次)
29
+ "d1": -0.42, "d2": -0.10, # 防守斜率
30
+ "lambda_home_bias": 1.0, # λ 偏差修正因子
31
+ "lambda_away_bias": 1.0,
32
+ "conf_temp": 1.0, # 概率温度(<1 收敛过度自信的预测)
33
+ "calibrated_at": None,
34
+ "n_matches": 0,
35
+ "avg_brier": None,
36
+ }
37
+
38
+
39
+ # ── 持久化工具 ────────────────────────────────────────────────────────────────
40
+
41
+ def _load_json(path: Path, default):
42
+ try:
43
+ if path.exists():
44
+ return json.loads(path.read_text(encoding="utf-8"))
45
+ except Exception:
46
+ pass
47
+ return default
48
+
49
+
50
+ def _save_json(path: Path, data) -> None:
51
+ try:
52
+ path.parent.mkdir(parents=True, exist_ok=True)
53
+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
54
+ except Exception:
55
+ pass
56
+
57
+
58
+ # ── 1. λ 偏差修正 ─────────────────────────────────────────────────────────────
59
+
60
+ def optimize_lambda_bias(settled_records: List[Dict]) -> Dict[str, float]:
61
+ """
62
+ 从已结算预测计算主客队 λ 系统偏差。
63
+
64
+ 每条记录需包含: actual_home_goals, actual_away_goals, lambda_home, lambda_away。
65
+ 偏差 = mean(actual / predicted);> 1.0 说明模型系统性低估进球。
66
+ 需要 ≥ 5 条含实际进球的记录才修正。
67
+ """
68
+ home_ratios, away_ratios = [], []
69
+
70
+ for r in settled_records:
71
+ ah = r.get("actual_home_goals")
72
+ aa = r.get("actual_away_goals")
73
+ lh = r.get("lambda_home")
74
+ la = r.get("lambda_away")
75
+ if ah is not None and lh and lh > 0:
76
+ home_ratios.append(ah / lh)
77
+ if aa is not None and la and la > 0:
78
+ away_ratios.append(aa / la)
79
+
80
+ result = {"home_bias": 1.0, "away_bias": 1.0, "n_home": len(home_ratios), "n_away": len(away_ratios)}
81
+ if len(home_ratios) >= 5:
82
+ result["home_bias"] = round(sum(home_ratios) / len(home_ratios), 4)
83
+ if len(away_ratios) >= 5:
84
+ result["away_bias"] = round(sum(away_ratios) / len(away_ratios), 4)
85
+ return result
86
+
87
+
88
+ # ── 2. 攻防斜率网格搜索 ───────────────────────────────────────────────────────
89
+
90
+ def optimize_slopes_from_outcomes(settled_records: List[Dict]) -> Dict:
91
+ """
92
+ 从已结算预测记录(需含 home_elo / away_elo / result)搜索最优攻防斜率。
93
+
94
+ 策略:固定 d1 = -a1×0.40, d2 = -a2×0.29(对称性假设),
95
+ 2D 网格搜索 a1 × a2,最小化平均 Brier Score。
96
+ 需要 ≥ 10 条含 Elo 数据的记录。
97
+ """
98
+ records = [
99
+ r for r in settled_records
100
+ if r.get("home_elo") and r.get("away_elo") and r.get("result")
101
+ ]
102
+ if len(records) < 10:
103
+ return {**_DEFAULT_PARAMS, "status": "not_enough_data", "n": len(records)}
104
+
105
+ try:
106
+ from .dixon_coles import compute_match_probabilities
107
+ except ImportError:
108
+ return {**_DEFAULT_PARAMS, "status": "import_error"}
109
+
110
+ best_brier = float("inf")
111
+ best = {}
112
+
113
+ for a1 in [0.85, 0.95, 1.05, 1.15, 1.25, 1.35]:
114
+ for a2 in [0.20, 0.28, 0.35, 0.43, 0.50]:
115
+ d1 = round(-a1 * 0.40, 3)
116
+ d2 = round(-a2 * 0.29, 3)
117
+ total_brier = 0.0
118
+
119
+ for r in records:
120
+ h_elo = float(r["home_elo"])
121
+ a_elo = float(r["away_elo"])
122
+ si_h = (h_elo - 1500) / 400.0
123
+ si_a = (a_elo - 1500) / 400.0
124
+
125
+ h_atk = max(0.45, min(1.10 + si_h*a1 + max(0, si_h)*si_h*a2, 2.60))
126
+ a_atk = max(0.45, min(1.10 + si_a*a1 + max(0, si_a)*si_a*a2, 2.60))
127
+ h_def = max(0.40, min(0.95 + si_h*d1 + max(0, si_h)*si_h*d2, 1.25))
128
+ a_def = max(0.40, min(0.95 + si_a*d1 + max(0, si_a)*si_a*d2, 1.25))
129
+
130
+ league_avg = float(r.get("league_avg", 1.35))
131
+ lh = max(0.2, min(h_atk * a_def * league_avg, 8.0))
132
+ la = max(0.2, min(a_atk * h_def * league_avg, 8.0))
133
+ elo_diff = h_elo - a_elo
134
+
135
+ dc = compute_match_probabilities(lh, la, rho=-0.10, elo_diff=elo_diff)
136
+ res = r["result"]
137
+ ih = 1.0 if res == "home" else 0.0
138
+ id_ = 1.0 if res == "draw" else 0.0
139
+ ia = 1.0 if res == "away" else 0.0
140
+ total_brier += (dc["home_win"]-ih)**2 + (dc["draw"]-id_)**2 + (dc["away_win"]-ia)**2
141
+
142
+ avg_brier = total_brier / len(records)
143
+ if avg_brier < best_brier:
144
+ best_brier = avg_brier
145
+ best = {
146
+ "a1": a1, "a2": a2, "d1": d1, "d2": d2,
147
+ "avg_brier": round(avg_brier, 4),
148
+ "n": len(records),
149
+ "status": "optimized",
150
+ }
151
+
152
+ return best
153
+
154
+
155
+ # ── 2b. 概率温度校准(对抗过度自信)──────────────────────────────────────────
156
+
157
+ def _apply_temp(ph: float, pd: float, pa: float, temp: float) -> Tuple[float, float, float]:
158
+ """Temperature-scale a 1X2 distribution: p_i ∝ p_i**temp, renormalized.
159
+
160
+ temp < 1 flattens (less confident); temp = 1 is a no-op. Guards against
161
+ zero/negative inputs.
162
+ """
163
+ if temp == 1.0:
164
+ return ph, pd, pa
165
+ eps = 1e-9
166
+ h = max(ph, eps) ** temp
167
+ d = max(pd, eps) ** temp
168
+ a = max(pa, eps) ** temp
169
+ s = h + d + a
170
+ return h / s, d / s, a / s
171
+
172
+
173
+ def optimize_confidence_temp(settled_records: List[Dict]) -> Dict:
174
+ """Grid-search the probability temperature that minimizes Brier.
175
+
176
+ World-Cup favorites are systematically over-predicted (e.g. 88% → draw),
177
+ so the raw 1X2 distribution is too sharp. We find temp ∈ [0.55, 1.0] that
178
+ flattens predictions to best match observed outcomes.
179
+
180
+ Trains on RAW probabilities (raw_home_win/…) when present so it never
181
+ compounds a temperature already applied at output; falls back to the
182
+ stored home_win/… for legacy records. Needs ≥ 8 settled records.
183
+ """
184
+ rows = []
185
+ for r in settled_records:
186
+ if not r.get("result"):
187
+ continue
188
+ ph = r.get("raw_home_win", r.get("home_win"))
189
+ pd = r.get("raw_draw", r.get("draw"))
190
+ pa = r.get("raw_away_win", r.get("away_win"))
191
+ if ph is None or pd is None or pa is None:
192
+ continue
193
+ rows.append((float(ph), float(pd), float(pa), r["result"]))
194
+
195
+ if len(rows) < 8:
196
+ return {"temp": 1.0, "status": "not_enough_data", "n": len(rows)}
197
+
198
+ def mean_brier(temp: float) -> float:
199
+ tot = 0.0
200
+ for ph, pd, pa, res in rows:
201
+ h, d, a = _apply_temp(ph, pd, pa, temp)
202
+ ih = 1.0 if res == "home" else 0.0
203
+ idr = 1.0 if res == "draw" else 0.0
204
+ ia = 1.0 if res == "away" else 0.0
205
+ tot += (h - ih) ** 2 + (d - idr) ** 2 + (a - ia) ** 2
206
+ return tot / len(rows)
207
+
208
+ base = mean_brier(1.0)
209
+ best_temp, best_brier = 1.0, base
210
+ t = 0.55
211
+ while t <= 1.001:
212
+ b = mean_brier(t)
213
+ if b < best_brier:
214
+ best_brier, best_temp = b, round(t, 2)
215
+ t += 0.05
216
+
217
+ return {
218
+ "temp": best_temp,
219
+ "status": "optimized",
220
+ "n": len(rows),
221
+ "brier_before": round(base, 4),
222
+ "brier_after": round(best_brier, 4),
223
+ }
224
+
225
+
226
+ def get_confidence_temp() -> float:
227
+ return get_calibrated_params().get("conf_temp", 1.0)
228
+
229
+
230
+ # ── 3. 队伍专属进球偏差(EMA)─────────────────────────────────────────────────
231
+
232
+ def update_team_goal_bias(team: str, predicted_lambda: float, actual_goals: int) -> None:
233
+ """
234
+ 更新队伍历史进球偏差(指数移动平均,alpha=0.3)。
235
+ bias_ema > 1 表示该队实际进球通常高于模型预测。
236
+ """
237
+ if predicted_lambda <= 0:
238
+ return
239
+
240
+ biases: Dict = _load_json(_TEAM_BIAS_PATH, {})
241
+ key = team.lower().strip()
242
+ ratio = actual_goals / predicted_lambda
243
+
244
+ if key not in biases:
245
+ biases[key] = {"ema": round(ratio, 4), "n": 1, "updated": time.strftime("%Y-%m-%d")}
246
+ else:
247
+ alpha = 0.3
248
+ biases[key]["ema"] = round(alpha * ratio + (1 - alpha) * biases[key]["ema"], 4)
249
+ biases[key]["n"] += 1
250
+ biases[key]["updated"] = time.strftime("%Y-%m-%d")
251
+
252
+ _save_json(_TEAM_BIAS_PATH, biases)
253
+
254
+
255
+ def get_team_goal_bias(team: str) -> float:
256
+ """
257
+ 返回队伍进球偏差修正因子。
258
+ < 3 场数据时返回 1.0(不修正,防止过拟合)。
259
+ """
260
+ biases = _load_json(_TEAM_BIAS_PATH, {})
261
+ entry = biases.get(team.lower().strip(), {})
262
+ if entry.get("n", 0) < 3:
263
+ return 1.0
264
+ bias = entry.get("ema", 1.0)
265
+ # 限制修正幅度,防止极端值
266
+ return round(max(0.70, min(bias, 1.50)), 4)
267
+
268
+
269
+ def get_all_team_biases() -> Dict[str, Dict]:
270
+ """返回所有有数据的队伍偏差记录。"""
271
+ return _load_json(_TEAM_BIAS_PATH, {})
272
+
273
+
274
+ # ── 3b. λ 偏差:基于比分 MAE 的精化校准 ──────────────────────────────────────
275
+
276
+ def optimize_lambda_bias_from_scores(settled_records: List[Dict]) -> Dict:
277
+ """
278
+ 用实际比分优化 λ_home / λ_away 全局缩放因子,最小化总进球 MAE。
279
+
280
+ 与 optimize_lambda_bias 的区别:
281
+ - 后者用 actual/predicted 比值的均值(易受极端值拉偏)
282
+ - 本函数网格搜索 bias_h × bias_a,最小化
283
+ mean(|bias_h * lambda_h - actual_h| + |bias_a * lambda_a - actual_a|)
284
+ 需要 ≥ 8 条含实际进球记录才运行。
285
+
286
+ 返回 {"home_bias": ..., "away_bias": ..., "goals_mae": ..., "n": ..., "status": ...}
287
+ """
288
+ rows = [
289
+ r for r in settled_records
290
+ if r.get("actual_home_goals") is not None
291
+ and r.get("actual_away_goals") is not None
292
+ and r.get("lambda_home") and r.get("lambda_away")
293
+ ]
294
+ if len(rows) < 8:
295
+ return {"home_bias": 1.0, "away_bias": 1.0, "status": "not_enough_data", "n": len(rows)}
296
+
297
+ best_mae = float("inf")
298
+ best_bh, best_ba = 1.0, 1.0
299
+
300
+ for bh in [0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 1.00, 1.05, 1.10, 1.15, 1.20]:
301
+ for ba in [0.70, 0.75, 0.80, 0.85, 0.90, 0.95, 1.00, 1.05, 1.10, 1.15]:
302
+ total = 0.0
303
+ for r in rows:
304
+ pred_h = float(r["lambda_home"]) * bh
305
+ pred_a = float(r["lambda_away"]) * ba
306
+ total += abs(pred_h - float(r["actual_home_goals"]))
307
+ total += abs(pred_a - float(r["actual_away_goals"]))
308
+ mae = total / (2 * len(rows))
309
+ if mae < best_mae:
310
+ best_mae, best_bh, best_ba = mae, bh, ba
311
+
312
+ return {
313
+ "home_bias": round(best_bh, 3),
314
+ "away_bias": round(best_ba, 3),
315
+ "goals_mae": round(best_mae, 4),
316
+ "n": len(rows),
317
+ "status": "optimized",
318
+ }
319
+
320
+
321
+ # ── 4. 参数读写 ───────────────────────────────────────────────────────────────
322
+
323
+ def get_calibrated_params() -> Dict:
324
+ """读取已保存的校准参数,不存在则返回默认值。"""
325
+ saved = _load_json(_PARAMS_PATH, {})
326
+ return {**_DEFAULT_PARAMS, **saved}
327
+
328
+
329
+ def save_calibration(params: Dict) -> None:
330
+ """保存校准结果(追加 timestamp)。"""
331
+ params["calibrated_at"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
332
+ existing = _load_json(_PARAMS_PATH, {})
333
+ existing.update(params)
334
+ _save_json(_PARAMS_PATH, existing)
335
+
336
+
337
+ def calibration_summary() -> str:
338
+ """打印可读的当前校准状态。"""
339
+ p = get_calibrated_params()
340
+ biases = get_all_team_biases()
341
+ lines = [
342
+ f"校准时间: {p.get('calibrated_at', '未校准')}",
343
+ f"攻击斜率: a1={p['a1']} a2={p['a2']}",
344
+ f"防守斜率: d1={p['d1']} d2={p['d2']}",
345
+ f"λ 偏差: 主队 ×{p['lambda_home_bias']} 客队 ×{p['lambda_away_bias']}",
346
+ f"平均 Brier: {p.get('avg_brier', 'N/A')}",
347
+ f"样本场次: {p.get('n_matches', 0)}",
348
+ "",
349
+ "队伍进球偏差 (≥3场数据):",
350
+ ]
351
+ for team, d in sorted(biases.items(), key=lambda x: -x[1].get("n", 0)):
352
+ if d.get("n", 0) >= 3:
353
+ lines.append(f" {team:<20} EMA={d['ema']:.3f} n={d['n']}")
354
+ return "\n".join(lines)
@@ -0,0 +1,234 @@
1
+ """
2
+ sports/dixon_coles.py — Dixon-Coles 足球比分预测模型
3
+ =====================================================
4
+ 实现 Dixon & Coles (1997) 经典论文的完整模型。
5
+
6
+ 核心改进 vs 纯泊松:
7
+ 1. τ (tau) 低比分修正:0-0 / 0-1 / 1-0 / 1-1 比分在现实中
8
+ 比独立泊松分布出现频率更高,DC 模型用相关性项修正。
9
+ 2. ρ (rho) 参数:控制修正强度,典型值 -0.13 ~ -0.08。
10
+ 3. 时间权重:近期比赛权重更高(可选)。
11
+
12
+ τ 修正矩阵:
13
+ τ(x, y, λ, μ, ρ) =
14
+ 1 - λμρ if x=0, y=0
15
+ 1 + λρ if x=0, y=1
16
+ 1 + μρ if x=1, y=0
17
+ 1 - ρ if x=1, y=1
18
+ 1 otherwise
19
+
20
+ 参考文献: Dixon, M.J. & Coles, S.G. (1997).
21
+ "Modelling Association Football Scores and Inefficiencies in the
22
+ Football Betting Market." Applied Statistics, 46(2), 265-280.
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import math
28
+ from typing import Dict, List, Optional, Tuple
29
+
30
+
31
+ def _poisson_pmf(k: int, lam: float) -> float:
32
+ if lam <= 0:
33
+ return 1.0 if k == 0 else 0.0
34
+ return (lam ** k) * math.exp(-lam) / math.factorial(k)
35
+
36
+
37
+ def _nb_pmf(k: int, mu: float, r: float) -> float:
38
+ """
39
+ 负二项分布 PMF,均值 mu,离散参数 r。
40
+
41
+ 方差 = mu + mu²/r > mu(泊松)
42
+ 当 r→∞ 时退化为泊松分布。
43
+ r 越小,尾部越重(大比分概率越高)。
44
+ """
45
+ if mu <= 0:
46
+ return 1.0 if k == 0 else 0.0
47
+ p = r / (r + mu)
48
+ log_pmf = (
49
+ math.lgamma(k + r) - math.lgamma(r) - math.lgamma(k + 1)
50
+ + r * math.log(p)
51
+ + k * math.log(1.0 - p)
52
+ )
53
+ return math.exp(log_pmf)
54
+
55
+
56
+ def _auto_dispersion(elo_diff: float) -> float:
57
+ """
58
+ 根据 Elo 差距自动选择负二项离散参数 r。
59
+ 差距越大 → r 越小 → 尾部越重 → 大比分概率更高。
60
+
61
+ elo_diff=0 → r=80 (近似泊松)
62
+ elo_diff=200 → r=25
63
+ elo_diff=387 → r=13 (德国 vs 库拉索)
64
+ elo_diff=500 → r=10
65
+ """
66
+ r = max(6.0, 80.0 / (1.0 + abs(elo_diff) / 100.0))
67
+ return round(r, 1)
68
+
69
+
70
+ def tau_correction(
71
+ x: int,
72
+ y: int,
73
+ lambda_home: float,
74
+ lambda_away: float,
75
+ rho: float = -0.10,
76
+ ) -> float:
77
+ """
78
+ Dixon-Coles τ 修正因子。
79
+
80
+ rho < 0 意味着低比分(含 0 的)出现频率比独立泊松预测的更低,
81
+ 但 0-0 / 0-1 / 1-0 / 1-1 特别地有正相关(团队防守同进攻 jointly low)。
82
+ """
83
+ if x == 0 and y == 0:
84
+ return 1.0 - lambda_home * lambda_away * rho
85
+ if x == 0 and y == 1:
86
+ return 1.0 + lambda_home * rho
87
+ if x == 1 and y == 0:
88
+ return 1.0 + lambda_away * rho
89
+ if x == 1 and y == 1:
90
+ return 1.0 - rho
91
+ return 1.0
92
+
93
+
94
+ def predict_scoreline_matrix(
95
+ lambda_home: float,
96
+ lambda_away: float,
97
+ rho: float = -0.10,
98
+ max_goals: int = 10,
99
+ elo_diff: float = 0.0,
100
+ ) -> Dict[Tuple[int, int], float]:
101
+ """
102
+ 计算所有比分的概率矩阵。
103
+
104
+ 当 |elo_diff| > 150 时自动切换到负二项分布以处理大比分场景,
105
+ 否则使用标准泊松分布(DC 修正)。
106
+
107
+ Returns:
108
+ dict: {(home_goals, away_goals): probability},归一化为 1.0
109
+ """
110
+ use_nb = abs(elo_diff) > 150
111
+ if use_nb:
112
+ r_home = _auto_dispersion(elo_diff)
113
+ r_away = _auto_dispersion(-elo_diff)
114
+
115
+ raw: Dict[Tuple[int, int], float] = {}
116
+ for hg in range(max_goals):
117
+ ph = _nb_pmf(hg, lambda_home, r_home) if use_nb else _poisson_pmf(hg, lambda_home)
118
+ for ag in range(max_goals):
119
+ pa = _nb_pmf(ag, lambda_away, r_away) if use_nb else _poisson_pmf(ag, lambda_away)
120
+ tau = tau_correction(hg, ag, lambda_home, lambda_away, rho)
121
+ raw[(hg, ag)] = ph * pa * tau
122
+
123
+ total = sum(raw.values())
124
+ if total <= 0:
125
+ return raw
126
+ return {k: v / total for k, v in raw.items()}
127
+
128
+
129
+ def compute_match_probabilities(
130
+ lambda_home: float,
131
+ lambda_away: float,
132
+ rho: float = -0.10,
133
+ max_goals: int = 10,
134
+ elo_diff: float = 0.0,
135
+ ) -> Dict:
136
+ """
137
+ 从期望进球计算比赛结果概率(含 D-C 修正)。
138
+
139
+ Returns:
140
+ {
141
+ "home_win": float,
142
+ "draw": float,
143
+ "away_win": float,
144
+ "btts": float,
145
+ "over_2_5": float,
146
+ "top_scorelines": [...],
147
+ "score_matrix": {...},
148
+ }
149
+ """
150
+ matrix = predict_scoreline_matrix(lambda_home, lambda_away, rho, max_goals, elo_diff)
151
+
152
+ home_win = draw = away_win = 0.0
153
+ btts = 0.0
154
+ over_2_5 = 0.0
155
+
156
+ for (hg, ag), p in matrix.items():
157
+ if hg > ag:
158
+ home_win += p
159
+ elif hg == ag:
160
+ draw += p
161
+ else:
162
+ away_win += p
163
+ if hg > 0 and ag > 0:
164
+ btts += p
165
+ if hg + ag > 2:
166
+ over_2_5 += p
167
+
168
+ top_scores = sorted(matrix.items(), key=lambda x: -x[1])[:8]
169
+
170
+ return {
171
+ "home_win": round(home_win, 4),
172
+ "draw": round(draw, 4),
173
+ "away_win": round(away_win, 4),
174
+ "btts": round(btts, 4),
175
+ "over_2_5": round(over_2_5, 4),
176
+ "rho": rho,
177
+ "top_scorelines": [
178
+ {"score": f"{hg}-{ag}", "prob": round(p * 100, 2)}
179
+ for (hg, ag), p in top_scores
180
+ ],
181
+ "implied_odds": {
182
+ "home": round(1 / home_win, 2) if home_win > 0.01 else 99,
183
+ "draw": round(1 / draw, 2) if draw > 0.01 else 99,
184
+ "away": round(1 / away_win, 2) if away_win > 0.01 else 99,
185
+ },
186
+ }
187
+
188
+
189
+ def estimate_rho_from_results(match_results: List[Tuple[int, int]]) -> float:
190
+ """
191
+ 从历史赛果估计最优 ρ 参数(简化版 MLE 搜索)。
192
+
193
+ match_results: [(home_goals, away_goals), ...]
194
+ 返回: 最优 ρ(范围 -0.3 ~ 0.0)
195
+ """
196
+ if len(match_results) < 20:
197
+ return -0.10 # 数据不足,用默认值
198
+
199
+ def log_likelihood(rho: float) -> float:
200
+ ll = 0.0
201
+ for hg, ag in match_results:
202
+ # 用平均进球作简化 λ
203
+ lh = sum(h for h, _ in match_results) / len(match_results)
204
+ la = sum(a for _, a in match_results) / len(match_results)
205
+ p_h = _poisson_pmf(hg, lh)
206
+ p_a = _poisson_pmf(ag, la)
207
+ tau = tau_correction(hg, ag, lh, la, rho)
208
+ p = p_h * p_a * tau
209
+ if p > 0:
210
+ ll += math.log(p)
211
+ return ll
212
+
213
+ best_rho = -0.10
214
+ best_ll = float("-inf")
215
+ for rho_int in range(-30, 1, 2):
216
+ rho = rho_int / 100.0
217
+ ll = log_likelihood(rho)
218
+ if ll > best_ll:
219
+ best_ll = ll
220
+ best_rho = rho
221
+
222
+ return round(best_rho, 3)
223
+
224
+
225
+ def format_dc_result(result: Dict, home_cn: str, away_cn: str) -> str:
226
+ """格式化 Dixon-Coles 预测结果为 CLI 输出文本。"""
227
+ lines = [
228
+ f" 主队 {home_cn:<12} 获胜: {result['home_win']*100:5.1f}% 赔率: {result['implied_odds']['home']:5.2f}",
229
+ f" 平局 {result['draw']*100:5.1f}% 赔率: {result['implied_odds']['draw']:5.2f}",
230
+ f" 客队 {away_cn:<12} 获胜: {result['away_win']*100:5.1f}% 赔率: {result['implied_odds']['away']:5.2f}",
231
+ "",
232
+ f" 双方均进球 (BTTS): {result['btts']*100:.1f}% 大于2.5球: {result['over_2_5']*100:.1f}%",
233
+ ]
234
+ return "\n".join(lines)