feat: implement PolyWeather dashboard with map UI, data collection, analysis, and comprehensive documentation.
This commit is contained in:
@@ -46,9 +46,13 @@ This project uses a decoupled production setup for reliability and iteration spe
|
||||
- **City Specialization**: `17130` (`Ankara (Bölge/Center)`) remains the Ankara lead station without replacing LTAC settlement observation.
|
||||
- **⚖️ DEB Smart Blending**
|
||||
- Dynamic weighting based on city-level performance and current model spread.
|
||||
- **🧩 React Dashboard Runtime**
|
||||
- **📈 Market Data Integration**
|
||||
- Live Polymarket quotes, probabilities, and dynamic settlement bucket tracking.
|
||||
- Automatic Market Edge and Spread calculation comparing DEB vs Market.
|
||||
- **🧩 React Dashboard Runtime (v1.2)**
|
||||
- Fully internationalized (i18n) with English and Simplified Chinese support.
|
||||
- Premium UI: Glassmorphism overlays, dynamic "Sonar Pulse" markers, and fluid loading states.
|
||||
- Typed store + typed API client + Leaflet/Chart.js lifecycle wrappers.
|
||||
- City click workflow: map focus + right panel open + nearby stations render.
|
||||
- Today analysis workflow: open modal + freeze map motion.
|
||||
- **🔔 Alert Engine**
|
||||
- **Momentum Spike**: Captures rapid short-window temperature slope changes.
|
||||
@@ -140,12 +144,12 @@ Set `frontend` as the Vercel root directory for automatic CI/CD.
|
||||
|
||||
## 💬 Bot Commands
|
||||
|
||||
| Command | Description | Example |
|
||||
| :-------- | :-------------------------------------- | :------------- |
|
||||
| `/city` | Query real-time analysis for a city | `/city ankara` |
|
||||
| `/deb` | View historical accuracy of DEB model | `/deb london` |
|
||||
| `/top` | View activity leaderboard | `/top` |
|
||||
| `/help` | Get detailed instructions | `/help` |
|
||||
| Command | Description | Example |
|
||||
| :------ | :------------------------------------ | :------------- |
|
||||
| `/city` | Query real-time analysis for a city | `/city ankara` |
|
||||
| `/deb` | View historical accuracy of DEB model | `/deb london` |
|
||||
| `/top` | View activity leaderboard | `/top` |
|
||||
| `/help` | Get detailed instructions | `/help` |
|
||||
|
||||
---
|
||||
|
||||
@@ -161,8 +165,8 @@ Set `frontend` as the Vercel root directory for automatic CI/CD.
|
||||
|
||||
---
|
||||
|
||||
**📅 Last Updated**: 2026-03-09
|
||||
**🚀 Status**: v1.1 Stable - React Dashboard Runtime in Production
|
||||
**📅 Last Updated**: 2026-03-10
|
||||
**🚀 Status**: v1.2 Stable - React Dashboard with i18n & Polymarket Integration in Production
|
||||
|
||||
> [!TIP]
|
||||
> **Production Note**: The UI layout and visual contract remain unchanged while data flow, map lifecycle, and modal interaction are now managed by typed React modules.
|
||||
> **Production Note**: The UI layout remains consistent while introducing full internationalization, market quote integration, and premium visual feedback (glassmorphism overlays, sonar markers).
|
||||
|
||||
+15
-11
@@ -46,9 +46,13 @@ PolyWeather 是一套专为 **Polymarket** 深度博弈者设计的实时情报
|
||||
- **城市特化**:安卡拉保留 `17130`(`Ankara (Bölge/Center)`)领先站逻辑,不替代 LTAC 结算主站。
|
||||
- **⚖️ DEB 智能融合**
|
||||
- 基于城市历史表现与当前模型分歧动态调整权重。
|
||||
- **🧩 React 仪表盘运行时**
|
||||
- **📈 市场数据深度整合**
|
||||
- 实时接入 Polymarket 报价、结算概率及动态“最热温度桶”追踪。
|
||||
- 自动对比 DEB 与市场差值,计算 Edge 与点差。
|
||||
- **🧩 React 仪表盘运行时 (v1.2)**
|
||||
- 全面支持双语国际化 (i18n):英文与简体中文无缝切换。
|
||||
- 尊享版 UI:新增毛玻璃效果、动态 Sonar 脉冲标记及流畅的全屏加载动效。
|
||||
- 类型化 Store + 类型化 Data Client + Leaflet/Chart.js 生命周期封装。
|
||||
- 点击城市:地图聚焦 + 右侧卡片打开 + 周边站点展示。
|
||||
- 点击“今日日内分析”:打开模态框并冻结地图动画。
|
||||
- **🔔 异动预警系统**
|
||||
- **动量突变**:捕捉短窗口温度斜率变化。
|
||||
@@ -140,12 +144,12 @@ docker-compose up -d --build
|
||||
|
||||
## 💬 机器人指令
|
||||
|
||||
| 命令 | 说明 | 示例 |
|
||||
| :-------- | :------------------------ | :------------- |
|
||||
| `/city` | 查询指定城市实时分析 | `/city ankara` |
|
||||
| `/deb` | 查看 DEB 模型的历史准确率 | `/deb london` |
|
||||
| `/top` | 查看活跃积分排行榜 | `/top` |
|
||||
| `/help` | 获取详细功能说明 | `/help` |
|
||||
| 命令 | 说明 | 示例 |
|
||||
| :------ | :------------------------ | :------------- |
|
||||
| `/city` | 查询指定城市实时分析 | `/city ankara` |
|
||||
| `/deb` | 查看 DEB 模型的历史准确率 | `/deb london` |
|
||||
| `/top` | 查看活跃积分排行榜 | `/top` |
|
||||
| `/help` | 获取详细功能说明 | `/help` |
|
||||
|
||||
---
|
||||
|
||||
@@ -161,8 +165,8 @@ docker-compose up -d --build
|
||||
|
||||
---
|
||||
|
||||
**📅 最后更新**:2026-03-09
|
||||
**🚀 状态**:v1.1 稳定版 - React 运行时已上线
|
||||
**📅 最后更新**:2026-03-10
|
||||
**🚀 状态**:v1.2 稳定版 - 国际化及 Polymarket 市场层融合已上线
|
||||
|
||||
> [!TIP]
|
||||
> **生产提示**:在不改变既有 UI 布局与视觉层级的前提下,数据流、地图联动和模态行为已迁移到类型化 React 组件体系。
|
||||
> **生产提示**:在不改变既有 UI 布局的前提下,前端已全面引入国际化、市场报价集成及进阶视觉效果(如动态雷达标记、高级加载与毛玻璃控件)。
|
||||
|
||||
+3
-2
@@ -160,9 +160,10 @@
|
||||
- `primary_market`
|
||||
- `selected_condition_id`
|
||||
- `yes_token` / `no_token`
|
||||
- `yes_buy` / `yes_sell` / `no_buy` / `no_sell`
|
||||
- `yes_buy` / `yes_sell` / `no_buy` / `no_sell` / `model_probability`
|
||||
- `market_price`(优先 midpoint)
|
||||
- `edge_percent`(`(model_probability - market_price) * 100`)
|
||||
- `temperature_bucket` / `top_buckets` (结算温度桶及市场概率)
|
||||
- `signal_label`(`BUY YES` / `BUY NO` / `MONITOR`)
|
||||
- `websocket.asset_ids` / `websocket.condition_ids`(仅用于订阅标识,P0 不下单)
|
||||
|
||||
@@ -249,4 +250,4 @@
|
||||
|
||||
---
|
||||
|
||||
**最后更新**: 2026-03-09
|
||||
**最后更新**: 2026-03-10
|
||||
|
||||
@@ -12,11 +12,11 @@ PolyWeather is positioned as a **premium intelligence service** for weather-driv
|
||||
|
||||
## 💰 Pricing & Monetization
|
||||
|
||||
| Tier | Price | Primary Value Proposition |
|
||||
| :------------------- | :------------ | :------------------------------------------------------------ |
|
||||
| **Telegram Channel** | **$1 / mo** | High-fidelity proactive alerts, low noise. |
|
||||
| **Web Dashboard** | **$5 / mo** | Full multi-model context + historical DEB benchmarking. |
|
||||
| **VIP Bundle** | **$5.5 / mo** | Unified access to dashboard + signal stream. |
|
||||
| Tier | Price | Primary Value Proposition |
|
||||
| :------------------- | :------------ | :------------------------------------------------------ |
|
||||
| **Telegram Channel** | **$1 / mo** | High-fidelity proactive alerts, low noise. |
|
||||
| **Web Dashboard** | **$5 / mo** | Full multi-model context + historical DEB benchmarking. |
|
||||
| **VIP Bundle** | **$5.5 / mo** | Unified access to dashboard + signal stream. |
|
||||
|
||||
### 🛠️ Payment Infrastructure
|
||||
|
||||
@@ -92,4 +92,4 @@ graph LR
|
||||
|
||||
---
|
||||
|
||||
**📅 Last Updated**: 2026-03-09
|
||||
**📅 Last Updated**: 2026-03-10
|
||||
|
||||
+10
-9
@@ -22,7 +22,8 @@ The core weather engine and React dashboard runtime are now stable, but product-
|
||||
- [x] DEB Blending Algorithm
|
||||
- [x] Proactive Telegram Alert Engine
|
||||
- [x] Vercel Dashboard Infrastructure
|
||||
- [x] React component-driven dashboard runtime (replacing legacy `public/static/app.js` rendering path)
|
||||
- [x] React component-driven dashboard runtime
|
||||
- [x] Internationalization (i18n) & Polymarket P0 Data Merge
|
||||
|
||||
---
|
||||
|
||||
@@ -33,18 +34,18 @@ The core weather engine and React dashboard runtime are now stable, but product-
|
||||
| **Monolithic Bot** | `bot_listener.py` is hard to test and evolve. | Isolate UI interaction from business logic into `src/analysis`. |
|
||||
| **Subscription Store** | No persistent record of who has paid. | Migrate from in-memory user checks to **Supabase/PostgreSQL**. |
|
||||
| **Alert Transparency** | Operators cannot easily audit "why" an alert fired. | Add an `Evidence` metadata block to all internal alert payloads. |
|
||||
| **Entitlement Guard** | Dashboard routes are public by default. | Add JWT/session gating in Next.js middleware + backend checks. |
|
||||
| **Entitlement Guard** | Dashboard routes are public by default. | Add JWT/session gating in Next.js middleware + backend checks. |
|
||||
|
||||
---
|
||||
|
||||
## 🟡 Medium Priority: Quality of Life
|
||||
|
||||
| Debt Item | Impact | Suggested Fix |
|
||||
| :------------------------ | :-------------------------------------------------- | :--------------------------------------------------------------------------- |
|
||||
| **Hard-coded Thresholds** | Modification requires code changes (e.g., 5s CD). | Extract all business constants into a structured `config.yaml`. |
|
||||
| **Simulation Harness** | No way to "replay" a rainy day to test alert logic. | Build a `ReplayEngine` using `data/daily_records.json`. |
|
||||
| **Backend Naming** | Artifacts of "market price" logic remain in naming. | Systematic refactor of variable names to reflect weather-intelligence focus. |
|
||||
| **Chart Regression Tests**| UI relies on custom Chart.js lifecycles. | Add snapshot + interaction tests for chart datasets and legends. |
|
||||
| Debt Item | Impact | Suggested Fix |
|
||||
| :------------------------- | :-------------------------------------------------- | :--------------------------------------------------------------------------- |
|
||||
| **Hard-coded Thresholds** | Modification requires code changes (e.g., 5s CD). | Extract all business constants into a structured `config.yaml`. |
|
||||
| **Simulation Harness** | No way to "replay" a rainy day to test alert logic. | Build a `ReplayEngine` using `data/daily_records.json`. |
|
||||
| **Backend Naming** | Artifacts of "market price" logic remain in naming. | Systematic refactor of variable names to reflect weather-intelligence focus. |
|
||||
| **Chart Regression Tests** | UI relies on custom Chart.js lifecycles. | Add snapshot + interaction tests for chart datasets and legends. |
|
||||
|
||||
---
|
||||
|
||||
@@ -66,4 +67,4 @@ The core weather engine and React dashboard runtime are now stable, but product-
|
||||
|
||||
---
|
||||
|
||||
**📅 Last Updated**: 2026-03-09
|
||||
**📅 Last Updated**: 2026-03-10
|
||||
|
||||
+19
-18
@@ -22,38 +22,39 @@ pie title 系统健康度与技术债
|
||||
- [x] DEB 融合算法
|
||||
- [x] 主动式 Telegram 预警引擎
|
||||
- [x] Vercel 仪表盘基础设施
|
||||
- [x] React 组件驱动仪表盘运行时(已替换 legacy `public/static/app.js` 渲染路径)
|
||||
- [x] React 组件驱动仪表盘运行时
|
||||
- [x] 国际化 (i18n) 与前端市场数据集成 (Polymarket)
|
||||
|
||||
---
|
||||
|
||||
## 🔴 高优先级:立即处理
|
||||
|
||||
| 债务项 | 影响 | 建议修复 |
|
||||
| :-------------------- | :------------------------------------------------- | :--------------------------------------------------------------- |
|
||||
| **Monolithic Bot** | `bot_listener.py` 可测试性差,演进成本高。 | 将 UI 交互与业务逻辑解耦,沉入 `src/analysis`。 |
|
||||
| **Subscription Store**| 付费用户缺少持久化记录。 | 从内存校验迁移到 **Supabase/PostgreSQL**。 |
|
||||
| **Alert Transparency**| 运维侧难以审计“告警为何触发”。 | 为所有内部告警载荷增加 `Evidence` 元数据块。 |
|
||||
| **Entitlement Guard** | 仪表盘路由默认仍是公开可访问。 | 在 Next.js middleware 与后端校验中加入 JWT/会话权限守卫。 |
|
||||
| 债务项 | 影响 | 建议修复 |
|
||||
| :--------------------- | :----------------------------------------- | :-------------------------------------------------------- |
|
||||
| **Monolithic Bot** | `bot_listener.py` 可测试性差,演进成本高。 | 将 UI 交互与业务逻辑解耦,沉入 `src/analysis`。 |
|
||||
| **Subscription Store** | 付费用户缺少持久化记录。 | 从内存校验迁移到 **Supabase/PostgreSQL**。 |
|
||||
| **Alert Transparency** | 运维侧难以审计“告警为何触发”。 | 为所有内部告警载荷增加 `Evidence` 元数据块。 |
|
||||
| **Entitlement Guard** | 仪表盘路由默认仍是公开可访问。 | 在 Next.js middleware 与后端校验中加入 JWT/会话权限守卫。 |
|
||||
|
||||
---
|
||||
|
||||
## 🟡 中优先级:体验与效率
|
||||
|
||||
| 债务项 | 影响 | 建议修复 |
|
||||
| :---------------------- | :------------------------------------------------- | :---------------------------------------------------------------------- |
|
||||
| **Hard-coded Thresholds** | 阈值修改需要改代码(如 5s 冷却)。 | 将业务常量统一抽离到结构化 `config.yaml`。 |
|
||||
| **Simulation Harness** | 无法“回放历史天气日”验证告警逻辑。 | 基于 `data/daily_records.json` 构建 `ReplayEngine`。 |
|
||||
| **Backend Naming** | 仍有“市场价格时代”的命名残留。 | 系统化重命名,统一为 weather-intelligence 语义。 |
|
||||
| **Chart Regression Tests**| 图表依赖自定义 Chart.js 生命周期,回归风险高。 | 增加图表数据集与图例的快照测试 + 交互测试。 |
|
||||
| 债务项 | 影响 | 建议修复 |
|
||||
| :------------------------- | :--------------------------------------------- | :--------------------------------------------------- |
|
||||
| **Hard-coded Thresholds** | 阈值修改需要改代码(如 5s 冷却)。 | 将业务常量统一抽离到结构化 `config.yaml`。 |
|
||||
| **Simulation Harness** | 无法“回放历史天气日”验证告警逻辑。 | 基于 `data/daily_records.json` 构建 `ReplayEngine`。 |
|
||||
| **Backend Naming** | 仍有“市场价格时代”的命名残留。 | 系统化重命名,统一为 weather-intelligence 语义。 |
|
||||
| **Chart Regression Tests** | 图表依赖自定义 Chart.js 生命周期,回归风险高。 | 增加图表数据集与图例的快照测试 + 交互测试。 |
|
||||
|
||||
---
|
||||
|
||||
## 🟢 低优先级:性能优化
|
||||
|
||||
| 债务项 | 影响 | 建议修复 |
|
||||
| :----------------------- | :------------------------------------------------- | :--------------------------------------------------------------- |
|
||||
| **Serverless Cold Starts** | Vercel 首次 API 调用可能偏慢。 | 为主要城市接口增加边缘缓存或预热任务。 |
|
||||
| **Local SQLite Files** | 与 Vercel 短暂文件系统不兼容。 | 全面迁移到远程数据库(Supabase/Redis)。 |
|
||||
| 债务项 | 影响 | 建议修复 |
|
||||
| :------------------------- | :----------------------------- | :--------------------------------------- |
|
||||
| **Serverless Cold Starts** | Vercel 首次 API 调用可能偏慢。 | 为主要城市接口增加边缘缓存或预热任务。 |
|
||||
| **Local SQLite Files** | 与 Vercel 短暂文件系统不兼容。 | 全面迁移到远程数据库(Supabase/Redis)。 |
|
||||
|
||||
---
|
||||
|
||||
@@ -66,4 +67,4 @@ pie title 系统健康度与技术债
|
||||
|
||||
---
|
||||
|
||||
**📅 最后更新**:2026-03-09
|
||||
**📅 最后更新**:2026-03-10
|
||||
|
||||
@@ -33,7 +33,7 @@
|
||||
/* Spacing */
|
||||
--panel-width: 560px;
|
||||
--header-height: 56px;
|
||||
--sidebar-width: 280px;
|
||||
--sidebar-width: 260px;
|
||||
|
||||
/* Effects */
|
||||
--glass-blur: 20px;
|
||||
@@ -328,6 +328,7 @@
|
||||
}
|
||||
|
||||
.root :global(.city-item) {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 4px;
|
||||
@@ -336,6 +337,10 @@
|
||||
cursor: pointer;
|
||||
transition: var(--transition);
|
||||
border: 1px solid transparent;
|
||||
background: transparent;
|
||||
color: inherit;
|
||||
font-family: inherit;
|
||||
text-align: left;
|
||||
}
|
||||
.root :global(.city-item:hover) {
|
||||
background: rgba(99, 102, 241, 0.08);
|
||||
@@ -722,6 +727,29 @@
|
||||
background: rgba(99, 102, 241, 0.15);
|
||||
}
|
||||
|
||||
.root :global(.prob-market-inline) {
|
||||
min-width: 120px;
|
||||
text-align: right;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
border-radius: 999px;
|
||||
padding: 4px 10px;
|
||||
letter-spacing: 0.02em;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.root :global(.prob-market-inline.yes) {
|
||||
color: #4ade80;
|
||||
background: rgba(74, 222, 128, 0.12);
|
||||
border: 1px solid rgba(74, 222, 128, 0.3);
|
||||
}
|
||||
|
||||
.root :global(.prob-market-inline.no) {
|
||||
color: #fb7185;
|
||||
background: rgba(251, 113, 133, 0.12);
|
||||
border: 1px solid rgba(251, 113, 133, 0.26);
|
||||
}
|
||||
|
||||
/* ── Model Bars ── */
|
||||
.root :global(.model-bars) {
|
||||
display: flex;
|
||||
@@ -1386,6 +1414,41 @@
|
||||
color: var(--text-primary);
|
||||
margin: 0;
|
||||
}
|
||||
.root :global(.future-modal-title-with-actions) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.root :global(.future-refresh-btn) {
|
||||
background: transparent;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
color: var(--text-muted);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 6px;
|
||||
border-radius: 6px;
|
||||
transition: all 0.2s ease;
|
||||
}
|
||||
|
||||
.root :global(.future-refresh-btn:hover) {
|
||||
color: var(--accent-cyan);
|
||||
background: rgba(34, 211, 238, 0.1);
|
||||
}
|
||||
|
||||
.root :global(.future-refresh-btn.spinning svg) {
|
||||
animation: spin 1s linear infinite;
|
||||
color: var(--accent-cyan);
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
100% {
|
||||
transform: rotate(360deg);
|
||||
}
|
||||
}
|
||||
|
||||
.root :global(.modal-close) {
|
||||
background: none;
|
||||
border: none;
|
||||
@@ -1435,6 +1498,14 @@
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
||||
.root :global(.h-stat-card .h-stat-note) {
|
||||
display: block;
|
||||
margin-top: 6px;
|
||||
font-size: 11px;
|
||||
color: var(--text-muted);
|
||||
line-height: 1.35;
|
||||
}
|
||||
|
||||
.root :global(.history-chart-wrapper) {
|
||||
position: relative;
|
||||
height: 300px;
|
||||
@@ -1551,6 +1622,301 @@
|
||||
padding-right: 14px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-layout) {
|
||||
display: grid;
|
||||
grid-template-columns: 360px minmax(0, 1fr);
|
||||
gap: 14px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-left) {
|
||||
display: grid;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-right) {
|
||||
display: grid;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-card) {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border: 1px solid var(--border-subtle);
|
||||
border-radius: 14px;
|
||||
padding: 14px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-hero-card) {
|
||||
background: linear-gradient(
|
||||
180deg,
|
||||
rgba(99, 102, 241, 0.12) 0%,
|
||||
rgba(255, 255, 255, 0.02) 100%
|
||||
);
|
||||
}
|
||||
|
||||
.root :global(.future-v2-hero-title) {
|
||||
margin: 0;
|
||||
font-size: 18px;
|
||||
font-weight: 700;
|
||||
color: var(--text-primary);
|
||||
letter-spacing: -0.01em;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-hero-main) {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 14px;
|
||||
margin-top: 14px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-hero-temp) {
|
||||
font-size: 56px;
|
||||
font-weight: 800;
|
||||
letter-spacing: -0.04em;
|
||||
line-height: 1;
|
||||
color: #f8fafc;
|
||||
text-shadow: 0 10px 30px rgba(34, 211, 238, 0.14);
|
||||
}
|
||||
|
||||
.root :global(.future-v2-hero-divider) {
|
||||
width: 1px;
|
||||
height: 56px;
|
||||
background: rgba(255, 255, 255, 0.12);
|
||||
}
|
||||
|
||||
.root :global(.future-v2-hero-weather) {
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
font-size: 15px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.root :global(.future-v2-hero-icon) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-hero-obs) {
|
||||
margin-top: 10px;
|
||||
color: var(--text-secondary);
|
||||
font-size: 26px;
|
||||
font-weight: 500;
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-mini-grid) {
|
||||
margin-top: 14px;
|
||||
display: grid;
|
||||
grid-template-columns: repeat(2, minmax(0, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-mini-grid.future-v2-mini-grid-tight) {
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-mini-item) {
|
||||
border-radius: 10px;
|
||||
border: 1px solid var(--border-subtle);
|
||||
background: rgba(255, 255, 255, 0.025);
|
||||
padding: 10px;
|
||||
display: grid;
|
||||
gap: 4px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-mini-item span) {
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-mini-item strong) {
|
||||
color: var(--text-primary);
|
||||
font-size: 23px;
|
||||
line-height: 1.15;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-card-title) {
|
||||
margin: 0;
|
||||
color: var(--text-primary);
|
||||
font-size: 13px;
|
||||
font-weight: 700;
|
||||
letter-spacing: 0.02em;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-market-v3) {
|
||||
margin-top: 16px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 16px;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.root :global(.market-layer-loading-overlay) {
|
||||
position: absolute;
|
||||
top: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
bottom: 0;
|
||||
background: rgba(15, 23, 42, 0.6);
|
||||
backdrop-filter: blur(2px);
|
||||
z-index: 10;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
border-radius: 8px;
|
||||
color: var(--accent-cyan);
|
||||
font-size: 13px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.root :global(.market-sub-title) {
|
||||
color: var(--text-secondary);
|
||||
font-size: 11px;
|
||||
text-transform: uppercase;
|
||||
letter-spacing: 0.05em;
|
||||
margin-bottom: 8px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.root :global(.market-layer-target) {
|
||||
background: rgba(34, 211, 238, 0.04);
|
||||
border: 1px solid rgba(34, 211, 238, 0.15);
|
||||
border-radius: 8px;
|
||||
padding: 12px;
|
||||
}
|
||||
|
||||
.root :global(.market-target-header) {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 12px;
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.root :global(.market-target-bucket) {
|
||||
font-size: 16px;
|
||||
color: var(--text-primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.root :global(.market-edge-box) {
|
||||
background: rgba(15, 23, 42, 0.4);
|
||||
border-radius: 6px;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
.root :global(.market-edge-header) {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
margin-bottom: 8px;
|
||||
font-size: 12px;
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.root :global(.market-edge-val) {
|
||||
font-size: 15px;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.root :global(.market-edge-val.positive) {
|
||||
color: var(--accent-green);
|
||||
}
|
||||
|
||||
.root :global(.market-edge-val.negative) {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.root :global(.market-edge-compare) {
|
||||
display: grid;
|
||||
grid-template-columns: 1fr 1fr;
|
||||
gap: 8px;
|
||||
border-top: 1px solid rgba(255, 255, 255, 0.06);
|
||||
padding-top: 8px;
|
||||
}
|
||||
|
||||
.root :global(.edge-stat) {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.root :global(.edge-label) {
|
||||
font-size: 10px;
|
||||
color: var(--text-muted);
|
||||
}
|
||||
|
||||
.root :global(.edge-value) {
|
||||
font-size: 13px;
|
||||
color: var(--text-secondary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.root :global(.market-layer-book),
|
||||
.root :global(.market-layer-context) {
|
||||
padding: 0 4px;
|
||||
}
|
||||
|
||||
.root :global(.market-book-row),
|
||||
.root :global(.market-context-row) {
|
||||
display: flex;
|
||||
justify-content: space-between;
|
||||
align-items: center;
|
||||
font-size: 13px;
|
||||
padding: 6px 0;
|
||||
border-bottom: 1px dashed rgba(255, 255, 255, 0.05);
|
||||
}
|
||||
|
||||
.root :global(.market-book-row:last-child),
|
||||
.root :global(.market-context-row:last-child) {
|
||||
border-bottom: none;
|
||||
}
|
||||
|
||||
.root :global(.book-label),
|
||||
.root :global(.market-context-row span) {
|
||||
color: var(--text-secondary);
|
||||
}
|
||||
|
||||
.root :global(.book-quote strong),
|
||||
.root :global(.market-context-row strong) {
|
||||
color: var(--text-primary);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.root :global(.book-quote span) {
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.root :global(.book-spread) {
|
||||
color: var(--text-muted);
|
||||
font-size: 11px;
|
||||
}
|
||||
|
||||
.root :global(.mt-3) {
|
||||
margin-top: 12px;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-market-signal) {
|
||||
margin-top: 10px;
|
||||
padding: 8px 10px;
|
||||
border-radius: 10px;
|
||||
background: rgba(34, 211, 238, 0.08);
|
||||
border: 1px solid rgba(34, 211, 238, 0.22);
|
||||
color: var(--accent-cyan);
|
||||
font-size: 12px;
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-main-chart) {
|
||||
min-height: 340px;
|
||||
}
|
||||
|
||||
.root :global(.future-modal-section) {
|
||||
background: rgba(255, 255, 255, 0.02);
|
||||
border: 1px solid var(--border-subtle);
|
||||
@@ -1660,9 +2026,12 @@
|
||||
border-radius: 999px;
|
||||
background: linear-gradient(
|
||||
90deg,
|
||||
rgba(245, 158, 11, 0.35),
|
||||
rgba(255, 255, 255, 0.06) 50%,
|
||||
rgba(52, 211, 153, 0.35)
|
||||
rgba(56, 189, 248, 0.4) 0%,
|
||||
rgba(56, 189, 248, 0.4) 30%,
|
||||
rgba(255, 255, 255, 0.06) 45%,
|
||||
rgba(255, 255, 255, 0.06) 55%,
|
||||
rgba(245, 158, 11, 0.4) 70%,
|
||||
rgba(245, 158, 11, 0.4) 100%
|
||||
);
|
||||
overflow: hidden;
|
||||
}
|
||||
@@ -1675,9 +2044,11 @@
|
||||
width: 14px;
|
||||
height: 14px;
|
||||
border-radius: 999px;
|
||||
background: var(--accent-cyan);
|
||||
background: var(--text-primary);
|
||||
transform: translate(-50%, -50%);
|
||||
box-shadow: 0 0 0 4px rgba(34, 211, 238, 0.14);
|
||||
box-shadow: 0 0 0 3px rgba(255, 255, 255, 0.15);
|
||||
z-index: 2;
|
||||
transition: left 0.5s ease;
|
||||
}
|
||||
|
||||
.root :global(.future-front-meta) {
|
||||
@@ -1699,6 +2070,14 @@
|
||||
}
|
||||
|
||||
@media (max-width: 960px) {
|
||||
.root :global(.future-v2-layout) {
|
||||
grid-template-columns: 1fr;
|
||||
}
|
||||
|
||||
.root :global(.future-v2-mini-item strong) {
|
||||
font-size: 18px;
|
||||
}
|
||||
|
||||
.root :global(.future-modal-grid),
|
||||
.root :global(.future-trend-grid) {
|
||||
grid-template-columns: 1fr;
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -5,7 +5,12 @@ import clsx from "clsx";
|
||||
import { useChart } from "@/hooks/useChart";
|
||||
import { useCityData, useDashboardStore } from "@/hooks/useDashboardStore";
|
||||
import { useI18n } from "@/hooks/useI18n";
|
||||
import { CityDetail } from "@/lib/dashboard-types";
|
||||
import {
|
||||
CityDetail,
|
||||
MarketScan,
|
||||
MarketTopBucket,
|
||||
ProbabilityBucket,
|
||||
} from "@/lib/dashboard-types";
|
||||
import {
|
||||
getHeroMetaItems,
|
||||
getModelView,
|
||||
@@ -17,7 +22,101 @@ import {
|
||||
} from "@/lib/dashboard-utils";
|
||||
|
||||
function EmptyState({ text }: { text: string }) {
|
||||
return <div style={{ color: "var(--text-muted)", fontSize: "13px" }}>{text}</div>;
|
||||
return (
|
||||
<div style={{ color: "var(--text-muted)", fontSize: "13px" }}>{text}</div>
|
||||
);
|
||||
}
|
||||
|
||||
function toPercent(value?: number | null) {
|
||||
const numeric = Number(value);
|
||||
if (!Number.isFinite(numeric)) return null;
|
||||
return `${(numeric * 100).toFixed(1)}%`;
|
||||
}
|
||||
|
||||
function toPriceCents(value?: number | null) {
|
||||
const numeric = Number(value);
|
||||
if (!Number.isFinite(numeric)) return null;
|
||||
const normalized = numeric > 1 ? numeric / 100 : numeric;
|
||||
const cents = normalized * 100;
|
||||
const rounded = Math.round(cents * 10) / 10;
|
||||
const text = Number.isInteger(rounded)
|
||||
? String(rounded.toFixed(0))
|
||||
: String(rounded);
|
||||
return `${text}c`;
|
||||
}
|
||||
|
||||
function parseTempFromText(value: unknown) {
|
||||
const text = String(value || "");
|
||||
const match = text.match(/(-?\d+(?:\.\d+)?)/);
|
||||
if (!match) return null;
|
||||
const numeric = Number(match[1]);
|
||||
return Number.isFinite(numeric) ? numeric : null;
|
||||
}
|
||||
|
||||
function getBucketTemp(bucket: ProbabilityBucket) {
|
||||
const byValue = Number(bucket.value);
|
||||
if (Number.isFinite(byValue)) return byValue;
|
||||
return parseTempFromText(bucket.label || bucket.bucket || bucket.range);
|
||||
}
|
||||
|
||||
function getMarketBucketTemp(scan?: MarketScan | null) {
|
||||
if (!scan) return null;
|
||||
|
||||
const byBucketValue = Number(scan.temperature_bucket?.value);
|
||||
if (Number.isFinite(byBucketValue)) return byBucketValue;
|
||||
|
||||
const byBucketLabel = parseTempFromText(
|
||||
scan.temperature_bucket?.label ||
|
||||
scan.temperature_bucket?.bucket ||
|
||||
scan.temperature_bucket?.range,
|
||||
);
|
||||
if (byBucketLabel != null) return byBucketLabel;
|
||||
|
||||
const slug = String(scan.selected_slug || scan.primary_market?.slug || "");
|
||||
const slugMatch = slug.match(/-(-?\d+(?:\.\d+)?)c(?:$|[^a-z0-9])/i);
|
||||
if (slugMatch) {
|
||||
const numeric = Number(slugMatch[1]);
|
||||
if (Number.isFinite(numeric)) return numeric;
|
||||
}
|
||||
|
||||
return parseTempFromText(scan.primary_market?.question);
|
||||
}
|
||||
|
||||
function getMarketYesPrice(scan?: MarketScan | null) {
|
||||
const preferred = Number(scan?.market_price);
|
||||
if (Number.isFinite(preferred)) return preferred;
|
||||
const implied = Number(scan?.yes_token?.implied_probability);
|
||||
return Number.isFinite(implied) ? implied : null;
|
||||
}
|
||||
|
||||
function getMarketNoPrice(scan?: MarketScan | null) {
|
||||
const direct = Number(scan?.no_buy);
|
||||
if (Number.isFinite(direct)) return direct;
|
||||
const marketYes = getMarketYesPrice(scan);
|
||||
if (marketYes != null) return Math.max(0, Math.min(1, 1 - marketYes));
|
||||
return null;
|
||||
}
|
||||
|
||||
function normalizeMarketProbability(value?: number | null) {
|
||||
const numeric = Number(value);
|
||||
if (!Number.isFinite(numeric)) return null;
|
||||
if (numeric > 1) return Math.max(0, Math.min(1, numeric / 100));
|
||||
return Math.max(0, Math.min(1, numeric));
|
||||
}
|
||||
|
||||
function getMarketTopBuckets(scan?: MarketScan | null) {
|
||||
const buckets = Array.isArray(scan?.top_buckets) ? scan.top_buckets : [];
|
||||
if (!buckets.length) return [];
|
||||
|
||||
return buckets
|
||||
.map((item) => ({
|
||||
...item,
|
||||
probability: normalizeMarketProbability(item.probability),
|
||||
}))
|
||||
.filter(
|
||||
(item): item is MarketTopBucket & { probability: number } =>
|
||||
item.probability != null,
|
||||
);
|
||||
}
|
||||
|
||||
export function HeroSummary() {
|
||||
@@ -55,7 +154,9 @@ export function HeroSummary() {
|
||||
</div>
|
||||
<div className="hero-details">
|
||||
<div className="hero-item">
|
||||
<span className="label">{locale === "en-US" ? "Current Obs" : "当前实测"}</span>
|
||||
<span className="label">
|
||||
{locale === "en-US" ? "Current Obs" : "当前实测"}
|
||||
</span>
|
||||
<span className="value">
|
||||
{current.temp != null
|
||||
? `${current.temp}${data.temp_symbol} @${current.obs_time || "--"}`
|
||||
@@ -73,7 +174,9 @@ export function HeroSummary() {
|
||||
</span>
|
||||
</div>
|
||||
<div className="hero-item">
|
||||
<span className="label">{locale === "en-US" ? "DEB Forecast" : "DEB 预测"}</span>
|
||||
<span className="label">
|
||||
{locale === "en-US" ? "DEB Forecast" : "DEB 预测"}
|
||||
</span>
|
||||
<span className="value">
|
||||
{data.deb?.prediction != null
|
||||
? `${data.deb.prediction}${data.temp_symbol}`
|
||||
@@ -95,142 +198,141 @@ export function TemperatureChart() {
|
||||
const { locale, t } = useI18n();
|
||||
const chartData = data ? getTemperatureChartData(data, locale) : null;
|
||||
|
||||
const canvasRef = useChart(
|
||||
() => {
|
||||
if (!data || !chartData) {
|
||||
return {
|
||||
data: { datasets: [], labels: [] },
|
||||
type: "line",
|
||||
} satisfies ChartConfiguration<"line">;
|
||||
}
|
||||
|
||||
const datasets: NonNullable<ChartConfiguration<"line">["data"]>["datasets"] = [];
|
||||
|
||||
if (chartData.datasets.hasMgmHourly) {
|
||||
datasets.push({
|
||||
backgroundColor: "rgba(234, 179, 8, 0.05)",
|
||||
borderColor: "rgba(234, 179, 8, 0.8)",
|
||||
borderWidth: 2,
|
||||
data: chartData.datasets.mgmHourlyPoints,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "MGM Forecast" : "MGM 预报",
|
||||
pointHoverRadius: 6,
|
||||
pointRadius: 3,
|
||||
spanGaps: true,
|
||||
tension: 0.3,
|
||||
});
|
||||
} else {
|
||||
datasets.push({
|
||||
backgroundColor: "rgba(52, 211, 153, 0.05)",
|
||||
borderColor: "rgba(52, 211, 153, 0.6)",
|
||||
borderWidth: 1.5,
|
||||
data: chartData.datasets.debPast,
|
||||
fill: true,
|
||||
label: locale === "en-US" ? "DEB Forecast" : "DEB 预报",
|
||||
pointHoverRadius: 3,
|
||||
pointRadius: 0,
|
||||
tension: 0.3,
|
||||
});
|
||||
datasets.push({
|
||||
borderColor: "rgba(52, 211, 153, 0.35)",
|
||||
borderDash: [5, 3],
|
||||
borderWidth: 1.5,
|
||||
data: chartData.datasets.debFuture,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "DEB Forecast" : "DEB 预报",
|
||||
pointRadius: 0,
|
||||
tension: 0.3,
|
||||
});
|
||||
}
|
||||
|
||||
datasets.push({
|
||||
backgroundColor: "#22d3ee",
|
||||
borderColor: "#22d3ee",
|
||||
borderWidth: 0,
|
||||
data: chartData.datasets.metarPoints,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "METAR Observation" : "METAR 实测",
|
||||
order: 0,
|
||||
pointHoverRadius: 7,
|
||||
pointRadius: 5,
|
||||
});
|
||||
|
||||
if (chartData.datasets.mgmPoints.some((value) => value != null)) {
|
||||
datasets.push({
|
||||
backgroundColor: "#facc15",
|
||||
borderColor: "#facc15",
|
||||
borderWidth: 0,
|
||||
data: chartData.datasets.mgmPoints,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "MGM Observation" : "MGM 实测",
|
||||
order: -1,
|
||||
pointHoverRadius: 9,
|
||||
pointRadius: 7,
|
||||
showLine: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
!chartData.datasets.hasMgmHourly &&
|
||||
Math.abs(chartData.datasets.offset) > 0.3
|
||||
) {
|
||||
datasets.push({
|
||||
borderColor: "rgba(99, 102, 241, 0.2)",
|
||||
borderDash: [2, 4],
|
||||
borderWidth: 1,
|
||||
data: chartData.datasets.temps,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "OM Raw" : "OM 原始",
|
||||
pointRadius: 0,
|
||||
tension: 0.3,
|
||||
});
|
||||
}
|
||||
|
||||
const canvasRef = useChart(() => {
|
||||
if (!data || !chartData) {
|
||||
return {
|
||||
data: {
|
||||
datasets,
|
||||
labels: chartData.times,
|
||||
},
|
||||
options: {
|
||||
interaction: { intersect: false, mode: "index" },
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
backgroundColor: "rgba(15, 23, 42, 0.9)",
|
||||
borderColor: "rgba(52, 211, 153, 0.3)",
|
||||
borderWidth: 1,
|
||||
},
|
||||
},
|
||||
responsive: true,
|
||||
scales: {
|
||||
x: {
|
||||
grid: { color: "rgba(255,255,255,0.04)" },
|
||||
ticks: {
|
||||
callback: (_value, index) =>
|
||||
typeof index === "number" && index % 3 === 0
|
||||
? chartData.times[index]
|
||||
: "",
|
||||
color: "#64748b",
|
||||
maxRotation: 0,
|
||||
},
|
||||
},
|
||||
y: {
|
||||
grid: { color: "rgba(255,255,255,0.04)" },
|
||||
max: chartData.max,
|
||||
min: chartData.min,
|
||||
ticks: {
|
||||
callback: (value) => `${value}${data.temp_symbol || "°C"}`,
|
||||
color: "#64748b",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
data: { datasets: [], labels: [] },
|
||||
type: "line",
|
||||
} satisfies ChartConfiguration<"line">;
|
||||
},
|
||||
[data, chartData, locale],
|
||||
);
|
||||
}
|
||||
|
||||
const datasets: NonNullable<
|
||||
ChartConfiguration<"line">["data"]
|
||||
>["datasets"] = [];
|
||||
|
||||
if (chartData.datasets.hasMgmHourly) {
|
||||
datasets.push({
|
||||
backgroundColor: "rgba(234, 179, 8, 0.05)",
|
||||
borderColor: "rgba(234, 179, 8, 0.8)",
|
||||
borderWidth: 2,
|
||||
data: chartData.datasets.mgmHourlyPoints,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "MGM Forecast" : "MGM 预报",
|
||||
pointHoverRadius: 6,
|
||||
pointRadius: 3,
|
||||
spanGaps: true,
|
||||
tension: 0.3,
|
||||
});
|
||||
} else {
|
||||
datasets.push({
|
||||
backgroundColor: "rgba(52, 211, 153, 0.05)",
|
||||
borderColor: "rgba(52, 211, 153, 0.6)",
|
||||
borderWidth: 1.5,
|
||||
data: chartData.datasets.debPast,
|
||||
fill: true,
|
||||
label: locale === "en-US" ? "DEB Forecast" : "DEB 预报",
|
||||
pointHoverRadius: 3,
|
||||
pointRadius: 0,
|
||||
tension: 0.3,
|
||||
});
|
||||
datasets.push({
|
||||
borderColor: "rgba(52, 211, 153, 0.35)",
|
||||
borderDash: [5, 3],
|
||||
borderWidth: 1.5,
|
||||
data: chartData.datasets.debFuture,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "DEB Forecast" : "DEB 预报",
|
||||
pointRadius: 0,
|
||||
tension: 0.3,
|
||||
});
|
||||
}
|
||||
|
||||
datasets.push({
|
||||
backgroundColor: "#22d3ee",
|
||||
borderColor: "#22d3ee",
|
||||
borderWidth: 0,
|
||||
data: chartData.datasets.metarPoints,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "METAR Observation" : "METAR 实测",
|
||||
order: 0,
|
||||
pointHoverRadius: 7,
|
||||
pointRadius: 5,
|
||||
});
|
||||
|
||||
if (chartData.datasets.mgmPoints.some((value) => value != null)) {
|
||||
datasets.push({
|
||||
backgroundColor: "#facc15",
|
||||
borderColor: "#facc15",
|
||||
borderWidth: 0,
|
||||
data: chartData.datasets.mgmPoints,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "MGM Observation" : "MGM 实测",
|
||||
order: -1,
|
||||
pointHoverRadius: 9,
|
||||
pointRadius: 7,
|
||||
showLine: false,
|
||||
});
|
||||
}
|
||||
|
||||
if (
|
||||
!chartData.datasets.hasMgmHourly &&
|
||||
Math.abs(chartData.datasets.offset) > 0.3
|
||||
) {
|
||||
datasets.push({
|
||||
borderColor: "rgba(99, 102, 241, 0.2)",
|
||||
borderDash: [2, 4],
|
||||
borderWidth: 1,
|
||||
data: chartData.datasets.temps,
|
||||
fill: false,
|
||||
label: locale === "en-US" ? "OM Raw" : "OM 原始",
|
||||
pointRadius: 0,
|
||||
tension: 0.3,
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
data: {
|
||||
datasets,
|
||||
labels: chartData.times,
|
||||
},
|
||||
options: {
|
||||
interaction: { intersect: false, mode: "index" },
|
||||
maintainAspectRatio: false,
|
||||
plugins: {
|
||||
legend: { display: false },
|
||||
tooltip: {
|
||||
backgroundColor: "rgba(15, 23, 42, 0.9)",
|
||||
borderColor: "rgba(52, 211, 153, 0.3)",
|
||||
borderWidth: 1,
|
||||
},
|
||||
},
|
||||
responsive: true,
|
||||
scales: {
|
||||
x: {
|
||||
grid: { color: "rgba(255,255,255,0.04)" },
|
||||
ticks: {
|
||||
callback: (_value, index) =>
|
||||
typeof index === "number" && index % 3 === 0
|
||||
? chartData.times[index]
|
||||
: "",
|
||||
color: "#64748b",
|
||||
maxRotation: 0,
|
||||
},
|
||||
},
|
||||
y: {
|
||||
grid: { color: "rgba(255,255,255,0.04)" },
|
||||
max: chartData.max,
|
||||
min: chartData.min,
|
||||
ticks: {
|
||||
callback: (value) => `${value}${data.temp_symbol || "°C"}`,
|
||||
color: "#64748b",
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
type: "line",
|
||||
} satisfies ChartConfiguration<"line">;
|
||||
}, [data, chartData, locale]);
|
||||
|
||||
return (
|
||||
<section className="chart-section">
|
||||
@@ -238,7 +340,9 @@ export function TemperatureChart() {
|
||||
<div className="chart-wrapper">
|
||||
<canvas ref={canvasRef} />
|
||||
</div>
|
||||
<div className="chart-legend">{chartData?.legendText || t("section.chartEmpty")}</div>
|
||||
<div className="chart-legend">
|
||||
{chartData?.legendText || t("section.chartEmpty")}
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -247,13 +351,28 @@ export function ProbabilityDistribution({
|
||||
detail,
|
||||
hideTitle = false,
|
||||
targetDate,
|
||||
marketScan,
|
||||
}: {
|
||||
detail: CityDetail;
|
||||
hideTitle?: boolean;
|
||||
targetDate?: string | null;
|
||||
marketScan?: MarketScan | null;
|
||||
}) {
|
||||
const { t } = useI18n();
|
||||
const { locale, t } = useI18n();
|
||||
const view = getProbabilityView(detail, targetDate);
|
||||
const marketBucketTemp = getMarketBucketTemp(marketScan);
|
||||
const marketYesPrice = getMarketYesPrice(marketScan);
|
||||
const marketNoPrice = getMarketNoPrice(marketScan);
|
||||
const marketYesText = toPercent(marketYesPrice);
|
||||
const marketNoText = toPercent(marketNoPrice);
|
||||
const isToday = !targetDate || targetDate === detail.local_date;
|
||||
const marketTopBuckets = isToday ? getMarketTopBuckets(marketScan) : [];
|
||||
const sortedMarketTopBuckets = [...marketTopBuckets]
|
||||
.sort((a, b) => Number(b.probability || 0) - Number(a.probability || 0))
|
||||
.slice(0, 4);
|
||||
const useMarketTopBuckets =
|
||||
marketScan?.available && sortedMarketTopBuckets.length > 0;
|
||||
const topMarketBucketText = toPercent(sortedMarketTopBuckets[0]?.probability);
|
||||
|
||||
return (
|
||||
<section className="prob-section">
|
||||
@@ -261,7 +380,11 @@ export function ProbabilityDistribution({
|
||||
<div className="prob-bars">
|
||||
{view.mu != null && (
|
||||
<div
|
||||
style={{ color: "var(--text-muted)", fontSize: "11px", marginBottom: "6px" }}
|
||||
style={{
|
||||
color: "var(--text-muted)",
|
||||
fontSize: "11px",
|
||||
marginBottom: "6px",
|
||||
}}
|
||||
>
|
||||
{t("section.mu", {
|
||||
unit: detail.temp_symbol || "",
|
||||
@@ -269,16 +392,62 @@ export function ProbabilityDistribution({
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{view.probabilities.length === 0 ? (
|
||||
<EmptyState text={t("section.noProb")} />
|
||||
) : (
|
||||
view.probabilities.slice(0, 6).map((bucket, index) => {
|
||||
const probability = Math.round(Number(bucket.probability || 0) * 100);
|
||||
{marketScan?.available && (topMarketBucketText || marketYesText) && (
|
||||
<div
|
||||
style={{
|
||||
color: "var(--text-secondary)",
|
||||
fontSize: "11px",
|
||||
marginBottom: "6px",
|
||||
}}
|
||||
>
|
||||
{useMarketTopBuckets
|
||||
? locale === "en-US"
|
||||
? `Market top-4 buckets (top): ${topMarketBucketText}`
|
||||
: `市场概率(前4温度桶):最高 ${topMarketBucketText}`
|
||||
: locale === "en-US"
|
||||
? `Market probability (this bucket): ${marketYesText}`
|
||||
: `市场概率(该温度桶): ${marketYesText}`}
|
||||
</div>
|
||||
)}
|
||||
{useMarketTopBuckets ? (
|
||||
sortedMarketTopBuckets.map((bucket, index) => {
|
||||
const probability = Math.round(
|
||||
Number(bucket.probability || 0) * 100,
|
||||
);
|
||||
let bucketLabel =
|
||||
bucket.label ||
|
||||
(bucket.value != null
|
||||
? `${bucket.value}${detail.temp_symbol}`
|
||||
: `${bucket.temp ?? "--"}${detail.temp_symbol}`);
|
||||
|
||||
if (bucketLabel) {
|
||||
let str = String(bucketLabel).toUpperCase().replace(/\s+/g, "");
|
||||
str = str.replace(/°?C($|\+|-)/g, "℃$1");
|
||||
if (!str.includes("℃") && /[0-9]/.test(str)) {
|
||||
str += "℃";
|
||||
}
|
||||
bucketLabel = str;
|
||||
}
|
||||
const buyYesText = toPriceCents(
|
||||
bucket.yes_buy ?? bucket.market_price ?? bucket.probability,
|
||||
);
|
||||
const buyNoText = toPriceCents(bucket.no_buy);
|
||||
const marketTag = buyYesText
|
||||
? locale === "en-US"
|
||||
? `Buy Yes: ${buyYesText}`
|
||||
: `买 Yes: ${buyYesText}`
|
||||
: buyNoText
|
||||
? locale === "en-US"
|
||||
? `Buy No: ${buyNoText}`
|
||||
: `买 No: ${buyNoText}`
|
||||
: null;
|
||||
|
||||
return (
|
||||
<div key={`${bucket.label || bucket.value || index}`} className="prob-row">
|
||||
<div className="prob-label">
|
||||
{bucket.label || `${bucket.value}${detail.temp_symbol}`}
|
||||
</div>
|
||||
<div
|
||||
key={`${bucket.slug || bucket.label || index}`}
|
||||
className="prob-row"
|
||||
>
|
||||
<div className="prob-label">{bucketLabel}</div>
|
||||
<div className="prob-bar-track">
|
||||
<div
|
||||
className={clsx("prob-bar-fill", `rank-${index}`)}
|
||||
@@ -287,6 +456,82 @@ export function ProbabilityDistribution({
|
||||
{probability}%
|
||||
</div>
|
||||
</div>
|
||||
{marketTag && (
|
||||
<div className={clsx("prob-market-inline", "yes")}>
|
||||
{marketTag}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
) : view.probabilities.length === 0 ? (
|
||||
<EmptyState text={t("section.noProb")} />
|
||||
) : (
|
||||
view.probabilities.slice(0, 6).map((bucket, index) => {
|
||||
const probability = Math.round(
|
||||
Number(bucket.probability || 0) * 100,
|
||||
);
|
||||
const bucketTemp = getBucketTemp(bucket);
|
||||
const isMarketBucket =
|
||||
marketYesText != null &&
|
||||
marketBucketTemp != null &&
|
||||
bucketTemp != null &&
|
||||
Math.abs(bucketTemp - marketBucketTemp) < 0.26;
|
||||
const marketTag = isMarketBucket
|
||||
? locale === "en-US"
|
||||
? `Buy Yes: ${marketYesText || "--"}`
|
||||
: `买 Yes: ${marketYesText || "--"}`
|
||||
: marketNoText
|
||||
? locale === "en-US"
|
||||
? `Buy No: ${marketNoText}`
|
||||
: `买 No: ${marketNoText}`
|
||||
: null;
|
||||
const yesPriceText = toPriceCents(marketYesPrice);
|
||||
const noPriceText = toPriceCents(marketNoPrice);
|
||||
const marketTagFinal = isMarketBucket
|
||||
? locale === "en-US"
|
||||
? `Buy Yes: ${yesPriceText || "--"}`
|
||||
: `买 Yes: ${yesPriceText || "--"}`
|
||||
: noPriceText
|
||||
? locale === "en-US"
|
||||
? `Buy No: ${noPriceText}`
|
||||
: `买 No: ${noPriceText}`
|
||||
: marketTag;
|
||||
let bucketLabel =
|
||||
bucket.label || `${bucket.value}${detail.temp_symbol}`;
|
||||
if (bucketLabel) {
|
||||
let str = String(bucketLabel).toUpperCase().replace(/\s+/g, "");
|
||||
str = str.replace(/°?C($|\+|-)/g, "℃$1");
|
||||
if (!str.includes("℃") && /[0-9]/.test(str)) {
|
||||
str += "℃";
|
||||
}
|
||||
bucketLabel = str;
|
||||
}
|
||||
|
||||
return (
|
||||
<div
|
||||
key={`${bucket.label || bucket.value || index}`}
|
||||
className="prob-row"
|
||||
>
|
||||
<div className="prob-label">{bucketLabel}</div>
|
||||
<div className="prob-bar-track">
|
||||
<div
|
||||
className={clsx("prob-bar-fill", `rank-${index}`)}
|
||||
style={{ width: `${Math.max(probability, 8)}%` }}
|
||||
>
|
||||
{probability}%
|
||||
</div>
|
||||
</div>
|
||||
{marketTagFinal && (
|
||||
<div
|
||||
className={clsx(
|
||||
"prob-market-inline",
|
||||
isMarketBucket ? "yes" : "no",
|
||||
)}
|
||||
>
|
||||
{marketTagFinal}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})
|
||||
@@ -313,8 +558,12 @@ export function ModelForecast({
|
||||
const numericValues = modelEntries.map(([, value]) => Number(value));
|
||||
const comparisonValues =
|
||||
view.deb != null ? [...numericValues, Number(view.deb)] : numericValues;
|
||||
const minValue = comparisonValues.length ? Math.min(...comparisonValues) - 1 : 0;
|
||||
const maxValue = comparisonValues.length ? Math.max(...comparisonValues) + 1 : 1;
|
||||
const minValue = comparisonValues.length
|
||||
? Math.min(...comparisonValues) - 1
|
||||
: 0;
|
||||
const maxValue = comparisonValues.length
|
||||
? Math.max(...comparisonValues) + 1
|
||||
: 1;
|
||||
const range = Math.max(maxValue - minValue, 1);
|
||||
|
||||
return (
|
||||
@@ -341,12 +590,18 @@ export function ModelForecast({
|
||||
{name}
|
||||
</div>
|
||||
<div className="model-bar-track">
|
||||
<div className="model-bar-fill" style={{ width: `${width}%` }}>
|
||||
<div
|
||||
className="model-bar-fill"
|
||||
style={{ width: `${width}%` }}
|
||||
>
|
||||
{numeric}
|
||||
{detail.temp_symbol}
|
||||
</div>
|
||||
{debLine != null && (
|
||||
<div className="model-deb-line" style={{ left: `${debLine}%` }} />
|
||||
<div
|
||||
className="model-deb-line"
|
||||
style={{ left: `${debLine}%` }}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
@@ -410,13 +665,19 @@ export function ForecastTable() {
|
||||
<button
|
||||
key={day.date}
|
||||
type="button"
|
||||
className={clsx("forecast-day", isToday && "today", isSelected && "selected")}
|
||||
className={clsx(
|
||||
"forecast-day",
|
||||
isToday && "today",
|
||||
isSelected && "selected",
|
||||
)}
|
||||
onClick={() => {
|
||||
store.openFutureModal(day.date);
|
||||
}}
|
||||
>
|
||||
<div className="f-date">
|
||||
{isToday ? t("forecast.today") : day.date.substring(5).replace("-", "/")}
|
||||
{isToday
|
||||
? t("forecast.today")
|
||||
: day.date.substring(5).replace("-", "/")}
|
||||
</div>
|
||||
<div className="f-temp">
|
||||
{day.max_temp}
|
||||
@@ -471,7 +732,9 @@ export function RiskInfo() {
|
||||
<h3>{t("section.risk")}</h3>
|
||||
<div className="risk-info">
|
||||
{!risk.airport ? (
|
||||
<span style={{ color: "var(--text-muted)" }}>{t("section.noRiskProfile")}</span>
|
||||
<span style={{ color: "var(--text-muted)" }}>
|
||||
{t("section.noRiskProfile")}
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<div className="risk-row">
|
||||
|
||||
@@ -21,6 +21,7 @@ import {
|
||||
HistoryPoint,
|
||||
HistoryState,
|
||||
LoadingState,
|
||||
MarketScan,
|
||||
} from "@/lib/dashboard-types";
|
||||
|
||||
interface DashboardStoreValue extends DashboardState {
|
||||
@@ -35,13 +36,15 @@ interface DashboardStoreValue extends DashboardState {
|
||||
openFutureModal: (dateStr: string) => void;
|
||||
openGuide: () => void;
|
||||
openHistory: () => Promise<void>;
|
||||
openTodayModal: () => Promise<void>;
|
||||
openTodayModal: (forceRefresh?: boolean) => Promise<void>;
|
||||
registerMapStopMotion: (stopMotion: () => void) => void;
|
||||
refreshAll: () => Promise<void>;
|
||||
refreshSelectedCity: () => Promise<void>;
|
||||
selectedMarketScan: MarketScan | null;
|
||||
selectedDetail: CityDetail | null;
|
||||
selectCity: (cityName: string) => Promise<void>;
|
||||
setForecastDate: (dateStr: string | null) => void;
|
||||
marketScanByCityName: Record<string, MarketScan>;
|
||||
}
|
||||
|
||||
const DashboardStoreContext = createContext<DashboardStoreValue | null>(null);
|
||||
@@ -52,6 +55,7 @@ function getInitialLoadingState(): LoadingState {
|
||||
cityDetail: false,
|
||||
history: false,
|
||||
refresh: false,
|
||||
marketScan: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -177,6 +181,9 @@ export function DashboardStoreProvider({
|
||||
const [cityDetailMetaByName, setCityDetailMetaByName] = useState<
|
||||
Record<string, { cachedAt: number; revision: string }>
|
||||
>(() => initialCache.meta);
|
||||
const [marketScanByCityName, setMarketScanByCityName] = useState<
|
||||
Record<string, MarketScan>
|
||||
>({});
|
||||
const [selectedCity, setSelectedCity] = useState<string | null>(null);
|
||||
const [isPanelOpen, setIsPanelOpen] = useState(false);
|
||||
const [selectedForecastDate, setSelectedForecastDate] = useState<
|
||||
@@ -203,6 +210,9 @@ export function DashboardStoreProvider({
|
||||
const selectedDetail = selectedCity
|
||||
? cityDetailsByName[selectedCity] || null
|
||||
: null;
|
||||
const selectedMarketScan = selectedCity
|
||||
? marketScanByCityName[selectedCity] || null
|
||||
: null;
|
||||
|
||||
useEffect(() => {
|
||||
dashboardClient.writeCityDetailCacheBundle(
|
||||
@@ -241,7 +251,9 @@ export function DashboardStoreProvider({
|
||||
}
|
||||
}
|
||||
|
||||
const latestDetail = await dashboardClient.getCityDetail(cityName, { force });
|
||||
const latestDetail = await dashboardClient.getCityDetail(cityName, {
|
||||
force,
|
||||
});
|
||||
const detail = mergeAiAnalysisIfStable(cached, latestDetail);
|
||||
setCityDetailsByName((current) => ({
|
||||
...current,
|
||||
@@ -261,6 +273,29 @@ export function DashboardStoreProvider({
|
||||
return detail;
|
||||
};
|
||||
|
||||
const ensureCityMarketScan = async (
|
||||
cityName: string,
|
||||
force = false,
|
||||
marketSlug?: string | null,
|
||||
) => {
|
||||
const cached = marketScanByCityName[cityName];
|
||||
if (!force && cached && !marketSlug) {
|
||||
return cached;
|
||||
}
|
||||
|
||||
const latestScan = await dashboardClient.getCityMarketScan(cityName, {
|
||||
force,
|
||||
marketSlug,
|
||||
});
|
||||
if (latestScan) {
|
||||
setMarketScanByCityName((current) => ({
|
||||
...current,
|
||||
[cityName]: latestScan,
|
||||
}));
|
||||
}
|
||||
return latestScan;
|
||||
};
|
||||
|
||||
const loadCities = async () => {
|
||||
setLoadingState((current) => ({ ...current, cities: true }));
|
||||
try {
|
||||
@@ -330,6 +365,8 @@ export function DashboardStoreProvider({
|
||||
try {
|
||||
const detail = await ensureCityDetail(cityName);
|
||||
setSelectedForecastDate(detail.local_date);
|
||||
// 预热市场数据,不做 await 阻塞,后台静默拉取
|
||||
void ensureCityMarketScan(cityName, false).catch(() => {});
|
||||
} finally {
|
||||
setLoadingState((current) => ({ ...current, cityDetail: false }));
|
||||
}
|
||||
@@ -433,24 +470,50 @@ export function DashboardStoreProvider({
|
||||
},
|
||||
openGuide: () => setIsGuideOpen(true),
|
||||
openHistory,
|
||||
openTodayModal: async () => {
|
||||
if (!selectedCity || loadingState.cityDetail || loadingState.refresh) {
|
||||
openTodayModal: async (forceRefresh?: boolean) => {
|
||||
if (!selectedCity || loadingState.cityDetail) {
|
||||
return;
|
||||
}
|
||||
|
||||
mapStopMotionRef.current();
|
||||
setLoadingState((current) => ({ ...current, refresh: true }));
|
||||
const cachedDetail = cityDetailsByName[selectedCity];
|
||||
|
||||
// 乐观 UI: 有缓存则立刻秒开 modal,不阻塞显示
|
||||
if (cachedDetail?.local_date) {
|
||||
setSelectedForecastDate(cachedDetail.local_date);
|
||||
setFutureModalDate(cachedDetail.local_date);
|
||||
setLoadingState((current) => ({ ...current, marketScan: true }));
|
||||
} else {
|
||||
setLoadingState((current) => ({
|
||||
...current,
|
||||
refresh: true,
|
||||
marketScan: true,
|
||||
}));
|
||||
}
|
||||
|
||||
// 异步静默拉取最新气象与市场数据
|
||||
try {
|
||||
const detail = await ensureCityDetail(selectedCity, true);
|
||||
setSelectedForecastDate(detail.local_date);
|
||||
setFutureModalDate(detail.local_date);
|
||||
|
||||
try {
|
||||
// 如果缓存里没有或者想要强制刷新,则拉取最新市场数据
|
||||
await ensureCityMarketScan(
|
||||
selectedCity,
|
||||
forceRefresh || !marketScanByCityName[selectedCity],
|
||||
);
|
||||
} catch {}
|
||||
} catch {
|
||||
const fallback = cityDetailsByName[selectedCity];
|
||||
if (fallback?.local_date) {
|
||||
setFutureModalDate(fallback.local_date);
|
||||
if (cachedDetail?.local_date) {
|
||||
setFutureModalDate(cachedDetail.local_date);
|
||||
}
|
||||
} finally {
|
||||
setLoadingState((current) => ({ ...current, refresh: false }));
|
||||
setLoadingState((current) => ({
|
||||
...current,
|
||||
refresh: false,
|
||||
marketScan: false,
|
||||
}));
|
||||
}
|
||||
},
|
||||
registerMapStopMotion: (stopMotion: () => void) => {
|
||||
@@ -458,12 +521,14 @@ export function DashboardStoreProvider({
|
||||
},
|
||||
refreshAll,
|
||||
refreshSelectedCity,
|
||||
selectedMarketScan,
|
||||
selectedCity,
|
||||
selectedDetail,
|
||||
selectedForecastDate,
|
||||
selectCity,
|
||||
setForecastDate: (dateStr: string | null) =>
|
||||
setSelectedForecastDate(dateStr),
|
||||
marketScanByCityName,
|
||||
}),
|
||||
[
|
||||
cities,
|
||||
@@ -474,6 +539,8 @@ export function DashboardStoreProvider({
|
||||
isPanelOpen,
|
||||
isGuideOpen,
|
||||
loadingState,
|
||||
marketScanByCityName,
|
||||
selectedMarketScan,
|
||||
selectedCity,
|
||||
selectedDetail,
|
||||
selectedForecastDate,
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
import {
|
||||
CityDetail,
|
||||
CityListItem,
|
||||
MarketScan,
|
||||
CitySummary,
|
||||
HistoryPoint,
|
||||
} from "@/lib/dashboard-types";
|
||||
@@ -12,6 +13,7 @@ const CACHE_TTL_MS = 5 * 60 * 1000;
|
||||
const pendingCityDetailRequests = new Map<string, Promise<CityDetail>>();
|
||||
const pendingHistoryRequests = new Map<string, Promise<HistoryPoint[]>>();
|
||||
const pendingCitySummaryRequests = new Map<string, Promise<CitySummary>>();
|
||||
const pendingMarketScanRequests = new Map<string, Promise<MarketScan | null>>();
|
||||
|
||||
type CityCacheMeta = {
|
||||
cachedAt: number;
|
||||
@@ -134,20 +136,75 @@ export const dashboardClient = {
|
||||
|
||||
async getCityDetail(cityName: string, options?: { force?: boolean }) {
|
||||
const force = options?.force ?? false;
|
||||
const requestKey = `${cityName}::${force ? "force" : "cached"}`;
|
||||
const existing = pendingCityDetailRequests.get(requestKey);
|
||||
if (existing) {
|
||||
return existing;
|
||||
if (!force) {
|
||||
const requestKey = `${cityName}::cached`;
|
||||
const existing = pendingCityDetailRequests.get(requestKey);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const request = fetchJson<CityDetail>(
|
||||
`/api/city/${normalizeCityName(cityName)}?force_refresh=false`,
|
||||
).finally(() => {
|
||||
pendingCityDetailRequests.delete(requestKey);
|
||||
});
|
||||
|
||||
pendingCityDetailRequests.set(requestKey, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
const request = fetchJson<CityDetail>(
|
||||
`/api/city/${normalizeCityName(cityName)}?force_refresh=${force}`,
|
||||
).finally(() => {
|
||||
pendingCityDetailRequests.delete(requestKey);
|
||||
const params = new URLSearchParams({
|
||||
force_refresh: "true",
|
||||
_ts: String(Date.now()),
|
||||
});
|
||||
return fetchJson<CityDetail>(
|
||||
`/api/city/${normalizeCityName(cityName)}?${params.toString()}`,
|
||||
);
|
||||
},
|
||||
|
||||
pendingCityDetailRequests.set(requestKey, request);
|
||||
return request;
|
||||
async getCityMarketScan(
|
||||
cityName: string,
|
||||
options?: { force?: boolean; marketSlug?: string | null },
|
||||
) {
|
||||
const force = options?.force ?? false;
|
||||
const marketSlug = options?.marketSlug || null;
|
||||
if (!force) {
|
||||
const requestKey = `${cityName}::cached::${marketSlug || "-"}`;
|
||||
const existing = pendingMarketScanRequests.get(requestKey);
|
||||
if (existing) {
|
||||
return existing;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
force_refresh: "false",
|
||||
});
|
||||
if (marketSlug) {
|
||||
params.set("market_slug", marketSlug);
|
||||
}
|
||||
|
||||
const request = fetchJson<{ market_scan?: MarketScan }>(
|
||||
`/api/city/${normalizeCityName(cityName)}/detail?${params.toString()}`,
|
||||
)
|
||||
.then((data) => data.market_scan || null)
|
||||
.finally(() => {
|
||||
pendingMarketScanRequests.delete(requestKey);
|
||||
});
|
||||
|
||||
pendingMarketScanRequests.set(requestKey, request);
|
||||
return request;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams({
|
||||
force_refresh: "true",
|
||||
_ts: String(Date.now()),
|
||||
});
|
||||
if (marketSlug) {
|
||||
params.set("market_slug", marketSlug);
|
||||
}
|
||||
|
||||
return fetchJson<{ market_scan?: MarketScan }>(
|
||||
`/api/city/${normalizeCityName(cityName)}/detail?${params.toString()}`,
|
||||
).then((data) => data.market_scan || null);
|
||||
},
|
||||
|
||||
async getHistory(cityName: string) {
|
||||
|
||||
@@ -181,6 +181,71 @@ export interface DailyModelForecast {
|
||||
probabilities?: ProbabilityBucket[];
|
||||
}
|
||||
|
||||
export interface MarketToken {
|
||||
outcome?: string | null;
|
||||
token_id?: string | null;
|
||||
implied_probability?: number | null;
|
||||
buy_price?: number | null;
|
||||
sell_price?: number | null;
|
||||
midpoint?: number | null;
|
||||
last_trade_price?: number | null;
|
||||
}
|
||||
|
||||
export interface MarketPrimary {
|
||||
id?: string | null;
|
||||
question?: string | null;
|
||||
slug?: string | null;
|
||||
condition_id?: string | null;
|
||||
end_date?: string | null;
|
||||
active?: boolean;
|
||||
closed?: boolean;
|
||||
liquidity?: number | null;
|
||||
volume?: number | null;
|
||||
}
|
||||
|
||||
export interface MarketTopBucket {
|
||||
label?: string | null;
|
||||
value?: number | null;
|
||||
temp?: number | null;
|
||||
probability?: number | null;
|
||||
market_price?: number | null;
|
||||
yes_buy?: number | null;
|
||||
yes_sell?: number | null;
|
||||
no_buy?: number | null;
|
||||
no_sell?: number | null;
|
||||
slug?: string | null;
|
||||
question?: string | null;
|
||||
is_primary?: boolean;
|
||||
}
|
||||
|
||||
export interface MarketScan {
|
||||
available?: boolean;
|
||||
reason?: string | null;
|
||||
primary_market?: MarketPrimary | null;
|
||||
selected_date?: string | null;
|
||||
selected_condition_id?: string | null;
|
||||
selected_slug?: string | null;
|
||||
temperature_bucket?: ProbabilityBucket | null;
|
||||
model_probability?: number | null;
|
||||
market_price?: number | null;
|
||||
edge_percent?: number | null;
|
||||
signal_label?: string | null;
|
||||
confidence?: string | null;
|
||||
yes_token?: MarketToken | null;
|
||||
no_token?: MarketToken | null;
|
||||
yes_buy?: number | null;
|
||||
yes_sell?: number | null;
|
||||
no_buy?: number | null;
|
||||
no_sell?: number | null;
|
||||
last_trade_price?: number | null;
|
||||
liquidity?: number | null;
|
||||
volume?: number | null;
|
||||
sparkline?: number[];
|
||||
top_buckets?: MarketTopBucket[] | null;
|
||||
recent_trades?: unknown[];
|
||||
websocket?: Record<string, unknown>;
|
||||
}
|
||||
|
||||
export interface AiAnalysisStructured {
|
||||
summary?: string | null;
|
||||
text?: string | null;
|
||||
@@ -227,6 +292,7 @@ export interface CityDetail {
|
||||
updated_at?: string;
|
||||
multi_model_daily?: Record<string, DailyModelForecast>;
|
||||
source_forecasts?: SourceForecasts;
|
||||
market_scan?: MarketScan;
|
||||
}
|
||||
|
||||
export interface HistoryPoint {
|
||||
@@ -241,6 +307,7 @@ export interface LoadingState {
|
||||
cityDetail: boolean;
|
||||
refresh: boolean;
|
||||
history: boolean;
|
||||
marketScan?: boolean;
|
||||
}
|
||||
|
||||
export interface HistoryState {
|
||||
|
||||
+12
-8
@@ -71,7 +71,7 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"future.score": "趋势评分",
|
||||
"future.todayTempTrend": "今日温度走势",
|
||||
"future.targetTempTrend": "目标日小时走势",
|
||||
"future.probability": "结算概率分布",
|
||||
"future.probability": "模型结算概率分布",
|
||||
"future.models": "多模型预报",
|
||||
"future.structureToday": "今日日内结构信号",
|
||||
"future.structureDate": "未来 6-48 小时趋势",
|
||||
@@ -91,7 +91,7 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
|
||||
"section.todayTempTrend": "今日温度走势",
|
||||
"section.chartEmpty": "暂无小时级数据",
|
||||
"section.probability": "结算概率分布",
|
||||
"section.probability": "模型结算概率分布",
|
||||
"section.mu": "动态分布中心 μ = {value}{unit}",
|
||||
"section.noProb": "暂无概率数据",
|
||||
"section.models": "多模型预报",
|
||||
@@ -133,7 +133,8 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"No scenery image matched. You can still review station and observation profile below.",
|
||||
"detail.profile": "City Profile",
|
||||
"detail.todayMiniTrend": "Today's Intraday Trend (Compact)",
|
||||
"detail.chartLegendEmpty": "No hourly observations or forecast curve available.",
|
||||
"detail.chartLegendEmpty":
|
||||
"No hourly observations or forecast curve available.",
|
||||
|
||||
"forecast.title": "Multi-day Forecast",
|
||||
"forecast.empty": "No multi-day forecast available",
|
||||
@@ -171,7 +172,7 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"future.score": "Trend Score",
|
||||
"future.todayTempTrend": "Today's Temperature Trend",
|
||||
"future.targetTempTrend": "Target-day Hourly Trend",
|
||||
"future.probability": "Settlement Probability Distribution",
|
||||
"future.probability": "Model Settlement Probabilities",
|
||||
"future.models": "Multi-model Forecast",
|
||||
"future.structureToday": "Intraday Structural Signal",
|
||||
"future.structureDate": "6-48h Structural Trend",
|
||||
@@ -179,11 +180,13 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
"future.confidence": "Confidence",
|
||||
"future.maxPrecip": "Max Precip Probability",
|
||||
"future.ai": "AI Deep Analysis",
|
||||
"future.noAi": "No AI analysis available. Structured meteorological and model data are used as baseline.",
|
||||
"future.noAi":
|
||||
"No AI analysis available. Structured meteorological and model data are used as baseline.",
|
||||
"future.weatherGov": "weather.gov text",
|
||||
"future.risk": "Settlement & Deviation Risk",
|
||||
"future.climate": "What Mainly Drives Local Climate",
|
||||
"future.chartLegendEmpty": "No METAR bulletin or hourly observations available",
|
||||
"future.chartLegendEmpty":
|
||||
"No METAR bulletin or hourly observations available",
|
||||
|
||||
"confidence.high": "High",
|
||||
"confidence.medium": "Medium",
|
||||
@@ -191,13 +194,14 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
||||
|
||||
"section.todayTempTrend": "Today's Temperature Trend",
|
||||
"section.chartEmpty": "No hourly data available",
|
||||
"section.probability": "Settlement Probability Distribution",
|
||||
"section.probability": "Model Settlement Probabilities",
|
||||
"section.mu": "Dynamic center μ = {value}{unit}",
|
||||
"section.noProb": "No probability data available",
|
||||
"section.models": "Multi-model Forecast",
|
||||
"section.noModels": "No multi-model forecast available",
|
||||
"section.ai": "AI Deep Analysis",
|
||||
"section.aiEmpty": "No AI analysis available. Structured meteorological and model data are currently used.",
|
||||
"section.aiEmpty":
|
||||
"No AI analysis available. Structured meteorological and model data are currently used.",
|
||||
"section.risk": "Data Deviation Risk",
|
||||
"section.noRiskProfile": "No risk profile available",
|
||||
"section.airport": "Airport",
|
||||
|
||||
@@ -292,6 +292,20 @@ export interface MarketScan {
|
||||
liquidity: number | null;
|
||||
volume: number | null;
|
||||
sparkline: number[];
|
||||
top_buckets?: Array<{
|
||||
label?: string | null;
|
||||
value?: number | null;
|
||||
temp?: number | null;
|
||||
probability?: number | null;
|
||||
market_price?: number | null;
|
||||
yes_buy?: number | null;
|
||||
yes_sell?: number | null;
|
||||
no_buy?: number | null;
|
||||
no_sell?: number | null;
|
||||
slug?: string | null;
|
||||
question?: string | null;
|
||||
is_primary?: boolean;
|
||||
}>;
|
||||
recent_trades: Trade[];
|
||||
websocket: any;
|
||||
}
|
||||
|
||||
@@ -421,6 +421,111 @@ def _join_trigger_types_cn(rules: Dict[str, Dict[str, Any]]) -> str:
|
||||
return " + ".join(parts)
|
||||
|
||||
|
||||
def _norm_probability(v: Any) -> Optional[float]:
|
||||
n = _sf(v)
|
||||
if n is None:
|
||||
return None
|
||||
if n > 1.0:
|
||||
n = n / 100.0
|
||||
return max(0.0, min(1.0, n))
|
||||
|
||||
|
||||
def _fmt_percent(v: Any) -> str:
|
||||
n = _norm_probability(v)
|
||||
if n is None:
|
||||
return "--"
|
||||
return f"{n * 100:.1f}%"
|
||||
|
||||
|
||||
def _fmt_cents(v: Any) -> str:
|
||||
n = _norm_probability(v)
|
||||
if n is None:
|
||||
return "--"
|
||||
cents = n * 100.0
|
||||
return f"{cents:.1f}c"
|
||||
|
||||
|
||||
def _bucket_label(bucket: Any) -> Optional[str]:
|
||||
if not isinstance(bucket, dict):
|
||||
return None
|
||||
direct = (
|
||||
str(bucket.get("label") or "").strip()
|
||||
or str(bucket.get("bucket") or "").strip()
|
||||
or str(bucket.get("range") or "").strip()
|
||||
)
|
||||
if direct:
|
||||
return direct
|
||||
value = _sf(bucket.get("value"))
|
||||
if value is not None:
|
||||
return f"{round(value)}C"
|
||||
temp = _sf(bucket.get("temp"))
|
||||
if temp is not None:
|
||||
return f"{round(temp)}C"
|
||||
return None
|
||||
|
||||
|
||||
def _extract_market_snapshot(city_weather: Dict[str, Any]) -> Dict[str, Any]:
|
||||
scan = city_weather.get("market_scan") or {}
|
||||
if not isinstance(scan, dict):
|
||||
return {"available": False}
|
||||
if not scan.get("available"):
|
||||
return {"available": False}
|
||||
|
||||
yes_buy = _norm_probability(scan.get("yes_buy"))
|
||||
yes_sell = _norm_probability(scan.get("yes_sell"))
|
||||
market_prob = _norm_probability(
|
||||
scan.get("market_price")
|
||||
or ((scan.get("yes_token") or {}).get("implied_probability"))
|
||||
)
|
||||
model_prob = _norm_probability(scan.get("model_probability"))
|
||||
spread = None
|
||||
if yes_buy is not None and yes_sell is not None:
|
||||
spread = abs(yes_sell - yes_buy)
|
||||
|
||||
top_bucket = None
|
||||
top_bucket_rows: List[Dict[str, Any]] = []
|
||||
top_buckets = scan.get("top_buckets") or []
|
||||
if isinstance(top_buckets, list):
|
||||
normalized = []
|
||||
for row in top_buckets:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
p = _norm_probability(row.get("probability"))
|
||||
if p is None:
|
||||
continue
|
||||
normalized.append((p, row))
|
||||
if normalized:
|
||||
normalized.sort(key=lambda x: x[0], reverse=True)
|
||||
top_bucket = normalized[0][1]
|
||||
for p, row in normalized[:4]:
|
||||
top_bucket_rows.append(
|
||||
{
|
||||
"label": _bucket_label(row),
|
||||
"probability": p,
|
||||
"yes_buy": _norm_probability(row.get("yes_buy")),
|
||||
"yes_sell": _norm_probability(row.get("yes_sell")),
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"available": True,
|
||||
"selected_bucket": _bucket_label(scan.get("temperature_bucket")),
|
||||
"top_bucket": _bucket_label(top_bucket) if isinstance(top_bucket, dict) else None,
|
||||
"top_bucket_prob": _norm_probability(
|
||||
top_bucket.get("probability") if isinstance(top_bucket, dict) else None
|
||||
),
|
||||
"market_prob": market_prob,
|
||||
"model_prob": model_prob,
|
||||
"yes_buy": yes_buy,
|
||||
"yes_sell": yes_sell,
|
||||
"spread": spread,
|
||||
"edge_percent": _sf(scan.get("edge_percent")),
|
||||
"signal_label": scan.get("signal_label"),
|
||||
"confidence": scan.get("confidence"),
|
||||
"top_bucket_rows": top_bucket_rows,
|
||||
}
|
||||
|
||||
|
||||
def _build_advice_cn(
|
||||
rules: Dict[str, Dict[str, Any]],
|
||||
temp_symbol: str,
|
||||
@@ -472,6 +577,7 @@ def _build_telegram_messages(
|
||||
city_weather: Dict[str, Any],
|
||||
rules: Dict[str, Dict[str, Any]],
|
||||
map_url: Optional[str],
|
||||
market_snapshot: Optional[Dict[str, Any]] = None,
|
||||
suppression: Optional[Dict[str, Any]] = None,
|
||||
) -> Dict[str, str]:
|
||||
temp_symbol = city_weather.get("temp_symbol", "°C")
|
||||
@@ -482,6 +588,7 @@ def _build_telegram_messages(
|
||||
center_deb = rules.get("ankara_center_deb_hit", {})
|
||||
momentum = rules.get("momentum_spike", {})
|
||||
advection = rules.get("advection", {})
|
||||
market_snapshot = market_snapshot or _extract_market_snapshot(city_weather)
|
||||
|
||||
if current_temp is None:
|
||||
return {"zh": "", "en": ""}
|
||||
@@ -559,6 +666,30 @@ def _build_telegram_messages(
|
||||
lines_zh.append(peak_line)
|
||||
if lead_line:
|
||||
lines_zh.append(lead_line)
|
||||
if market_snapshot.get("available") and market_snapshot.get("top_bucket_rows"):
|
||||
lines_zh.append("市场结算概率分布(Top4):")
|
||||
for row in (market_snapshot.get("top_bucket_rows") or [])[:4]:
|
||||
label = row.get("label") or "--"
|
||||
prob_text = _fmt_percent(row.get("probability"))
|
||||
yes_buy_text = _fmt_cents(row.get("yes_buy"))
|
||||
lines_zh.append(f"{label} {prob_text} | 买Yes: {yes_buy_text}")
|
||||
if market_snapshot.get("available") and not market_snapshot.get("top_bucket_rows"):
|
||||
market_edge = _sf(market_snapshot.get("edge_percent"))
|
||||
market_edge_text = f"{market_edge:+.1f}%" if market_edge is not None else "--"
|
||||
lines_zh.append(
|
||||
"市场联动:同桶 "
|
||||
f"模型 {_fmt_percent(market_snapshot.get('model_prob'))} vs "
|
||||
f"市场 {_fmt_percent(market_snapshot.get('market_prob'))} | "
|
||||
f"Yes {_fmt_cents(market_snapshot.get('yes_buy'))}/{_fmt_cents(market_snapshot.get('yes_sell'))} | "
|
||||
f"点差 {_fmt_cents(market_snapshot.get('spread'))} | "
|
||||
f"偏差 {market_edge_text} | "
|
||||
f"信号 {market_snapshot.get('signal_label') or '--'}/{market_snapshot.get('confidence') or '--'}"
|
||||
)
|
||||
if market_snapshot.get("top_bucket"):
|
||||
lines_zh.append(
|
||||
f"市场最热桶:{market_snapshot.get('top_bucket')} "
|
||||
f"({_fmt_percent(market_snapshot.get('top_bucket_prob'))})"
|
||||
)
|
||||
lines_zh.append(f"AI 建议:{advice}")
|
||||
lines_zh.append(f"点击查看实时地图:{final_map}")
|
||||
|
||||
@@ -602,6 +733,30 @@ def _build_telegram_messages(
|
||||
f"Peak state: intraday high {max_so_far:.1f}{temp_symbol} at {max_temp_time}, "
|
||||
f"now off by {rollback:.1f}{temp_symbol}"
|
||||
)
|
||||
if market_snapshot.get("available") and market_snapshot.get("top_bucket_rows"):
|
||||
lines_en.append("Settlement distribution (Top4):")
|
||||
for row in (market_snapshot.get("top_bucket_rows") or [])[:4]:
|
||||
label = row.get("label") or "--"
|
||||
prob_text = _fmt_percent(row.get("probability"))
|
||||
yes_buy_text = _fmt_cents(row.get("yes_buy"))
|
||||
lines_en.append(f"{label} {prob_text} | Buy Yes: {yes_buy_text}")
|
||||
if market_snapshot.get("available") and not market_snapshot.get("top_bucket_rows"):
|
||||
market_edge = _sf(market_snapshot.get("edge_percent"))
|
||||
market_edge_text = f"{market_edge:+.1f}%" if market_edge is not None else "--"
|
||||
lines_en.append(
|
||||
"Market: same-bucket "
|
||||
f"model {_fmt_percent(market_snapshot.get('model_prob'))} vs "
|
||||
f"market {_fmt_percent(market_snapshot.get('market_prob'))} | "
|
||||
f"Yes {_fmt_cents(market_snapshot.get('yes_buy'))}/{_fmt_cents(market_snapshot.get('yes_sell'))} | "
|
||||
f"spread {_fmt_cents(market_snapshot.get('spread'))} | "
|
||||
f"edge {market_edge_text} | "
|
||||
f"signal {market_snapshot.get('signal_label') or '--'}/{market_snapshot.get('confidence') or '--'}"
|
||||
)
|
||||
if market_snapshot.get("top_bucket"):
|
||||
lines_en.append(
|
||||
f"Top market bucket: {market_snapshot.get('top_bucket')} "
|
||||
f"({_fmt_percent(market_snapshot.get('top_bucket_prob'))})"
|
||||
)
|
||||
lines_en.append(f"Action: {advice}")
|
||||
lines_en.append(f"Map: {final_map}")
|
||||
|
||||
@@ -618,6 +773,7 @@ def build_trading_alerts(
|
||||
temp_symbol = city_weather.get("temp_symbol", "°C")
|
||||
city = city_weather.get("name", "")
|
||||
now = datetime.now(timezone.utc).isoformat()
|
||||
market_snapshot = _extract_market_snapshot(city_weather)
|
||||
|
||||
rules: Dict[str, Dict[str, Any]] = {
|
||||
"ankara_center_deb_hit": _calc_ankara_center_deb_alert(city_weather, temp_symbol),
|
||||
@@ -658,6 +814,7 @@ def build_trading_alerts(
|
||||
city_weather=city_weather,
|
||||
rules=rules,
|
||||
map_url=map_url,
|
||||
market_snapshot=market_snapshot,
|
||||
suppression=suppression,
|
||||
)
|
||||
|
||||
@@ -668,6 +825,7 @@ def build_trading_alerts(
|
||||
"severity": severity,
|
||||
"trigger_count": len(triggered),
|
||||
"rules": rules,
|
||||
"market_snapshot": market_snapshot,
|
||||
"suppression": suppression,
|
||||
"triggered_alerts": triggered,
|
||||
"telegram": telegram,
|
||||
|
||||
@@ -394,6 +394,7 @@ class PolymarketReadOnlyLayer:
|
||||
"liquidity": None,
|
||||
"volume": None,
|
||||
"sparkline": fallback_sparkline or [],
|
||||
"top_buckets": [],
|
||||
"recent_trades": [],
|
||||
"websocket": {},
|
||||
}
|
||||
@@ -485,6 +486,13 @@ class PolymarketReadOnlyLayer:
|
||||
|
||||
signal_label, confidence = self._derive_signal(edge_percent, liquidity)
|
||||
|
||||
top_buckets = self._build_top_temperature_buckets(
|
||||
city_key=city_key,
|
||||
target_date=date_str,
|
||||
primary_market=market,
|
||||
limit=4,
|
||||
)
|
||||
|
||||
yes_payload = {
|
||||
"outcome": yes_token.get("outcome") or "Yes",
|
||||
"token_id": yes_token.get("token_id"),
|
||||
@@ -551,6 +559,7 @@ class PolymarketReadOnlyLayer:
|
||||
"liquidity": liquidity,
|
||||
"volume": volume,
|
||||
"sparkline": sparkline_values,
|
||||
"top_buckets": top_buckets,
|
||||
"websocket": {
|
||||
"market_url": market_url,
|
||||
"asset_ids": [
|
||||
@@ -1174,3 +1183,232 @@ class PolymarketReadOnlyLayer:
|
||||
if slug:
|
||||
return f"https://polymarket.com/market/{slug}"
|
||||
return None
|
||||
|
||||
def _build_top_temperature_buckets(
|
||||
self,
|
||||
city_key: str,
|
||||
target_date: str,
|
||||
primary_market: Dict[str, Any],
|
||||
limit: int = 4,
|
||||
) -> List[Dict[str, Any]]:
|
||||
candidate_markets = self._collect_related_temperature_markets(
|
||||
city_key=city_key,
|
||||
target_date=target_date,
|
||||
primary_market=primary_market,
|
||||
)
|
||||
if not candidate_markets:
|
||||
return []
|
||||
|
||||
ranked: List[
|
||||
Tuple[
|
||||
float,
|
||||
float,
|
||||
Dict[str, Any],
|
||||
Dict[str, Any],
|
||||
Dict[str, Any],
|
||||
Dict[str, Any],
|
||||
Dict[str, Any],
|
||||
]
|
||||
] = []
|
||||
for market in candidate_markets:
|
||||
tokens = self._extract_market_tokens(market)
|
||||
yes_token, no_token = self._resolve_yes_no_tokens(tokens)
|
||||
if not yes_token or not no_token:
|
||||
continue
|
||||
|
||||
yes_token_id = str(yes_token.get("token_id") or "").strip()
|
||||
no_token_id = str(no_token.get("token_id") or "").strip()
|
||||
yes_prices = self._get_token_market_data(yes_token_id) if yes_token_id else {}
|
||||
no_prices = self._get_token_market_data(no_token_id) if no_token_id else {}
|
||||
|
||||
yes_midpoint = _extract_price(yes_prices.get("midpoint"))
|
||||
yes_implied = _extract_price(yes_token.get("implied_probability"))
|
||||
no_implied = _extract_price(no_token.get("implied_probability"))
|
||||
market_prob = (
|
||||
yes_midpoint
|
||||
if yes_midpoint is not None
|
||||
else (
|
||||
yes_implied
|
||||
if yes_implied is not None
|
||||
else (1.0 - no_implied if no_implied is not None else None)
|
||||
)
|
||||
)
|
||||
if market_prob is None:
|
||||
continue
|
||||
|
||||
market_prob = max(0.0, min(1.0, float(market_prob)))
|
||||
volume = (
|
||||
_extract_price(
|
||||
market.get("volumeNum")
|
||||
or market.get("volume")
|
||||
or market.get("volume24hr")
|
||||
)
|
||||
or 0.0
|
||||
)
|
||||
ranked.append(
|
||||
(
|
||||
market_prob,
|
||||
volume,
|
||||
market,
|
||||
yes_token,
|
||||
no_token,
|
||||
yes_prices,
|
||||
no_prices,
|
||||
)
|
||||
)
|
||||
|
||||
if not ranked:
|
||||
return []
|
||||
|
||||
ranked.sort(key=lambda item: (item[0], item[1]), reverse=True)
|
||||
top_rows: List[Dict[str, Any]] = []
|
||||
max_items = max(1, int(limit or 4))
|
||||
primary_slug = str(primary_market.get("slug") or "").strip().lower()
|
||||
|
||||
for market_prob, _volume, market, yes_token, no_token, yes_prices, no_prices in ranked[
|
||||
:max_items
|
||||
]:
|
||||
yes_buy = _extract_price(yes_prices.get("buy"))
|
||||
yes_sell = _extract_price(yes_prices.get("sell"))
|
||||
yes_midpoint = _extract_price(yes_prices.get("midpoint")) or market_prob
|
||||
no_buy = _extract_price(no_prices.get("buy"))
|
||||
no_sell = _extract_price(no_prices.get("sell"))
|
||||
|
||||
if no_buy is None and yes_buy is not None:
|
||||
no_buy = max(0.0, min(1.0, 1.0 - yes_buy))
|
||||
if no_sell is None and yes_sell is not None:
|
||||
no_sell = max(0.0, min(1.0, 1.0 - yes_sell))
|
||||
|
||||
bucket_temp = self._extract_market_bucket_temp(market)
|
||||
market_slug = str(market.get("slug") or "").strip()
|
||||
|
||||
top_rows.append(
|
||||
{
|
||||
"label": self._extract_market_bucket_label(market, bucket_temp),
|
||||
"value": bucket_temp,
|
||||
"temp": bucket_temp,
|
||||
"probability": market_prob,
|
||||
"market_price": yes_midpoint,
|
||||
"yes_buy": yes_buy,
|
||||
"yes_sell": yes_sell,
|
||||
"no_buy": no_buy,
|
||||
"no_sell": no_sell,
|
||||
"slug": market_slug or None,
|
||||
"question": market.get("question") or market.get("title"),
|
||||
"is_primary": bool(
|
||||
primary_slug
|
||||
and market_slug
|
||||
and primary_slug == market_slug.strip().lower()
|
||||
),
|
||||
}
|
||||
)
|
||||
|
||||
return top_rows
|
||||
|
||||
def _collect_related_temperature_markets(
|
||||
self,
|
||||
city_key: str,
|
||||
target_date: str,
|
||||
primary_market: Dict[str, Any],
|
||||
) -> List[Dict[str, Any]]:
|
||||
related: List[Dict[str, Any]] = []
|
||||
canonical_event_slug = self._build_weather_event_slug(city_key, target_date)
|
||||
if canonical_event_slug:
|
||||
related.extend(self._load_event_markets(canonical_event_slug))
|
||||
|
||||
event_slug = self._extract_event_slug(primary_market)
|
||||
if event_slug and event_slug != canonical_event_slug:
|
||||
related.extend(self._load_event_markets(event_slug))
|
||||
|
||||
if not related:
|
||||
for market in self._load_markets(active_only=True):
|
||||
if self._score_market(city_key, target_date, market) <= 0:
|
||||
continue
|
||||
if self._extract_market_bucket_temp(market) is None:
|
||||
continue
|
||||
related.append(market)
|
||||
|
||||
related.append(primary_market)
|
||||
|
||||
unique: List[Dict[str, Any]] = []
|
||||
seen = set()
|
||||
for market in related:
|
||||
if not isinstance(market, dict):
|
||||
continue
|
||||
dedupe_key = str(
|
||||
market.get("id")
|
||||
or market.get("slug")
|
||||
or market.get("conditionId")
|
||||
or ""
|
||||
).strip()
|
||||
if not dedupe_key:
|
||||
continue
|
||||
if dedupe_key in seen:
|
||||
continue
|
||||
seen.add(dedupe_key)
|
||||
unique.append(market)
|
||||
return unique
|
||||
|
||||
def _extract_event_slug(self, market: Dict[str, Any]) -> Optional[str]:
|
||||
event_slug = str(market.get("eventSlug") or "").strip().lower()
|
||||
if event_slug:
|
||||
return event_slug
|
||||
|
||||
slug = str(market.get("slug") or "").strip().lower()
|
||||
if not slug:
|
||||
return None
|
||||
|
||||
trimmed = re.sub(
|
||||
r"-(?:m)?\d+(?:-\d+)?c(?:-or-(?:higher|lower|above|below))?$",
|
||||
"",
|
||||
slug,
|
||||
)
|
||||
trimmed = trimmed.strip("-")
|
||||
return trimmed or None
|
||||
|
||||
def _load_event_markets(self, event_slug: str) -> List[Dict[str, Any]]:
|
||||
normalized_slug = str(event_slug or "").strip().lower()
|
||||
if not normalized_slug:
|
||||
return []
|
||||
|
||||
try:
|
||||
resp = self._session.get(
|
||||
f"{self.gamma_url}/events",
|
||||
params={"slug": normalized_slug, "limit": 5},
|
||||
timeout=self.http_timeout,
|
||||
)
|
||||
resp.raise_for_status()
|
||||
payload = resp.json()
|
||||
except Exception:
|
||||
return []
|
||||
|
||||
events = payload if isinstance(payload, list) else []
|
||||
out: List[Dict[str, Any]] = []
|
||||
for event in events:
|
||||
if not isinstance(event, dict):
|
||||
continue
|
||||
event_item_slug = str(event.get("slug") or "").strip().lower()
|
||||
if event_item_slug and event_item_slug != normalized_slug:
|
||||
continue
|
||||
for market in event.get("markets") or []:
|
||||
if not isinstance(market, dict):
|
||||
continue
|
||||
market["eventSlug"] = market.get("eventSlug") or event_item_slug
|
||||
market["eventTitle"] = market.get("eventTitle") or event.get("title")
|
||||
out.append(market)
|
||||
return out
|
||||
|
||||
def _extract_market_bucket_label(
|
||||
self,
|
||||
market: Dict[str, Any],
|
||||
bucket_temp: Optional[float],
|
||||
) -> str:
|
||||
question = str(market.get("question") or market.get("title") or "").strip()
|
||||
text = question.lower()
|
||||
if bucket_temp is not None:
|
||||
if "or higher" in text or "or above" in text or "and above" in text:
|
||||
return f"{bucket_temp:g}C+"
|
||||
if "or lower" in text or "or below" in text or "and below" in text:
|
||||
return f"<={bucket_temp:g}C"
|
||||
return f"{bucket_temp:g}C"
|
||||
return question or str(market.get("slug") or "")
|
||||
|
||||
@@ -117,6 +117,12 @@ def _trigger_type_key(alert_payload: Dict[str, Any]) -> str:
|
||||
for alert in (alert_payload.get("triggered_alerts") or [])
|
||||
if alert.get("type")
|
||||
)
|
||||
market = alert_payload.get("market_snapshot") or {}
|
||||
if isinstance(market, dict) and market.get("available"):
|
||||
signal = str(market.get("signal_label") or "").strip()
|
||||
bucket = str(market.get("selected_bucket") or "").strip()
|
||||
if signal:
|
||||
trigger_types.append(f"mkt:{signal}:{bucket}")
|
||||
return "|".join(trigger_types)
|
||||
|
||||
|
||||
@@ -127,6 +133,7 @@ def _alert_signature(alert_payload: Dict[str, Any]) -> str:
|
||||
breakthrough = rules.get("forecast_breakthrough") or {}
|
||||
advection = rules.get("advection") or {}
|
||||
suppression = alert_payload.get("suppression") or {}
|
||||
market = alert_payload.get("market_snapshot") or {}
|
||||
|
||||
signature_payload = {
|
||||
"city": alert_payload.get("city"),
|
||||
@@ -149,6 +156,18 @@ def _alert_signature(alert_payload: Dict[str, Any]) -> str:
|
||||
"suppression_reason": suppression.get("reason"),
|
||||
"suppression_peak_time": suppression.get("max_temp_time"),
|
||||
"suppression_rollback": round(float(suppression.get("rollback") or 0.0), 1),
|
||||
"market_available": bool(market.get("available")),
|
||||
"market_bucket": market.get("selected_bucket"),
|
||||
"market_top_bucket": market.get("top_bucket"),
|
||||
"market_top_bucket_prob": round(float(market.get("top_bucket_prob") or 0.0), 3),
|
||||
"market_prob": round(float(market.get("market_prob") or 0.0), 3),
|
||||
"model_prob": round(float(market.get("model_prob") or 0.0), 3),
|
||||
"market_yes_buy": round(float(market.get("yes_buy") or 0.0), 3),
|
||||
"market_yes_sell": round(float(market.get("yes_sell") or 0.0), 3),
|
||||
"market_spread": round(float(market.get("spread") or 0.0), 3),
|
||||
"market_edge_percent": round(float(market.get("edge_percent") or 0.0), 2),
|
||||
"market_signal": market.get("signal_label"),
|
||||
"market_confidence": market.get("confidence"),
|
||||
}
|
||||
raw = json.dumps(signature_payload, sort_keys=True, ensure_ascii=True)
|
||||
return hashlib.sha1(raw.encode("utf-8")).hexdigest()
|
||||
@@ -160,10 +179,18 @@ def build_trade_alert_for_city(
|
||||
force_refresh: bool = False,
|
||||
target_date: Optional[str] = None,
|
||||
) -> Dict[str, Any]:
|
||||
from web.app import _analyze
|
||||
from web.app import _analyze, _build_city_detail_payload
|
||||
from src.analysis.market_alert_engine import build_trading_alerts
|
||||
|
||||
city_weather = _analyze(city, force_refresh=force_refresh)
|
||||
try:
|
||||
aggregate_detail = _build_city_detail_payload(city_weather)
|
||||
market_scan = aggregate_detail.get("market_scan")
|
||||
if isinstance(market_scan, dict):
|
||||
city_weather = {**city_weather, "market_scan": market_scan}
|
||||
except Exception as exc:
|
||||
logger.debug(f"market scan attach skipped city={city}: {exc}")
|
||||
|
||||
resolved_target_date = target_date or city_weather.get("local_date")
|
||||
if resolved_target_date:
|
||||
datetime.strptime(resolved_target_date, "%Y-%m-%d")
|
||||
@@ -212,7 +239,7 @@ def _maybe_send_alert(
|
||||
last_sig_ts = int((state.get("by_signature") or {}).get(signature) or 0)
|
||||
last_city_active = bool(last_city.get("active"))
|
||||
|
||||
if last_city_active and last_city_key == trigger_key:
|
||||
if last_city_active and last_city_key == trigger_key and last_city_sig == signature:
|
||||
return False
|
||||
|
||||
if last_city_ts and now_ts - last_city_ts < cooldown_sec:
|
||||
|
||||
+9
-5
@@ -681,11 +681,15 @@ def _build_city_detail_payload(
|
||||
) -> Dict[str, Any]:
|
||||
distribution = data.get("probabilities", {}).get("distribution", []) or []
|
||||
primary_bucket = distribution[0] if distribution else None
|
||||
model_probability = (
|
||||
(primary_bucket.get("probability") / 100.0)
|
||||
if isinstance(primary_bucket, dict) and primary_bucket.get("probability") is not None
|
||||
else None
|
||||
)
|
||||
model_probability = None
|
||||
if isinstance(primary_bucket, dict) and primary_bucket.get("probability") is not None:
|
||||
try:
|
||||
raw_probability = float(primary_bucket.get("probability"))
|
||||
model_probability = (
|
||||
raw_probability / 100.0 if raw_probability > 1.0 else raw_probability
|
||||
)
|
||||
except Exception:
|
||||
model_probability = None
|
||||
fallback_sparkline = [
|
||||
p.get("probability", 0)
|
||||
for p in distribution[:8]
|
||||
|
||||
Reference in New Issue
Block a user