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.
|
- **City Specialization**: `17130` (`Ankara (Bölge/Center)`) remains the Ankara lead station without replacing LTAC settlement observation.
|
||||||
- **⚖️ DEB Smart Blending**
|
- **⚖️ DEB Smart Blending**
|
||||||
- Dynamic weighting based on city-level performance and current model spread.
|
- 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.
|
- 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.
|
- Today analysis workflow: open modal + freeze map motion.
|
||||||
- **🔔 Alert Engine**
|
- **🔔 Alert Engine**
|
||||||
- **Momentum Spike**: Captures rapid short-window temperature slope changes.
|
- **Momentum Spike**: Captures rapid short-window temperature slope changes.
|
||||||
@@ -141,7 +145,7 @@ Set `frontend` as the Vercel root directory for automatic CI/CD.
|
|||||||
## 💬 Bot Commands
|
## 💬 Bot Commands
|
||||||
|
|
||||||
| Command | Description | Example |
|
| Command | Description | Example |
|
||||||
| :-------- | :-------------------------------------- | :------------- |
|
| :------ | :------------------------------------ | :------------- |
|
||||||
| `/city` | Query real-time analysis for a city | `/city ankara` |
|
| `/city` | Query real-time analysis for a city | `/city ankara` |
|
||||||
| `/deb` | View historical accuracy of DEB model | `/deb london` |
|
| `/deb` | View historical accuracy of DEB model | `/deb london` |
|
||||||
| `/top` | View activity leaderboard | `/top` |
|
| `/top` | View activity leaderboard | `/top` |
|
||||||
@@ -161,8 +165,8 @@ Set `frontend` as the Vercel root directory for automatic CI/CD.
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**📅 Last Updated**: 2026-03-09
|
**📅 Last Updated**: 2026-03-10
|
||||||
**🚀 Status**: v1.1 Stable - React Dashboard Runtime in Production
|
**🚀 Status**: v1.2 Stable - React Dashboard with i18n & Polymarket Integration in Production
|
||||||
|
|
||||||
> [!TIP]
|
> [!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).
|
||||||
|
|||||||
+10
-6
@@ -46,9 +46,13 @@ PolyWeather 是一套专为 **Polymarket** 深度博弈者设计的实时情报
|
|||||||
- **城市特化**:安卡拉保留 `17130`(`Ankara (Bölge/Center)`)领先站逻辑,不替代 LTAC 结算主站。
|
- **城市特化**:安卡拉保留 `17130`(`Ankara (Bölge/Center)`)领先站逻辑,不替代 LTAC 结算主站。
|
||||||
- **⚖️ DEB 智能融合**
|
- **⚖️ DEB 智能融合**
|
||||||
- 基于城市历史表现与当前模型分歧动态调整权重。
|
- 基于城市历史表现与当前模型分歧动态调整权重。
|
||||||
- **🧩 React 仪表盘运行时**
|
- **📈 市场数据深度整合**
|
||||||
|
- 实时接入 Polymarket 报价、结算概率及动态“最热温度桶”追踪。
|
||||||
|
- 自动对比 DEB 与市场差值,计算 Edge 与点差。
|
||||||
|
- **🧩 React 仪表盘运行时 (v1.2)**
|
||||||
|
- 全面支持双语国际化 (i18n):英文与简体中文无缝切换。
|
||||||
|
- 尊享版 UI:新增毛玻璃效果、动态 Sonar 脉冲标记及流畅的全屏加载动效。
|
||||||
- 类型化 Store + 类型化 Data Client + Leaflet/Chart.js 生命周期封装。
|
- 类型化 Store + 类型化 Data Client + Leaflet/Chart.js 生命周期封装。
|
||||||
- 点击城市:地图聚焦 + 右侧卡片打开 + 周边站点展示。
|
|
||||||
- 点击“今日日内分析”:打开模态框并冻结地图动画。
|
- 点击“今日日内分析”:打开模态框并冻结地图动画。
|
||||||
- **🔔 异动预警系统**
|
- **🔔 异动预警系统**
|
||||||
- **动量突变**:捕捉短窗口温度斜率变化。
|
- **动量突变**:捕捉短窗口温度斜率变化。
|
||||||
@@ -141,7 +145,7 @@ docker-compose up -d --build
|
|||||||
## 💬 机器人指令
|
## 💬 机器人指令
|
||||||
|
|
||||||
| 命令 | 说明 | 示例 |
|
| 命令 | 说明 | 示例 |
|
||||||
| :-------- | :------------------------ | :------------- |
|
| :------ | :------------------------ | :------------- |
|
||||||
| `/city` | 查询指定城市实时分析 | `/city ankara` |
|
| `/city` | 查询指定城市实时分析 | `/city ankara` |
|
||||||
| `/deb` | 查看 DEB 模型的历史准确率 | `/deb london` |
|
| `/deb` | 查看 DEB 模型的历史准确率 | `/deb london` |
|
||||||
| `/top` | 查看活跃积分排行榜 | `/top` |
|
| `/top` | 查看活跃积分排行榜 | `/top` |
|
||||||
@@ -161,8 +165,8 @@ docker-compose up -d --build
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**📅 最后更新**:2026-03-09
|
**📅 最后更新**:2026-03-10
|
||||||
**🚀 状态**:v1.1 稳定版 - React 运行时已上线
|
**🚀 状态**:v1.2 稳定版 - 国际化及 Polymarket 市场层融合已上线
|
||||||
|
|
||||||
> [!TIP]
|
> [!TIP]
|
||||||
> **生产提示**:在不改变既有 UI 布局与视觉层级的前提下,数据流、地图联动和模态行为已迁移到类型化 React 组件体系。
|
> **生产提示**:在不改变既有 UI 布局的前提下,前端已全面引入国际化、市场报价集成及进阶视觉效果(如动态雷达标记、高级加载与毛玻璃控件)。
|
||||||
|
|||||||
+3
-2
@@ -160,9 +160,10 @@
|
|||||||
- `primary_market`
|
- `primary_market`
|
||||||
- `selected_condition_id`
|
- `selected_condition_id`
|
||||||
- `yes_token` / `no_token`
|
- `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)
|
- `market_price`(优先 midpoint)
|
||||||
- `edge_percent`(`(model_probability - market_price) * 100`)
|
- `edge_percent`(`(model_probability - market_price) * 100`)
|
||||||
|
- `temperature_bucket` / `top_buckets` (结算温度桶及市场概率)
|
||||||
- `signal_label`(`BUY YES` / `BUY NO` / `MONITOR`)
|
- `signal_label`(`BUY YES` / `BUY NO` / `MONITOR`)
|
||||||
- `websocket.asset_ids` / `websocket.condition_ids`(仅用于订阅标识,P0 不下单)
|
- `websocket.asset_ids` / `websocket.condition_ids`(仅用于订阅标识,P0 不下单)
|
||||||
|
|
||||||
@@ -249,4 +250,4 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**最后更新**: 2026-03-09
|
**最后更新**: 2026-03-10
|
||||||
|
|||||||
@@ -13,7 +13,7 @@ PolyWeather is positioned as a **premium intelligence service** for weather-driv
|
|||||||
## 💰 Pricing & Monetization
|
## 💰 Pricing & Monetization
|
||||||
|
|
||||||
| Tier | Price | Primary Value Proposition |
|
| Tier | Price | Primary Value Proposition |
|
||||||
| :------------------- | :------------ | :------------------------------------------------------------ |
|
| :------------------- | :------------ | :------------------------------------------------------ |
|
||||||
| **Telegram Channel** | **$1 / mo** | High-fidelity proactive alerts, low noise. |
|
| **Telegram Channel** | **$1 / mo** | High-fidelity proactive alerts, low noise. |
|
||||||
| **Web Dashboard** | **$5 / mo** | Full multi-model context + historical DEB benchmarking. |
|
| **Web Dashboard** | **$5 / mo** | Full multi-model context + historical DEB benchmarking. |
|
||||||
| **VIP Bundle** | **$5.5 / mo** | Unified access to dashboard + signal stream. |
|
| **VIP Bundle** | **$5.5 / mo** | Unified access to dashboard + signal stream. |
|
||||||
@@ -92,4 +92,4 @@ graph LR
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**📅 Last Updated**: 2026-03-09
|
**📅 Last Updated**: 2026-03-10
|
||||||
|
|||||||
+4
-3
@@ -22,7 +22,8 @@ The core weather engine and React dashboard runtime are now stable, but product-
|
|||||||
- [x] DEB Blending Algorithm
|
- [x] DEB Blending Algorithm
|
||||||
- [x] Proactive Telegram Alert Engine
|
- [x] Proactive Telegram Alert Engine
|
||||||
- [x] Vercel Dashboard Infrastructure
|
- [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
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@@ -40,7 +41,7 @@ The core weather engine and React dashboard runtime are now stable, but product-
|
|||||||
## 🟡 Medium Priority: Quality of Life
|
## 🟡 Medium Priority: Quality of Life
|
||||||
|
|
||||||
| Debt Item | Impact | Suggested Fix |
|
| 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`. |
|
| **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`. |
|
| **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. |
|
| **Backend Naming** | Artifacts of "market price" logic remain in naming. | Systematic refactor of variable names to reflect weather-intelligence focus. |
|
||||||
@@ -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
|
||||||
|
|||||||
@@ -22,14 +22,15 @@ pie title 系统健康度与技术债
|
|||||||
- [x] DEB 融合算法
|
- [x] DEB 融合算法
|
||||||
- [x] 主动式 Telegram 预警引擎
|
- [x] 主动式 Telegram 预警引擎
|
||||||
- [x] Vercel 仪表盘基础设施
|
- [x] Vercel 仪表盘基础设施
|
||||||
- [x] React 组件驱动仪表盘运行时(已替换 legacy `public/static/app.js` 渲染路径)
|
- [x] React 组件驱动仪表盘运行时
|
||||||
|
- [x] 国际化 (i18n) 与前端市场数据集成 (Polymarket)
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## 🔴 高优先级:立即处理
|
## 🔴 高优先级:立即处理
|
||||||
|
|
||||||
| 债务项 | 影响 | 建议修复 |
|
| 债务项 | 影响 | 建议修复 |
|
||||||
| :-------------------- | :------------------------------------------------- | :--------------------------------------------------------------- |
|
| :--------------------- | :----------------------------------------- | :-------------------------------------------------------- |
|
||||||
| **Monolithic Bot** | `bot_listener.py` 可测试性差,演进成本高。 | 将 UI 交互与业务逻辑解耦,沉入 `src/analysis`。 |
|
| **Monolithic Bot** | `bot_listener.py` 可测试性差,演进成本高。 | 将 UI 交互与业务逻辑解耦,沉入 `src/analysis`。 |
|
||||||
| **Subscription Store** | 付费用户缺少持久化记录。 | 从内存校验迁移到 **Supabase/PostgreSQL**。 |
|
| **Subscription Store** | 付费用户缺少持久化记录。 | 从内存校验迁移到 **Supabase/PostgreSQL**。 |
|
||||||
| **Alert Transparency** | 运维侧难以审计“告警为何触发”。 | 为所有内部告警载荷增加 `Evidence` 元数据块。 |
|
| **Alert Transparency** | 运维侧难以审计“告警为何触发”。 | 为所有内部告警载荷增加 `Evidence` 元数据块。 |
|
||||||
@@ -40,7 +41,7 @@ pie title 系统健康度与技术债
|
|||||||
## 🟡 中优先级:体验与效率
|
## 🟡 中优先级:体验与效率
|
||||||
|
|
||||||
| 债务项 | 影响 | 建议修复 |
|
| 债务项 | 影响 | 建议修复 |
|
||||||
| :---------------------- | :------------------------------------------------- | :---------------------------------------------------------------------- |
|
| :------------------------- | :--------------------------------------------- | :--------------------------------------------------- |
|
||||||
| **Hard-coded Thresholds** | 阈值修改需要改代码(如 5s 冷却)。 | 将业务常量统一抽离到结构化 `config.yaml`。 |
|
| **Hard-coded Thresholds** | 阈值修改需要改代码(如 5s 冷却)。 | 将业务常量统一抽离到结构化 `config.yaml`。 |
|
||||||
| **Simulation Harness** | 无法“回放历史天气日”验证告警逻辑。 | 基于 `data/daily_records.json` 构建 `ReplayEngine`。 |
|
| **Simulation Harness** | 无法“回放历史天气日”验证告警逻辑。 | 基于 `data/daily_records.json` 构建 `ReplayEngine`。 |
|
||||||
| **Backend Naming** | 仍有“市场价格时代”的命名残留。 | 系统化重命名,统一为 weather-intelligence 语义。 |
|
| **Backend Naming** | 仍有“市场价格时代”的命名残留。 | 系统化重命名,统一为 weather-intelligence 语义。 |
|
||||||
@@ -51,7 +52,7 @@ pie title 系统健康度与技术债
|
|||||||
## 🟢 低优先级:性能优化
|
## 🟢 低优先级:性能优化
|
||||||
|
|
||||||
| 债务项 | 影响 | 建议修复 |
|
| 债务项 | 影响 | 建议修复 |
|
||||||
| :----------------------- | :------------------------------------------------- | :--------------------------------------------------------------- |
|
| :------------------------- | :----------------------------- | :--------------------------------------- |
|
||||||
| **Serverless Cold Starts** | Vercel 首次 API 调用可能偏慢。 | 为主要城市接口增加边缘缓存或预热任务。 |
|
| **Serverless Cold Starts** | Vercel 首次 API 调用可能偏慢。 | 为主要城市接口增加边缘缓存或预热任务。 |
|
||||||
| **Local SQLite Files** | 与 Vercel 短暂文件系统不兼容。 | 全面迁移到远程数据库(Supabase/Redis)。 |
|
| **Local SQLite Files** | 与 Vercel 短暂文件系统不兼容。 | 全面迁移到远程数据库(Supabase/Redis)。 |
|
||||||
|
|
||||||
@@ -66,4 +67,4 @@ pie title 系统健康度与技术债
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
**📅 最后更新**:2026-03-09
|
**📅 最后更新**:2026-03-10
|
||||||
|
|||||||
@@ -33,7 +33,7 @@
|
|||||||
/* Spacing */
|
/* Spacing */
|
||||||
--panel-width: 560px;
|
--panel-width: 560px;
|
||||||
--header-height: 56px;
|
--header-height: 56px;
|
||||||
--sidebar-width: 280px;
|
--sidebar-width: 260px;
|
||||||
|
|
||||||
/* Effects */
|
/* Effects */
|
||||||
--glass-blur: 20px;
|
--glass-blur: 20px;
|
||||||
@@ -328,6 +328,7 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
.root :global(.city-item) {
|
.root :global(.city-item) {
|
||||||
|
width: 100%;
|
||||||
display: flex;
|
display: flex;
|
||||||
flex-direction: column;
|
flex-direction: column;
|
||||||
gap: 4px;
|
gap: 4px;
|
||||||
@@ -336,6 +337,10 @@
|
|||||||
cursor: pointer;
|
cursor: pointer;
|
||||||
transition: var(--transition);
|
transition: var(--transition);
|
||||||
border: 1px solid transparent;
|
border: 1px solid transparent;
|
||||||
|
background: transparent;
|
||||||
|
color: inherit;
|
||||||
|
font-family: inherit;
|
||||||
|
text-align: left;
|
||||||
}
|
}
|
||||||
.root :global(.city-item:hover) {
|
.root :global(.city-item:hover) {
|
||||||
background: rgba(99, 102, 241, 0.08);
|
background: rgba(99, 102, 241, 0.08);
|
||||||
@@ -722,6 +727,29 @@
|
|||||||
background: rgba(99, 102, 241, 0.15);
|
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 ── */
|
/* ── Model Bars ── */
|
||||||
.root :global(.model-bars) {
|
.root :global(.model-bars) {
|
||||||
display: flex;
|
display: flex;
|
||||||
@@ -1386,6 +1414,41 @@
|
|||||||
color: var(--text-primary);
|
color: var(--text-primary);
|
||||||
margin: 0;
|
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) {
|
.root :global(.modal-close) {
|
||||||
background: none;
|
background: none;
|
||||||
border: none;
|
border: none;
|
||||||
@@ -1435,6 +1498,14 @@
|
|||||||
color: var(--text-primary);
|
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) {
|
.root :global(.history-chart-wrapper) {
|
||||||
position: relative;
|
position: relative;
|
||||||
height: 300px;
|
height: 300px;
|
||||||
@@ -1551,6 +1622,301 @@
|
|||||||
padding-right: 14px;
|
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) {
|
.root :global(.future-modal-section) {
|
||||||
background: rgba(255, 255, 255, 0.02);
|
background: rgba(255, 255, 255, 0.02);
|
||||||
border: 1px solid var(--border-subtle);
|
border: 1px solid var(--border-subtle);
|
||||||
@@ -1660,9 +2026,12 @@
|
|||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
background: linear-gradient(
|
background: linear-gradient(
|
||||||
90deg,
|
90deg,
|
||||||
rgba(245, 158, 11, 0.35),
|
rgba(56, 189, 248, 0.4) 0%,
|
||||||
rgba(255, 255, 255, 0.06) 50%,
|
rgba(56, 189, 248, 0.4) 30%,
|
||||||
rgba(52, 211, 153, 0.35)
|
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;
|
overflow: hidden;
|
||||||
}
|
}
|
||||||
@@ -1675,9 +2044,11 @@
|
|||||||
width: 14px;
|
width: 14px;
|
||||||
height: 14px;
|
height: 14px;
|
||||||
border-radius: 999px;
|
border-radius: 999px;
|
||||||
background: var(--accent-cyan);
|
background: var(--text-primary);
|
||||||
transform: translate(-50%, -50%);
|
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) {
|
.root :global(.future-front-meta) {
|
||||||
@@ -1699,6 +2070,14 @@
|
|||||||
}
|
}
|
||||||
|
|
||||||
@media (max-width: 960px) {
|
@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-modal-grid),
|
||||||
.root :global(.future-trend-grid) {
|
.root :global(.future-trend-grid) {
|
||||||
grid-template-columns: 1fr;
|
grid-template-columns: 1fr;
|
||||||
|
|||||||
@@ -1,5 +1,17 @@
|
|||||||
"use client";
|
"use client";
|
||||||
|
|
||||||
|
import {
|
||||||
|
Cloud,
|
||||||
|
CloudFog,
|
||||||
|
CloudLightning,
|
||||||
|
CloudRain,
|
||||||
|
CloudSnow,
|
||||||
|
CloudSun,
|
||||||
|
Search,
|
||||||
|
Sun,
|
||||||
|
Wind,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
import { ChartConfiguration } from "chart.js/auto";
|
import { ChartConfiguration } from "chart.js/auto";
|
||||||
import clsx from "clsx";
|
import clsx from "clsx";
|
||||||
import { CSSProperties } from "react";
|
import { CSSProperties } from "react";
|
||||||
@@ -20,6 +32,155 @@ import {
|
|||||||
parseAiAnalysis,
|
parseAiAnalysis,
|
||||||
} from "@/lib/dashboard-utils";
|
} from "@/lib/dashboard-utils";
|
||||||
|
|
||||||
|
function normalizeMarketValue(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 WeatherIcon({ emoji, size = 32 }: { emoji: string; size?: number }) {
|
||||||
|
if (emoji === "☀️") return <Sun size={size} color="#facc15" />;
|
||||||
|
if (emoji === "⛅" || emoji === "🌤️")
|
||||||
|
return <CloudSun size={size} color="#38bdf8" />;
|
||||||
|
if (emoji === "☁️") return <Cloud size={size} color="#94a3b8" />;
|
||||||
|
if (emoji === "🌧️" || emoji === "🌦️")
|
||||||
|
return <CloudRain size={size} color="#60a5fa" />;
|
||||||
|
if (emoji === "⛈️") return <CloudLightning size={size} color="#c084fc" />;
|
||||||
|
if (emoji === "❄️" || emoji === "🌨️")
|
||||||
|
return <CloudSnow size={size} color="#7dd3fc" />;
|
||||||
|
if (emoji === "🌫️") return <CloudFog size={size} color="#a1a1aa" />;
|
||||||
|
if (emoji === "💨") return <Wind size={size} color="#cbd5e1" />;
|
||||||
|
return <Search size={size} color="#64748b" />;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMarketPercent(value?: number | null) {
|
||||||
|
const normalized = normalizeMarketValue(value);
|
||||||
|
if (normalized == null) return "--";
|
||||||
|
return `${(normalized * 100).toFixed(1)}%`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMarketPriceCents(value?: number | null) {
|
||||||
|
const normalized = normalizeMarketValue(value);
|
||||||
|
if (normalized == null) return "--";
|
||||||
|
const cents = normalized * 100;
|
||||||
|
const rounded = Math.round(cents * 10) / 10;
|
||||||
|
return `${Number.isInteger(rounded) ? rounded.toFixed(0) : rounded.toFixed(1)}¢`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSignedPercent(value?: number | null) {
|
||||||
|
const numeric = Number(value);
|
||||||
|
if (!Number.isFinite(numeric)) return "--";
|
||||||
|
const sign = numeric > 0 ? "+" : "";
|
||||||
|
return `${sign}${numeric.toFixed(1)}%`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatSpreadPercent(low?: number | null, high?: number | null) {
|
||||||
|
const a = normalizeMarketValue(low);
|
||||||
|
const b = normalizeMarketValue(high);
|
||||||
|
if (a == null || b == null) return "--";
|
||||||
|
const spreadCents = Math.abs((b - a) * 100);
|
||||||
|
const rounded = Math.round(spreadCents * 10) / 10;
|
||||||
|
return `${Number.isInteger(rounded) ? rounded.toFixed(0) : rounded.toFixed(1)}¢`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function resolveCounterPrice(
|
||||||
|
directValue?: number | null,
|
||||||
|
mirrorValue?: number | null,
|
||||||
|
) {
|
||||||
|
const direct = normalizeMarketValue(directValue);
|
||||||
|
if (direct != null) return direct;
|
||||||
|
const mirror = normalizeMarketValue(mirrorValue);
|
||||||
|
if (mirror == null) return null;
|
||||||
|
return Math.max(0, Math.min(1, 1 - mirror));
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBucketLabel(
|
||||||
|
bucket?: {
|
||||||
|
label?: string | null;
|
||||||
|
bucket?: string | null;
|
||||||
|
range?: string | null;
|
||||||
|
value?: number | null;
|
||||||
|
temp?: number | null;
|
||||||
|
} | null,
|
||||||
|
) {
|
||||||
|
if (!bucket) return "--";
|
||||||
|
const direct =
|
||||||
|
String(bucket.label || "").trim() ||
|
||||||
|
String(bucket.bucket || "").trim() ||
|
||||||
|
String(bucket.range || "").trim();
|
||||||
|
if (direct) {
|
||||||
|
let str = direct.toUpperCase().replace(/\s+/g, "");
|
||||||
|
str = str.replace(/°?C($|\+|-)/g, "℃$1");
|
||||||
|
if (!str.includes("℃") && /[0-9]/.test(str)) {
|
||||||
|
str += "℃";
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
const temp = Number(bucket.value ?? bucket.temp);
|
||||||
|
if (Number.isFinite(temp)) {
|
||||||
|
return `${Math.round(temp)}℃`;
|
||||||
|
}
|
||||||
|
return "--";
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseMetarSignedInt(token: string) {
|
||||||
|
if (!token) return null;
|
||||||
|
const normalized = token.toUpperCase();
|
||||||
|
if (!/^[M]?\d{2}$/.test(normalized)) return null;
|
||||||
|
const value = Number(normalized.replace("M", ""));
|
||||||
|
if (!Number.isFinite(value)) return null;
|
||||||
|
return normalized.startsWith("M") ? -value : value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseMetarTempDew(rawMetar?: string | null) {
|
||||||
|
const text = String(rawMetar || "").toUpperCase();
|
||||||
|
if (!text)
|
||||||
|
return { tempC: null as number | null, dewC: null as number | null };
|
||||||
|
const match = text.match(/\s(M?\d{2})\/(M?\d{2})(?:\s|$)/);
|
||||||
|
if (!match)
|
||||||
|
return { tempC: null as number | null, dewC: null as number | null };
|
||||||
|
return {
|
||||||
|
tempC: parseMetarSignedInt(match[1]),
|
||||||
|
dewC: parseMetarSignedInt(match[2]),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function estimateHumidityFromTempDew(
|
||||||
|
tempC?: number | null,
|
||||||
|
dewC?: number | null,
|
||||||
|
) {
|
||||||
|
const t = Number(tempC);
|
||||||
|
const d = Number(dewC);
|
||||||
|
if (!Number.isFinite(t) || !Number.isFinite(d)) return null;
|
||||||
|
const es = Math.exp((17.625 * t) / (243.04 + t));
|
||||||
|
const ed = Math.exp((17.625 * d) / (243.04 + d));
|
||||||
|
const rh = (ed / es) * 100;
|
||||||
|
if (!Number.isFinite(rh)) return null;
|
||||||
|
return Math.max(0, Math.min(100, rh));
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseVisibilityText(
|
||||||
|
rawMetar?: string | null,
|
||||||
|
visibilityMi?: number | null,
|
||||||
|
) {
|
||||||
|
const direct = Number(visibilityMi);
|
||||||
|
if (Number.isFinite(direct)) {
|
||||||
|
return `${direct} mi`;
|
||||||
|
}
|
||||||
|
|
||||||
|
const text = String(rawMetar || "").toUpperCase();
|
||||||
|
if (!text) return "--";
|
||||||
|
if (text.includes("CAVOK")) return ">=6 mi";
|
||||||
|
|
||||||
|
const sm = text.match(/\s(\d{1,2}(?:\/\d)?)SM(?:\s|$)/);
|
||||||
|
if (sm) {
|
||||||
|
return `${sm[1]} mi`;
|
||||||
|
}
|
||||||
|
return "--";
|
||||||
|
}
|
||||||
|
|
||||||
function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
||||||
const store = useDashboardStore();
|
const store = useDashboardStore();
|
||||||
const { locale, t } = useI18n();
|
const { locale, t } = useI18n();
|
||||||
@@ -29,8 +190,7 @@ function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
|||||||
const todayChartData =
|
const todayChartData =
|
||||||
detail && isToday ? getTemperatureChartData(detail, locale) : null;
|
detail && isToday ? getTemperatureChartData(detail, locale) : null;
|
||||||
|
|
||||||
const canvasRef = useChart(
|
const canvasRef = useChart(() => {
|
||||||
() => {
|
|
||||||
if (!detail || !view) {
|
if (!detail || !view) {
|
||||||
return {
|
return {
|
||||||
data: { datasets: [], labels: [] },
|
data: { datasets: [], labels: [] },
|
||||||
@@ -39,7 +199,9 @@ function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (isToday && todayChartData) {
|
if (isToday && todayChartData) {
|
||||||
const datasets: NonNullable<ChartConfiguration<"line">["data"]>["datasets"] = [];
|
const datasets: NonNullable<
|
||||||
|
ChartConfiguration<"line">["data"]
|
||||||
|
>["datasets"] = [];
|
||||||
|
|
||||||
if (todayChartData.datasets.hasMgmHourly) {
|
if (todayChartData.datasets.hasMgmHourly) {
|
||||||
datasets.push({
|
datasets.push({
|
||||||
@@ -48,7 +210,7 @@ function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
|||||||
borderWidth: 2,
|
borderWidth: 2,
|
||||||
data: todayChartData.datasets.mgmHourlyPoints,
|
data: todayChartData.datasets.mgmHourlyPoints,
|
||||||
fill: false,
|
fill: false,
|
||||||
label: locale === "en-US" ? "MGM Forecast" : "MGM 预报",
|
label: locale === "en-US" ? "MGM Forecast" : "MGM 预测",
|
||||||
pointHoverRadius: 6,
|
pointHoverRadius: 6,
|
||||||
pointRadius: 3,
|
pointRadius: 3,
|
||||||
spanGaps: true,
|
spanGaps: true,
|
||||||
@@ -61,7 +223,7 @@ function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
|||||||
borderWidth: 1.5,
|
borderWidth: 1.5,
|
||||||
data: todayChartData.datasets.debPast,
|
data: todayChartData.datasets.debPast,
|
||||||
fill: true,
|
fill: true,
|
||||||
label: locale === "en-US" ? "DEB Forecast" : "DEB 预报",
|
label: locale === "en-US" ? "DEB Forecast" : "DEB 预测",
|
||||||
pointHoverRadius: 3,
|
pointHoverRadius: 3,
|
||||||
pointRadius: 0,
|
pointRadius: 0,
|
||||||
tension: 0.3,
|
tension: 0.3,
|
||||||
@@ -72,7 +234,7 @@ function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
|||||||
borderWidth: 1.5,
|
borderWidth: 1.5,
|
||||||
data: todayChartData.datasets.debFuture,
|
data: todayChartData.datasets.debFuture,
|
||||||
fill: false,
|
fill: false,
|
||||||
label: locale === "en-US" ? "DEB Forecast" : "DEB 预报",
|
label: locale === "en-US" ? "DEB Forecast" : "DEB 预测",
|
||||||
pointRadius: 0,
|
pointRadius: 0,
|
||||||
tension: 0.3,
|
tension: 0.3,
|
||||||
});
|
});
|
||||||
@@ -138,8 +300,8 @@ function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
|||||||
if (!text) return false;
|
if (!text) return false;
|
||||||
if (!text.includes("DEB")) return true;
|
if (!text.includes("DEB")) return true;
|
||||||
|
|
||||||
const firstDebIndex = (chartData.datasets || []).findIndex((dataset) =>
|
const firstDebIndex = (chartData.datasets || []).findIndex(
|
||||||
String(dataset.label || "").includes("DEB"),
|
(dataset) => String(dataset.label || "").includes("DEB"),
|
||||||
);
|
);
|
||||||
return legendItem.datasetIndex === firstDebIndex;
|
return legendItem.datasetIndex === firstDebIndex;
|
||||||
},
|
},
|
||||||
@@ -193,7 +355,8 @@ function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
|||||||
borderColor: "#22d3ee",
|
borderColor: "#22d3ee",
|
||||||
data: view.slice.map((point) => point.temp),
|
data: view.slice.map((point) => point.temp),
|
||||||
fill: false,
|
fill: false,
|
||||||
label: locale === "en-US" ? "Open-Meteo Temperature" : "Open-Meteo 温度",
|
label:
|
||||||
|
locale === "en-US" ? "Open-Meteo Temperature" : "Open-Meteo 温度",
|
||||||
pointRadius: 2,
|
pointRadius: 2,
|
||||||
tension: 0.28,
|
tension: 0.28,
|
||||||
},
|
},
|
||||||
@@ -252,9 +415,7 @@ function DailyTemperatureChart({ dateStr }: { dateStr: string }) {
|
|||||||
},
|
},
|
||||||
type: "line",
|
type: "line",
|
||||||
} satisfies ChartConfiguration<"line">;
|
} satisfies ChartConfiguration<"line">;
|
||||||
},
|
}, [detail, isToday, locale, todayChartData, view]);
|
||||||
[detail, isToday, locale, todayChartData, view],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
@@ -274,6 +435,7 @@ export function FutureForecastModal() {
|
|||||||
const store = useDashboardStore();
|
const store = useDashboardStore();
|
||||||
const { locale, t } = useI18n();
|
const { locale, t } = useI18n();
|
||||||
const detail = store.selectedDetail;
|
const detail = store.selectedDetail;
|
||||||
|
const marketScan = store.selectedMarketScan;
|
||||||
const dateStr = store.futureModalDate;
|
const dateStr = store.futureModalDate;
|
||||||
|
|
||||||
if (!detail || !dateStr) return null;
|
if (!detail || !dateStr) return null;
|
||||||
@@ -289,6 +451,88 @@ export function FutureForecastModal() {
|
|||||||
"--score-position": scorePosition,
|
"--score-position": scorePosition,
|
||||||
} as CSSProperties & { "--score-position": string };
|
} as CSSProperties & { "--score-position": string };
|
||||||
const weatherSummary = getWeatherSummary(detail, locale);
|
const weatherSummary = getWeatherSummary(detail, locale);
|
||||||
|
const marketMidpoint = formatMarketPercent(
|
||||||
|
marketScan?.market_price ?? marketScan?.yes_token?.implied_probability,
|
||||||
|
);
|
||||||
|
const modelProbability = formatMarketPercent(marketScan?.model_probability);
|
||||||
|
const marketYesBuy = formatMarketPriceCents(marketScan?.yes_buy);
|
||||||
|
const marketYesSell = formatMarketPriceCents(marketScan?.yes_sell);
|
||||||
|
const marketNoBuy = formatMarketPriceCents(
|
||||||
|
resolveCounterPrice(marketScan?.no_buy, marketScan?.yes_buy),
|
||||||
|
);
|
||||||
|
const marketNoSell = formatMarketPriceCents(
|
||||||
|
resolveCounterPrice(marketScan?.no_sell, marketScan?.yes_sell),
|
||||||
|
);
|
||||||
|
const marketEdge = formatSignedPercent(marketScan?.edge_percent);
|
||||||
|
const marketSpread = formatSpreadPercent(
|
||||||
|
marketScan?.yes_buy,
|
||||||
|
marketScan?.yes_sell,
|
||||||
|
);
|
||||||
|
const topBucket = Array.isArray(marketScan?.top_buckets)
|
||||||
|
? [...marketScan.top_buckets]
|
||||||
|
.map((item) => ({
|
||||||
|
...item,
|
||||||
|
probability: normalizeMarketValue(item?.probability),
|
||||||
|
}))
|
||||||
|
.filter(
|
||||||
|
(
|
||||||
|
item,
|
||||||
|
): item is {
|
||||||
|
label?: string | null;
|
||||||
|
bucket?: string | null;
|
||||||
|
range?: string | null;
|
||||||
|
value?: number | null;
|
||||||
|
temp?: number | null;
|
||||||
|
probability: number;
|
||||||
|
} => item.probability != null,
|
||||||
|
)
|
||||||
|
.sort((a, b) => b.probability - a.probability)[0]
|
||||||
|
: null;
|
||||||
|
const settlementBucketLabel = formatBucketLabel(
|
||||||
|
marketScan?.temperature_bucket,
|
||||||
|
);
|
||||||
|
const hottestBucketLabel = formatBucketLabel(topBucket);
|
||||||
|
const hottestBucketProb = formatMarketPercent(topBucket?.probability);
|
||||||
|
const marketSignal = marketScan?.signal_label
|
||||||
|
? `${marketScan.signal_label}${
|
||||||
|
marketScan.confidence ? ` / ${marketScan.confidence}` : ""
|
||||||
|
}`
|
||||||
|
: "--";
|
||||||
|
const metarParsed = parseMetarTempDew(detail.current?.raw_metar);
|
||||||
|
const fallbackDewpoint =
|
||||||
|
detail.current?.dewpoint ??
|
||||||
|
metarParsed.dewC ??
|
||||||
|
(Array.isArray(detail.hourly_next_48h?.dew_point)
|
||||||
|
? detail.hourly_next_48h?.dew_point?.[0]
|
||||||
|
: null);
|
||||||
|
const fallbackHumidity =
|
||||||
|
detail.current?.humidity ??
|
||||||
|
estimateHumidityFromTempDew(
|
||||||
|
detail.current?.temp ?? metarParsed.tempC,
|
||||||
|
fallbackDewpoint,
|
||||||
|
);
|
||||||
|
const topObservedTemp =
|
||||||
|
detail.current?.max_so_far != null
|
||||||
|
? detail.current.max_so_far
|
||||||
|
: detail.current?.temp;
|
||||||
|
const currentTempText =
|
||||||
|
detail.current?.temp != null
|
||||||
|
? `${detail.current.temp}${detail.temp_symbol}`
|
||||||
|
: "--";
|
||||||
|
const humidityText =
|
||||||
|
fallbackHumidity != null ? `${Math.round(fallbackHumidity)}%` : "--";
|
||||||
|
const dewpointText =
|
||||||
|
fallbackDewpoint != null
|
||||||
|
? `${fallbackDewpoint}${detail.temp_symbol}`
|
||||||
|
: "--";
|
||||||
|
const windText =
|
||||||
|
detail.current?.wind_speed_kt != null
|
||||||
|
? `${detail.current.wind_speed_kt} kt`
|
||||||
|
: "--";
|
||||||
|
const visibilityText = parseVisibilityText(
|
||||||
|
detail.current?.raw_metar,
|
||||||
|
detail.current?.visibility_mi,
|
||||||
|
);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div
|
<div
|
||||||
@@ -304,7 +548,11 @@ export function FutureForecastModal() {
|
|||||||
>
|
>
|
||||||
<div className="modal-content large future-modal">
|
<div className="modal-content large future-modal">
|
||||||
<div className="modal-header">
|
<div className="modal-header">
|
||||||
<h2 id="future-modal-title">
|
<h2
|
||||||
|
id="future-modal-title"
|
||||||
|
className="future-modal-title-with-actions"
|
||||||
|
>
|
||||||
|
<span>
|
||||||
{isToday
|
{isToday
|
||||||
? t("future.todayTitle", {
|
? t("future.todayTitle", {
|
||||||
city: detail.display_name.toUpperCase(),
|
city: detail.display_name.toUpperCase(),
|
||||||
@@ -313,11 +561,36 @@ export function FutureForecastModal() {
|
|||||||
city: detail.display_name.toUpperCase(),
|
city: detail.display_name.toUpperCase(),
|
||||||
date: dateStr,
|
date: dateStr,
|
||||||
})}
|
})}
|
||||||
|
</span>
|
||||||
|
<button
|
||||||
|
className={clsx(
|
||||||
|
"future-refresh-btn",
|
||||||
|
store.loadingState.marketScan && "spinning",
|
||||||
|
)}
|
||||||
|
onClick={() => store.openTodayModal(true)}
|
||||||
|
title={locale === "en-US" ? "Refresh Data" : "刷新数据"}
|
||||||
|
>
|
||||||
|
<svg
|
||||||
|
width="14"
|
||||||
|
height="14"
|
||||||
|
viewBox="0 0 24 24"
|
||||||
|
fill="none"
|
||||||
|
stroke="currentColor"
|
||||||
|
strokeWidth="2.5"
|
||||||
|
strokeLinecap="round"
|
||||||
|
strokeLinejoin="round"
|
||||||
|
>
|
||||||
|
<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8" />
|
||||||
|
<path d="M3 3v5h5" />
|
||||||
|
</svg>
|
||||||
|
</button>
|
||||||
</h2>
|
</h2>
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
className="modal-close"
|
className="modal-close"
|
||||||
aria-label={isToday ? t("future.closeTodayAria") : t("future.closeDateAria")}
|
aria-label={
|
||||||
|
isToday ? t("future.closeTodayAria") : t("future.closeDateAria")
|
||||||
|
}
|
||||||
onClick={store.closeFutureModal}
|
onClick={store.closeFutureModal}
|
||||||
>
|
>
|
||||||
×
|
×
|
||||||
@@ -325,117 +598,282 @@ export function FutureForecastModal() {
|
|||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="modal-body future-modal-body">
|
<div className="modal-body future-modal-body">
|
||||||
<div className="history-stats">
|
{isToday ? (
|
||||||
{isToday && (
|
<div className="future-v2-layout">
|
||||||
<>
|
<aside className="future-v2-left">
|
||||||
<div className="h-stat-card">
|
<section className="future-v2-card future-v2-hero-card">
|
||||||
<span className="label">{t("future.currentObs")}</span>
|
<h3 className="future-v2-hero-title">
|
||||||
<span className="val">
|
{locale === "en-US"
|
||||||
{detail.current?.temp ?? "--"}
|
? "Current Conditions"
|
||||||
{detail.temp_symbol} @{detail.current?.obs_time || "--"}
|
: "实况与气象特征"}
|
||||||
|
</h3>
|
||||||
|
<div className="future-v2-hero-main">
|
||||||
|
<div className="future-v2-hero-temp">{currentTempText}</div>
|
||||||
|
<div className="future-v2-hero-divider" />
|
||||||
|
<div className="future-v2-hero-weather">
|
||||||
|
<span className="future-v2-hero-icon">
|
||||||
|
<WeatherIcon
|
||||||
|
emoji={weatherSummary.weatherIcon}
|
||||||
|
size={42}
|
||||||
|
/>
|
||||||
</span>
|
</span>
|
||||||
|
<span>{weatherSummary.weatherText}</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="h-stat-card">
|
</div>
|
||||||
<span className="label">{t("future.currentWeather")}</span>
|
<div className="future-v2-hero-obs">
|
||||||
<span className="val">
|
@{detail.current?.obs_time || "--"}
|
||||||
{weatherSummary.weatherIcon} {weatherSummary.weatherText}
|
</div>
|
||||||
|
<div className="future-v2-mini-grid">
|
||||||
|
<div className="future-v2-mini-item">
|
||||||
|
<span>
|
||||||
|
{locale === "en-US" ? "High So Far" : "目前最高温"}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
<strong>
|
||||||
<div className="h-stat-card">
|
{topObservedTemp ?? "--"}
|
||||||
<span className="label">{t("future.wuRef")}</span>
|
|
||||||
<span className="val">
|
|
||||||
{detail.current?.wu_settlement ?? "--"}
|
|
||||||
{detail.temp_symbol}
|
{detail.temp_symbol}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
<div className="future-v2-mini-item">
|
||||||
|
<span>{locale === "en-US" ? "Sunrise" : "日出时间"}</span>
|
||||||
|
<strong>{detail.forecast?.sunrise || "--"}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="future-v2-mini-item">
|
||||||
|
<span>{locale === "en-US" ? "Sunset" : "日落时间"}</span>
|
||||||
|
<strong>{detail.forecast?.sunset || "--"}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="future-v2-mini-item">
|
||||||
|
<span>
|
||||||
|
{locale === "en-US" ? "Sunshine" : "日照时长"}
|
||||||
</span>
|
</span>
|
||||||
</div>
|
<strong>
|
||||||
<div className="h-stat-card">
|
|
||||||
<span className="label">{t("future.sunrise")}</span>
|
|
||||||
<span className="val">{detail.forecast?.sunrise || "--"}</span>
|
|
||||||
</div>
|
|
||||||
<div className="h-stat-card">
|
|
||||||
<span className="label">{t("future.sunset")}</span>
|
|
||||||
<span className="val">{detail.forecast?.sunset || "--"}</span>
|
|
||||||
</div>
|
|
||||||
<div className="h-stat-card">
|
|
||||||
<span className="label">{t("future.sunshine")}</span>
|
|
||||||
<span className="val">
|
|
||||||
{detail.forecast?.sunshine_hours != null
|
{detail.forecast?.sunshine_hours != null
|
||||||
? `${detail.forecast.sunshine_hours}h`
|
? `${detail.forecast.sunshine_hours}h`
|
||||||
: "--"}
|
: "--"}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="future-v2-card">
|
||||||
|
<h4 className="future-v2-card-title">
|
||||||
|
{locale === "en-US" ? "Current Metrics" : "当前指标"}
|
||||||
|
</h4>
|
||||||
|
<div className="future-v2-mini-grid future-v2-mini-grid-tight">
|
||||||
|
<div className="future-v2-mini-item">
|
||||||
|
<span>{locale === "en-US" ? "Humidity" : "湿度"}</span>
|
||||||
|
<strong>{humidityText}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="future-v2-mini-item">
|
||||||
|
<span>{locale === "en-US" ? "Dew Point" : "露点"}</span>
|
||||||
|
<strong>{dewpointText}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="future-v2-mini-item">
|
||||||
|
<span>{locale === "en-US" ? "Wind" : "风速"}</span>
|
||||||
|
<strong>{windText}</strong>
|
||||||
|
</div>
|
||||||
|
<div className="future-v2-mini-item">
|
||||||
|
<span>
|
||||||
|
{locale === "en-US" ? "Visibility" : "能见度"}
|
||||||
</span>
|
</span>
|
||||||
|
<strong>{visibilityText}</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<section className="future-v2-card">
|
||||||
|
<h4 className="future-v2-card-title">
|
||||||
|
{locale === "en-US" ? "Market Alignment" : "市场对照"}
|
||||||
|
</h4>
|
||||||
|
<div className="future-v2-market-v3">
|
||||||
|
{/* Loading Overlay */}
|
||||||
|
{store.loadingState.marketScan && (
|
||||||
|
<div className="market-layer-loading-overlay">
|
||||||
|
<div
|
||||||
|
className="loading-spinner"
|
||||||
|
style={{
|
||||||
|
marginBottom: "8px",
|
||||||
|
width: "24px",
|
||||||
|
height: "24px",
|
||||||
|
borderWidth: "2px",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{locale === "en-US"
|
||||||
|
? "Crunching Polymarket Edges..."
|
||||||
|
: "正在计算市场对手盘..."}
|
||||||
</div>
|
</div>
|
||||||
</>
|
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="h-stat-card">
|
{/* Layer 1: Target & Edge */}
|
||||||
<span className="label">
|
<div className="market-layer-target">
|
||||||
{isToday ? t("future.todayForecastHigh") : t("future.targetForecast")}
|
<div className="market-target-header">
|
||||||
|
<span>
|
||||||
|
{locale === "en-US"
|
||||||
|
? "Target Bucket:"
|
||||||
|
: "结算温度区间:"}
|
||||||
</span>
|
</span>
|
||||||
<span className="val">
|
<strong className="market-target-bucket">
|
||||||
{view.forecastEntry?.max_temp ?? "--"}
|
{settlementBucketLabel}
|
||||||
{detail.temp_symbol}
|
</strong>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="market-edge-box">
|
||||||
|
<div className="market-edge-header">
|
||||||
|
<span>
|
||||||
|
📊 {locale === "en-US" ? "Core Edge" : "核心测算"}
|
||||||
|
</span>
|
||||||
|
<strong
|
||||||
|
className={clsx(
|
||||||
|
"market-edge-val",
|
||||||
|
Number(marketScan?.edge_percent) > 0
|
||||||
|
? "positive"
|
||||||
|
: "negative",
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
({marketEdge})
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
<div className="market-edge-compare">
|
||||||
|
<div className="edge-stat">
|
||||||
|
<span className="edge-label">
|
||||||
|
{locale === "en-US" ? "Model Prob:" : "模型概率:"}
|
||||||
|
</span>
|
||||||
|
<strong className="edge-value">
|
||||||
|
{modelProbability}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
<div className="edge-stat">
|
||||||
|
<span className="edge-label">
|
||||||
|
{locale === "en-US"
|
||||||
|
? "Market Prob:"
|
||||||
|
: "市场概率:"}
|
||||||
|
</span>
|
||||||
|
<strong className="edge-value">
|
||||||
|
{marketMidpoint}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Layer 2: Order Book */}
|
||||||
|
<div className="market-layer-book">
|
||||||
|
<div className="market-sub-title">
|
||||||
|
📈 {locale === "en-US" ? "Order Book" : "订单簿报价"}
|
||||||
|
</div>
|
||||||
|
<div className="market-book-row">
|
||||||
|
<span className="book-label">YES:</span>
|
||||||
|
<span className="book-quote">
|
||||||
|
<strong>{marketYesBuy}</strong> /{" "}
|
||||||
|
<strong>{marketYesSell}</strong>
|
||||||
|
</span>
|
||||||
|
<span className="book-spread">
|
||||||
|
({locale === "en-US" ? "Spread" : "价差"}{" "}
|
||||||
|
{marketSpread})
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="h-stat-card">
|
<div className="market-book-row">
|
||||||
<span className="label">{t("future.deb")}</span>
|
<span className="book-label">NO:</span>
|
||||||
<span className="val">
|
<span className="book-quote">
|
||||||
{view.deb ?? "--"}
|
<strong>{marketNoBuy}</strong> /{" "}
|
||||||
{detail.temp_symbol}
|
<strong>{marketNoSell}</strong>
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="h-stat-card">
|
|
||||||
<span className="label">{t("future.mu")}</span>
|
|
||||||
<span className="val">
|
|
||||||
{view.mu != null ? `${view.mu.toFixed(1)}${detail.temp_symbol}` : "--"}
|
|
||||||
</span>
|
|
||||||
</div>
|
|
||||||
<div className="h-stat-card">
|
|
||||||
<span className="label">{t("future.score")}</span>
|
|
||||||
<span className="val">
|
|
||||||
{view.front.score > 0 ? "+" : ""}
|
|
||||||
{view.front.score}
|
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<section className="future-modal-section">
|
{/* Layer 3: Context */}
|
||||||
<h3>{isToday ? t("future.todayTempTrend") : t("future.targetTempTrend")}</h3>
|
<div className="market-layer-context">
|
||||||
|
<div className="market-sub-title">
|
||||||
|
👀 {locale === "en-US" ? "Market Radar" : "情绪雷达"}
|
||||||
|
</div>
|
||||||
|
<div className="market-context-row">
|
||||||
|
<span>
|
||||||
|
{locale === "en-US"
|
||||||
|
? "Top Volume Bucket:"
|
||||||
|
: "市场当前押注最热:"}
|
||||||
|
</span>
|
||||||
|
<strong>
|
||||||
|
{hottestBucketLabel}{" "}
|
||||||
|
{hottestBucketProb !== "--"
|
||||||
|
? `(${hottestBucketProb})`
|
||||||
|
: ""}
|
||||||
|
</strong>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="future-v2-market-signal mt-3">
|
||||||
|
{locale === "en-US" ? "Signal" : "信号"}:{" "}
|
||||||
|
<strong>{marketSignal}</strong>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
</aside>
|
||||||
|
|
||||||
|
<main className="future-v2-right">
|
||||||
|
<section className="future-modal-section future-v2-main-chart">
|
||||||
|
<h3>
|
||||||
|
{locale === "en-US"
|
||||||
|
? "Today's temperature forecast (obs + market)"
|
||||||
|
: "今日气温预测(观测 + 市场)"}
|
||||||
|
</h3>
|
||||||
<DailyTemperatureChart dateStr={dateStr} />
|
<DailyTemperatureChart dateStr={dateStr} />
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<div className="future-modal-grid">
|
<div className="future-modal-grid">
|
||||||
<section className="future-modal-section">
|
<section className="future-modal-section">
|
||||||
<h3>{t("future.probability")}</h3>
|
<h3>{t("future.probability")}</h3>
|
||||||
<ProbabilityDistribution detail={detail} targetDate={dateStr} hideTitle />
|
<div style={{ position: "relative", minHeight: "120px" }}>
|
||||||
|
{/* Loading Overlay */}
|
||||||
|
{store.loadingState.marketScan && (
|
||||||
|
<div className="market-layer-loading-overlay">
|
||||||
|
<div
|
||||||
|
className="loading-spinner"
|
||||||
|
style={{
|
||||||
|
marginBottom: "8px",
|
||||||
|
width: "24px",
|
||||||
|
height: "24px",
|
||||||
|
borderWidth: "2px",
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
{locale === "en-US"
|
||||||
|
? "Crunching Polymarket Edges..."
|
||||||
|
: "正在同步市场挂单..."}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<ProbabilityDistribution
|
||||||
|
detail={detail}
|
||||||
|
targetDate={dateStr}
|
||||||
|
hideTitle
|
||||||
|
marketScan={marketScan}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
<section className="future-modal-section">
|
<section className="future-modal-section">
|
||||||
<h3>{t("future.models")}</h3>
|
<h3>{t("future.models")}</h3>
|
||||||
<ModelForecast detail={detail} targetDate={dateStr} hideTitle />
|
<ModelForecast
|
||||||
|
detail={detail}
|
||||||
|
targetDate={dateStr}
|
||||||
|
hideTitle
|
||||||
|
/>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<div className="future-modal-grid">
|
<div className="future-modal-grid">
|
||||||
<section className="future-modal-section">
|
<section className="future-modal-section">
|
||||||
<h3>
|
<h3>{t("future.structureToday")}</h3>
|
||||||
<span className="section-inline-icon" aria-hidden="true">
|
|
||||||
<svg
|
|
||||||
viewBox="0 0 24 24"
|
|
||||||
fill="none"
|
|
||||||
stroke="currentColor"
|
|
||||||
strokeWidth="1.9"
|
|
||||||
strokeLinecap="round"
|
|
||||||
strokeLinejoin="round"
|
|
||||||
>
|
|
||||||
<path d="M4 19V5" />
|
|
||||||
<path d="M10 19V10" />
|
|
||||||
<path d="M16 19V7" />
|
|
||||||
<path d="M22 19V13" />
|
|
||||||
</svg>
|
|
||||||
</span>
|
|
||||||
{isToday ? t("future.structureToday") : t("future.structureDate")}
|
|
||||||
</h3>
|
|
||||||
<div className="future-front-score">
|
<div className="future-front-score">
|
||||||
<div className="future-front-bar" style={barStyle} />
|
<div className="future-front-bar" style={barStyle}>
|
||||||
|
<div
|
||||||
|
style={{
|
||||||
|
position: "absolute",
|
||||||
|
top: 0,
|
||||||
|
bottom: 0,
|
||||||
|
left: "50%",
|
||||||
|
width: "2px",
|
||||||
|
background: "rgba(255, 255, 255, 0.2)",
|
||||||
|
transform: "translateX(-50%)",
|
||||||
|
zIndex: 1,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
<div className="future-front-meta">
|
<div className="future-front-meta">
|
||||||
<span className="future-front-pill">
|
<span className="future-front-pill">
|
||||||
{t("future.judgement")}: {view.front.label}
|
{t("future.judgement")}: {view.front.label}
|
||||||
@@ -445,15 +883,17 @@ export function FutureForecastModal() {
|
|||||||
{t(`confidence.${view.front.confidence}`)}
|
{t(`confidence.${view.front.confidence}`)}
|
||||||
</span>
|
</span>
|
||||||
<span className="future-front-pill">
|
<span className="future-front-pill">
|
||||||
{t("future.maxPrecip")}: {Math.round(view.front.precipMax)}%
|
{t("future.maxPrecip")}:{" "}
|
||||||
|
{Math.round(view.front.precipMax)}%
|
||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="future-text-block">{view.front.summary}</div>
|
|
||||||
</div>
|
</div>
|
||||||
<div className="future-trend-grid">
|
<div className="future-trend-grid">
|
||||||
{view.front.metrics.map((metric) => (
|
{view.front.metrics.slice(0, 6).map((metric) => (
|
||||||
<div key={metric.label} className="future-trend-card">
|
<div key={metric.label} className="future-trend-card">
|
||||||
<div className="future-trend-label">{metric.label}</div>
|
<div className="future-trend-label">
|
||||||
|
{metric.label}
|
||||||
|
</div>
|
||||||
<div
|
<div
|
||||||
className={clsx(
|
className={clsx(
|
||||||
"future-trend-value",
|
"future-trend-value",
|
||||||
@@ -472,70 +912,105 @@ export function FutureForecastModal() {
|
|||||||
<section className="future-modal-section">
|
<section className="future-modal-section">
|
||||||
<h3>{t("future.ai")}</h3>
|
<h3>{t("future.ai")}</h3>
|
||||||
<div className="future-text-block">
|
<div className="future-text-block">
|
||||||
{ai.summary ? <div>{ai.summary}</div> : null}
|
{ai.summary ? (
|
||||||
|
<div>{ai.summary}</div>
|
||||||
|
) : (
|
||||||
|
<div>{t("future.noAi")}</div>
|
||||||
|
)}
|
||||||
{ai.bullets.length > 0 && (
|
{ai.bullets.length > 0 && (
|
||||||
<div style={{ marginTop: ai.summary ? "10px" : 0 }}>
|
<div style={{ marginTop: "10px" }}>
|
||||||
{ai.bullets.map((item) => (
|
{ai.bullets.slice(0, 3).map((item) => (
|
||||||
<div key={item}>{item}</div>
|
<div key={item}>{item}</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
<div style={{ marginTop: "12px" }}>
|
||||||
{!ai.summary && ai.bullets.length === 0 && (
|
{nowcastRows.slice(0, 4).map(([label, value]) => (
|
||||||
<div>{t("future.noAi")}</div>
|
|
||||||
)}
|
|
||||||
|
|
||||||
<div style={{ marginTop: "14px" }}>
|
|
||||||
{nowcastRows.map(([label, value]) => (
|
|
||||||
<div key={label}>
|
<div key={label}>
|
||||||
<strong>{label}: </strong>
|
<strong>{label}: </strong>
|
||||||
{value}
|
{value}
|
||||||
</div>
|
</div>
|
||||||
))}
|
))}
|
||||||
</div>
|
</div>
|
||||||
|
{riskLines.length > 0 && (
|
||||||
{view.front.weatherGovPeriods.length > 0 && (
|
<div style={{ marginTop: "12px" }}>
|
||||||
<div style={{ marginTop: "10px" }}>
|
<strong>
|
||||||
<strong>{t("future.weatherGov")}: </strong>
|
{locale === "en-US" ? "Risk" : "风险"}:{" "}
|
||||||
{view.front.weatherGovPeriods
|
</strong>
|
||||||
.map((period) => period.short_forecast || period.detailed_forecast)
|
{riskLines[0]}
|
||||||
.filter(Boolean)
|
</div>
|
||||||
.join(" / ")}
|
)}
|
||||||
|
{climateDrivers.length > 0 && (
|
||||||
|
<div style={{ marginTop: "8px" }}>
|
||||||
|
<strong>
|
||||||
|
{locale === "en-US" ? "Climate" : "气候"}:{" "}
|
||||||
|
</strong>
|
||||||
|
{climateDrivers[0].text}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<div className="history-stats">
|
||||||
|
<div className="h-stat-card">
|
||||||
|
<span className="label">{t("future.targetForecast")}</span>
|
||||||
|
<span className="val">
|
||||||
|
{view.forecastEntry?.max_temp ?? "--"}
|
||||||
|
{detail.temp_symbol}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-stat-card">
|
||||||
|
<span className="label">{t("future.deb")}</span>
|
||||||
|
<span className="val">
|
||||||
|
{view.deb ?? "--"}
|
||||||
|
{detail.temp_symbol}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-stat-card">
|
||||||
|
<span className="label">{t("future.mu")}</span>
|
||||||
|
<span className="val">
|
||||||
|
{view.mu != null
|
||||||
|
? `${view.mu.toFixed(1)}${detail.temp_symbol}`
|
||||||
|
: "--"}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
<div className="h-stat-card">
|
||||||
|
<span className="label">{t("future.score")}</span>
|
||||||
|
<span className="val">
|
||||||
|
{view.front.score > 0 ? "+" : ""}
|
||||||
|
{view.front.score}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<section className="future-modal-section">
|
||||||
|
<h3>{t("future.targetTempTrend")}</h3>
|
||||||
|
<DailyTemperatureChart dateStr={dateStr} />
|
||||||
|
</section>
|
||||||
|
|
||||||
{isToday && (
|
|
||||||
<div className="future-modal-grid">
|
<div className="future-modal-grid">
|
||||||
<section className="future-modal-section">
|
<section className="future-modal-section">
|
||||||
<h3>{t("future.risk")}</h3>
|
<h3>{t("future.probability")}</h3>
|
||||||
<div className="risk-info">
|
<ProbabilityDistribution
|
||||||
{riskLines.map((line) => (
|
detail={detail}
|
||||||
<div key={line} className="risk-row">
|
targetDate={dateStr}
|
||||||
<span style={{ color: "var(--accent-cyan)", opacity: 0.6 }}>
|
hideTitle
|
||||||
•
|
/>
|
||||||
</span>
|
|
||||||
<span>{line}</span>
|
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</section>
|
</section>
|
||||||
|
|
||||||
<section className="future-modal-section">
|
<section className="future-modal-section">
|
||||||
<h3>{t("future.climate")}</h3>
|
<h3>{t("future.models")}</h3>
|
||||||
<div className="insight-list">
|
<ModelForecast
|
||||||
{climateDrivers.map((driver) => (
|
detail={detail}
|
||||||
<div key={driver.label} className="insight-item">
|
targetDate={dateStr}
|
||||||
<div className="insight-title">{driver.label}</div>
|
hideTitle
|
||||||
<div className="insight-text">{driver.text}</div>
|
/>
|
||||||
</div>
|
|
||||||
))}
|
|
||||||
</div>
|
|
||||||
</section>
|
</section>
|
||||||
</div>
|
</div>
|
||||||
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -5,7 +5,12 @@ import clsx from "clsx";
|
|||||||
import { useChart } from "@/hooks/useChart";
|
import { useChart } from "@/hooks/useChart";
|
||||||
import { useCityData, useDashboardStore } from "@/hooks/useDashboardStore";
|
import { useCityData, useDashboardStore } from "@/hooks/useDashboardStore";
|
||||||
import { useI18n } from "@/hooks/useI18n";
|
import { useI18n } from "@/hooks/useI18n";
|
||||||
import { CityDetail } from "@/lib/dashboard-types";
|
import {
|
||||||
|
CityDetail,
|
||||||
|
MarketScan,
|
||||||
|
MarketTopBucket,
|
||||||
|
ProbabilityBucket,
|
||||||
|
} from "@/lib/dashboard-types";
|
||||||
import {
|
import {
|
||||||
getHeroMetaItems,
|
getHeroMetaItems,
|
||||||
getModelView,
|
getModelView,
|
||||||
@@ -17,7 +22,101 @@ import {
|
|||||||
} from "@/lib/dashboard-utils";
|
} from "@/lib/dashboard-utils";
|
||||||
|
|
||||||
function EmptyState({ text }: { text: string }) {
|
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() {
|
export function HeroSummary() {
|
||||||
@@ -55,7 +154,9 @@ export function HeroSummary() {
|
|||||||
</div>
|
</div>
|
||||||
<div className="hero-details">
|
<div className="hero-details">
|
||||||
<div className="hero-item">
|
<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">
|
<span className="value">
|
||||||
{current.temp != null
|
{current.temp != null
|
||||||
? `${current.temp}${data.temp_symbol} @${current.obs_time || "--"}`
|
? `${current.temp}${data.temp_symbol} @${current.obs_time || "--"}`
|
||||||
@@ -73,7 +174,9 @@ export function HeroSummary() {
|
|||||||
</span>
|
</span>
|
||||||
</div>
|
</div>
|
||||||
<div className="hero-item">
|
<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">
|
<span className="value">
|
||||||
{data.deb?.prediction != null
|
{data.deb?.prediction != null
|
||||||
? `${data.deb.prediction}${data.temp_symbol}`
|
? `${data.deb.prediction}${data.temp_symbol}`
|
||||||
@@ -95,8 +198,7 @@ export function TemperatureChart() {
|
|||||||
const { locale, t } = useI18n();
|
const { locale, t } = useI18n();
|
||||||
const chartData = data ? getTemperatureChartData(data, locale) : null;
|
const chartData = data ? getTemperatureChartData(data, locale) : null;
|
||||||
|
|
||||||
const canvasRef = useChart(
|
const canvasRef = useChart(() => {
|
||||||
() => {
|
|
||||||
if (!data || !chartData) {
|
if (!data || !chartData) {
|
||||||
return {
|
return {
|
||||||
data: { datasets: [], labels: [] },
|
data: { datasets: [], labels: [] },
|
||||||
@@ -104,7 +206,9 @@ export function TemperatureChart() {
|
|||||||
} satisfies ChartConfiguration<"line">;
|
} satisfies ChartConfiguration<"line">;
|
||||||
}
|
}
|
||||||
|
|
||||||
const datasets: NonNullable<ChartConfiguration<"line">["data"]>["datasets"] = [];
|
const datasets: NonNullable<
|
||||||
|
ChartConfiguration<"line">["data"]
|
||||||
|
>["datasets"] = [];
|
||||||
|
|
||||||
if (chartData.datasets.hasMgmHourly) {
|
if (chartData.datasets.hasMgmHourly) {
|
||||||
datasets.push({
|
datasets.push({
|
||||||
@@ -228,9 +332,7 @@ export function TemperatureChart() {
|
|||||||
},
|
},
|
||||||
type: "line",
|
type: "line",
|
||||||
} satisfies ChartConfiguration<"line">;
|
} satisfies ChartConfiguration<"line">;
|
||||||
},
|
}, [data, chartData, locale]);
|
||||||
[data, chartData, locale],
|
|
||||||
);
|
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="chart-section">
|
<section className="chart-section">
|
||||||
@@ -238,7 +340,9 @@ export function TemperatureChart() {
|
|||||||
<div className="chart-wrapper">
|
<div className="chart-wrapper">
|
||||||
<canvas ref={canvasRef} />
|
<canvas ref={canvasRef} />
|
||||||
</div>
|
</div>
|
||||||
<div className="chart-legend">{chartData?.legendText || t("section.chartEmpty")}</div>
|
<div className="chart-legend">
|
||||||
|
{chartData?.legendText || t("section.chartEmpty")}
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -247,13 +351,28 @@ export function ProbabilityDistribution({
|
|||||||
detail,
|
detail,
|
||||||
hideTitle = false,
|
hideTitle = false,
|
||||||
targetDate,
|
targetDate,
|
||||||
|
marketScan,
|
||||||
}: {
|
}: {
|
||||||
detail: CityDetail;
|
detail: CityDetail;
|
||||||
hideTitle?: boolean;
|
hideTitle?: boolean;
|
||||||
targetDate?: string | null;
|
targetDate?: string | null;
|
||||||
|
marketScan?: MarketScan | null;
|
||||||
}) {
|
}) {
|
||||||
const { t } = useI18n();
|
const { locale, t } = useI18n();
|
||||||
const view = getProbabilityView(detail, targetDate);
|
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 (
|
return (
|
||||||
<section className="prob-section">
|
<section className="prob-section">
|
||||||
@@ -261,7 +380,11 @@ export function ProbabilityDistribution({
|
|||||||
<div className="prob-bars">
|
<div className="prob-bars">
|
||||||
{view.mu != null && (
|
{view.mu != null && (
|
||||||
<div
|
<div
|
||||||
style={{ color: "var(--text-muted)", fontSize: "11px", marginBottom: "6px" }}
|
style={{
|
||||||
|
color: "var(--text-muted)",
|
||||||
|
fontSize: "11px",
|
||||||
|
marginBottom: "6px",
|
||||||
|
}}
|
||||||
>
|
>
|
||||||
{t("section.mu", {
|
{t("section.mu", {
|
||||||
unit: detail.temp_symbol || "",
|
unit: detail.temp_symbol || "",
|
||||||
@@ -269,16 +392,62 @@ export function ProbabilityDistribution({
|
|||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
{view.probabilities.length === 0 ? (
|
{marketScan?.available && (topMarketBucketText || marketYesText) && (
|
||||||
<EmptyState text={t("section.noProb")} />
|
<div
|
||||||
) : (
|
style={{
|
||||||
view.probabilities.slice(0, 6).map((bucket, index) => {
|
color: "var(--text-secondary)",
|
||||||
const probability = Math.round(Number(bucket.probability || 0) * 100);
|
fontSize: "11px",
|
||||||
return (
|
marginBottom: "6px",
|
||||||
<div key={`${bucket.label || bucket.value || index}`} className="prob-row">
|
}}
|
||||||
<div className="prob-label">
|
>
|
||||||
{bucket.label || `${bucket.value}${detail.temp_symbol}`}
|
{useMarketTopBuckets
|
||||||
|
? locale === "en-US"
|
||||||
|
? `Market top-4 buckets (top): ${topMarketBucketText}`
|
||||||
|
: `市场概率(前4温度桶):最高 ${topMarketBucketText}`
|
||||||
|
: locale === "en-US"
|
||||||
|
? `Market probability (this bucket): ${marketYesText}`
|
||||||
|
: `市场概率(该温度桶): ${marketYesText}`}
|
||||||
</div>
|
</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.slug || bucket.label || index}`}
|
||||||
|
className="prob-row"
|
||||||
|
>
|
||||||
|
<div className="prob-label">{bucketLabel}</div>
|
||||||
<div className="prob-bar-track">
|
<div className="prob-bar-track">
|
||||||
<div
|
<div
|
||||||
className={clsx("prob-bar-fill", `rank-${index}`)}
|
className={clsx("prob-bar-fill", `rank-${index}`)}
|
||||||
@@ -287,6 +456,82 @@ export function ProbabilityDistribution({
|
|||||||
{probability}%
|
{probability}%
|
||||||
</div>
|
</div>
|
||||||
</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>
|
</div>
|
||||||
);
|
);
|
||||||
})
|
})
|
||||||
@@ -313,8 +558,12 @@ export function ModelForecast({
|
|||||||
const numericValues = modelEntries.map(([, value]) => Number(value));
|
const numericValues = modelEntries.map(([, value]) => Number(value));
|
||||||
const comparisonValues =
|
const comparisonValues =
|
||||||
view.deb != null ? [...numericValues, Number(view.deb)] : numericValues;
|
view.deb != null ? [...numericValues, Number(view.deb)] : numericValues;
|
||||||
const minValue = comparisonValues.length ? Math.min(...comparisonValues) - 1 : 0;
|
const minValue = comparisonValues.length
|
||||||
const maxValue = comparisonValues.length ? Math.max(...comparisonValues) + 1 : 1;
|
? Math.min(...comparisonValues) - 1
|
||||||
|
: 0;
|
||||||
|
const maxValue = comparisonValues.length
|
||||||
|
? Math.max(...comparisonValues) + 1
|
||||||
|
: 1;
|
||||||
const range = Math.max(maxValue - minValue, 1);
|
const range = Math.max(maxValue - minValue, 1);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -341,12 +590,18 @@ export function ModelForecast({
|
|||||||
{name}
|
{name}
|
||||||
</div>
|
</div>
|
||||||
<div className="model-bar-track">
|
<div className="model-bar-track">
|
||||||
<div className="model-bar-fill" style={{ width: `${width}%` }}>
|
<div
|
||||||
|
className="model-bar-fill"
|
||||||
|
style={{ width: `${width}%` }}
|
||||||
|
>
|
||||||
{numeric}
|
{numeric}
|
||||||
{detail.temp_symbol}
|
{detail.temp_symbol}
|
||||||
</div>
|
</div>
|
||||||
{debLine != null && (
|
{debLine != null && (
|
||||||
<div className="model-deb-line" style={{ left: `${debLine}%` }} />
|
<div
|
||||||
|
className="model-deb-line"
|
||||||
|
style={{ left: `${debLine}%` }}
|
||||||
|
/>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
@@ -410,13 +665,19 @@ export function ForecastTable() {
|
|||||||
<button
|
<button
|
||||||
key={day.date}
|
key={day.date}
|
||||||
type="button"
|
type="button"
|
||||||
className={clsx("forecast-day", isToday && "today", isSelected && "selected")}
|
className={clsx(
|
||||||
|
"forecast-day",
|
||||||
|
isToday && "today",
|
||||||
|
isSelected && "selected",
|
||||||
|
)}
|
||||||
onClick={() => {
|
onClick={() => {
|
||||||
store.openFutureModal(day.date);
|
store.openFutureModal(day.date);
|
||||||
}}
|
}}
|
||||||
>
|
>
|
||||||
<div className="f-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>
|
||||||
<div className="f-temp">
|
<div className="f-temp">
|
||||||
{day.max_temp}
|
{day.max_temp}
|
||||||
@@ -471,7 +732,9 @@ export function RiskInfo() {
|
|||||||
<h3>{t("section.risk")}</h3>
|
<h3>{t("section.risk")}</h3>
|
||||||
<div className="risk-info">
|
<div className="risk-info">
|
||||||
{!risk.airport ? (
|
{!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">
|
<div className="risk-row">
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import {
|
|||||||
HistoryPoint,
|
HistoryPoint,
|
||||||
HistoryState,
|
HistoryState,
|
||||||
LoadingState,
|
LoadingState,
|
||||||
|
MarketScan,
|
||||||
} from "@/lib/dashboard-types";
|
} from "@/lib/dashboard-types";
|
||||||
|
|
||||||
interface DashboardStoreValue extends DashboardState {
|
interface DashboardStoreValue extends DashboardState {
|
||||||
@@ -35,13 +36,15 @@ interface DashboardStoreValue extends DashboardState {
|
|||||||
openFutureModal: (dateStr: string) => void;
|
openFutureModal: (dateStr: string) => void;
|
||||||
openGuide: () => void;
|
openGuide: () => void;
|
||||||
openHistory: () => Promise<void>;
|
openHistory: () => Promise<void>;
|
||||||
openTodayModal: () => Promise<void>;
|
openTodayModal: (forceRefresh?: boolean) => Promise<void>;
|
||||||
registerMapStopMotion: (stopMotion: () => void) => void;
|
registerMapStopMotion: (stopMotion: () => void) => void;
|
||||||
refreshAll: () => Promise<void>;
|
refreshAll: () => Promise<void>;
|
||||||
refreshSelectedCity: () => Promise<void>;
|
refreshSelectedCity: () => Promise<void>;
|
||||||
|
selectedMarketScan: MarketScan | null;
|
||||||
selectedDetail: CityDetail | null;
|
selectedDetail: CityDetail | null;
|
||||||
selectCity: (cityName: string) => Promise<void>;
|
selectCity: (cityName: string) => Promise<void>;
|
||||||
setForecastDate: (dateStr: string | null) => void;
|
setForecastDate: (dateStr: string | null) => void;
|
||||||
|
marketScanByCityName: Record<string, MarketScan>;
|
||||||
}
|
}
|
||||||
|
|
||||||
const DashboardStoreContext = createContext<DashboardStoreValue | null>(null);
|
const DashboardStoreContext = createContext<DashboardStoreValue | null>(null);
|
||||||
@@ -52,6 +55,7 @@ function getInitialLoadingState(): LoadingState {
|
|||||||
cityDetail: false,
|
cityDetail: false,
|
||||||
history: false,
|
history: false,
|
||||||
refresh: false,
|
refresh: false,
|
||||||
|
marketScan: false,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -177,6 +181,9 @@ export function DashboardStoreProvider({
|
|||||||
const [cityDetailMetaByName, setCityDetailMetaByName] = useState<
|
const [cityDetailMetaByName, setCityDetailMetaByName] = useState<
|
||||||
Record<string, { cachedAt: number; revision: string }>
|
Record<string, { cachedAt: number; revision: string }>
|
||||||
>(() => initialCache.meta);
|
>(() => initialCache.meta);
|
||||||
|
const [marketScanByCityName, setMarketScanByCityName] = useState<
|
||||||
|
Record<string, MarketScan>
|
||||||
|
>({});
|
||||||
const [selectedCity, setSelectedCity] = useState<string | null>(null);
|
const [selectedCity, setSelectedCity] = useState<string | null>(null);
|
||||||
const [isPanelOpen, setIsPanelOpen] = useState(false);
|
const [isPanelOpen, setIsPanelOpen] = useState(false);
|
||||||
const [selectedForecastDate, setSelectedForecastDate] = useState<
|
const [selectedForecastDate, setSelectedForecastDate] = useState<
|
||||||
@@ -203,6 +210,9 @@ export function DashboardStoreProvider({
|
|||||||
const selectedDetail = selectedCity
|
const selectedDetail = selectedCity
|
||||||
? cityDetailsByName[selectedCity] || null
|
? cityDetailsByName[selectedCity] || null
|
||||||
: null;
|
: null;
|
||||||
|
const selectedMarketScan = selectedCity
|
||||||
|
? marketScanByCityName[selectedCity] || null
|
||||||
|
: null;
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
dashboardClient.writeCityDetailCacheBundle(
|
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);
|
const detail = mergeAiAnalysisIfStable(cached, latestDetail);
|
||||||
setCityDetailsByName((current) => ({
|
setCityDetailsByName((current) => ({
|
||||||
...current,
|
...current,
|
||||||
@@ -261,6 +273,29 @@ export function DashboardStoreProvider({
|
|||||||
return detail;
|
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 () => {
|
const loadCities = async () => {
|
||||||
setLoadingState((current) => ({ ...current, cities: true }));
|
setLoadingState((current) => ({ ...current, cities: true }));
|
||||||
try {
|
try {
|
||||||
@@ -330,6 +365,8 @@ export function DashboardStoreProvider({
|
|||||||
try {
|
try {
|
||||||
const detail = await ensureCityDetail(cityName);
|
const detail = await ensureCityDetail(cityName);
|
||||||
setSelectedForecastDate(detail.local_date);
|
setSelectedForecastDate(detail.local_date);
|
||||||
|
// 预热市场数据,不做 await 阻塞,后台静默拉取
|
||||||
|
void ensureCityMarketScan(cityName, false).catch(() => {});
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingState((current) => ({ ...current, cityDetail: false }));
|
setLoadingState((current) => ({ ...current, cityDetail: false }));
|
||||||
}
|
}
|
||||||
@@ -433,24 +470,50 @@ export function DashboardStoreProvider({
|
|||||||
},
|
},
|
||||||
openGuide: () => setIsGuideOpen(true),
|
openGuide: () => setIsGuideOpen(true),
|
||||||
openHistory,
|
openHistory,
|
||||||
openTodayModal: async () => {
|
openTodayModal: async (forceRefresh?: boolean) => {
|
||||||
if (!selectedCity || loadingState.cityDetail || loadingState.refresh) {
|
if (!selectedCity || loadingState.cityDetail) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
mapStopMotionRef.current();
|
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 {
|
try {
|
||||||
const detail = await ensureCityDetail(selectedCity, true);
|
const detail = await ensureCityDetail(selectedCity, true);
|
||||||
setSelectedForecastDate(detail.local_date);
|
setSelectedForecastDate(detail.local_date);
|
||||||
setFutureModalDate(detail.local_date);
|
setFutureModalDate(detail.local_date);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 如果缓存里没有或者想要强制刷新,则拉取最新市场数据
|
||||||
|
await ensureCityMarketScan(
|
||||||
|
selectedCity,
|
||||||
|
forceRefresh || !marketScanByCityName[selectedCity],
|
||||||
|
);
|
||||||
|
} catch {}
|
||||||
} catch {
|
} catch {
|
||||||
const fallback = cityDetailsByName[selectedCity];
|
if (cachedDetail?.local_date) {
|
||||||
if (fallback?.local_date) {
|
setFutureModalDate(cachedDetail.local_date);
|
||||||
setFutureModalDate(fallback.local_date);
|
|
||||||
}
|
}
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingState((current) => ({ ...current, refresh: false }));
|
setLoadingState((current) => ({
|
||||||
|
...current,
|
||||||
|
refresh: false,
|
||||||
|
marketScan: false,
|
||||||
|
}));
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
registerMapStopMotion: (stopMotion: () => void) => {
|
registerMapStopMotion: (stopMotion: () => void) => {
|
||||||
@@ -458,12 +521,14 @@ export function DashboardStoreProvider({
|
|||||||
},
|
},
|
||||||
refreshAll,
|
refreshAll,
|
||||||
refreshSelectedCity,
|
refreshSelectedCity,
|
||||||
|
selectedMarketScan,
|
||||||
selectedCity,
|
selectedCity,
|
||||||
selectedDetail,
|
selectedDetail,
|
||||||
selectedForecastDate,
|
selectedForecastDate,
|
||||||
selectCity,
|
selectCity,
|
||||||
setForecastDate: (dateStr: string | null) =>
|
setForecastDate: (dateStr: string | null) =>
|
||||||
setSelectedForecastDate(dateStr),
|
setSelectedForecastDate(dateStr),
|
||||||
|
marketScanByCityName,
|
||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
cities,
|
cities,
|
||||||
@@ -474,6 +539,8 @@ export function DashboardStoreProvider({
|
|||||||
isPanelOpen,
|
isPanelOpen,
|
||||||
isGuideOpen,
|
isGuideOpen,
|
||||||
loadingState,
|
loadingState,
|
||||||
|
marketScanByCityName,
|
||||||
|
selectedMarketScan,
|
||||||
selectedCity,
|
selectedCity,
|
||||||
selectedDetail,
|
selectedDetail,
|
||||||
selectedForecastDate,
|
selectedForecastDate,
|
||||||
|
|||||||
@@ -3,6 +3,7 @@
|
|||||||
import {
|
import {
|
||||||
CityDetail,
|
CityDetail,
|
||||||
CityListItem,
|
CityListItem,
|
||||||
|
MarketScan,
|
||||||
CitySummary,
|
CitySummary,
|
||||||
HistoryPoint,
|
HistoryPoint,
|
||||||
} from "@/lib/dashboard-types";
|
} from "@/lib/dashboard-types";
|
||||||
@@ -12,6 +13,7 @@ const CACHE_TTL_MS = 5 * 60 * 1000;
|
|||||||
const pendingCityDetailRequests = new Map<string, Promise<CityDetail>>();
|
const pendingCityDetailRequests = new Map<string, Promise<CityDetail>>();
|
||||||
const pendingHistoryRequests = new Map<string, Promise<HistoryPoint[]>>();
|
const pendingHistoryRequests = new Map<string, Promise<HistoryPoint[]>>();
|
||||||
const pendingCitySummaryRequests = new Map<string, Promise<CitySummary>>();
|
const pendingCitySummaryRequests = new Map<string, Promise<CitySummary>>();
|
||||||
|
const pendingMarketScanRequests = new Map<string, Promise<MarketScan | null>>();
|
||||||
|
|
||||||
type CityCacheMeta = {
|
type CityCacheMeta = {
|
||||||
cachedAt: number;
|
cachedAt: number;
|
||||||
@@ -134,20 +136,75 @@ export const dashboardClient = {
|
|||||||
|
|
||||||
async getCityDetail(cityName: string, options?: { force?: boolean }) {
|
async getCityDetail(cityName: string, options?: { force?: boolean }) {
|
||||||
const force = options?.force ?? false;
|
const force = options?.force ?? false;
|
||||||
const requestKey = `${cityName}::${force ? "force" : "cached"}`;
|
if (!force) {
|
||||||
|
const requestKey = `${cityName}::cached`;
|
||||||
const existing = pendingCityDetailRequests.get(requestKey);
|
const existing = pendingCityDetailRequests.get(requestKey);
|
||||||
if (existing) {
|
if (existing) {
|
||||||
return existing;
|
return existing;
|
||||||
}
|
}
|
||||||
|
|
||||||
const request = fetchJson<CityDetail>(
|
const request = fetchJson<CityDetail>(
|
||||||
`/api/city/${normalizeCityName(cityName)}?force_refresh=${force}`,
|
`/api/city/${normalizeCityName(cityName)}?force_refresh=false`,
|
||||||
).finally(() => {
|
).finally(() => {
|
||||||
pendingCityDetailRequests.delete(requestKey);
|
pendingCityDetailRequests.delete(requestKey);
|
||||||
});
|
});
|
||||||
|
|
||||||
pendingCityDetailRequests.set(requestKey, request);
|
pendingCityDetailRequests.set(requestKey, request);
|
||||||
return request;
|
return request;
|
||||||
|
}
|
||||||
|
|
||||||
|
const params = new URLSearchParams({
|
||||||
|
force_refresh: "true",
|
||||||
|
_ts: String(Date.now()),
|
||||||
|
});
|
||||||
|
return fetchJson<CityDetail>(
|
||||||
|
`/api/city/${normalizeCityName(cityName)}?${params.toString()}`,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
|
||||||
|
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) {
|
async getHistory(cityName: string) {
|
||||||
|
|||||||
@@ -181,6 +181,71 @@ export interface DailyModelForecast {
|
|||||||
probabilities?: ProbabilityBucket[];
|
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 {
|
export interface AiAnalysisStructured {
|
||||||
summary?: string | null;
|
summary?: string | null;
|
||||||
text?: string | null;
|
text?: string | null;
|
||||||
@@ -227,6 +292,7 @@ export interface CityDetail {
|
|||||||
updated_at?: string;
|
updated_at?: string;
|
||||||
multi_model_daily?: Record<string, DailyModelForecast>;
|
multi_model_daily?: Record<string, DailyModelForecast>;
|
||||||
source_forecasts?: SourceForecasts;
|
source_forecasts?: SourceForecasts;
|
||||||
|
market_scan?: MarketScan;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface HistoryPoint {
|
export interface HistoryPoint {
|
||||||
@@ -241,6 +307,7 @@ export interface LoadingState {
|
|||||||
cityDetail: boolean;
|
cityDetail: boolean;
|
||||||
refresh: boolean;
|
refresh: boolean;
|
||||||
history: boolean;
|
history: boolean;
|
||||||
|
marketScan?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface HistoryState {
|
export interface HistoryState {
|
||||||
|
|||||||
+12
-8
@@ -71,7 +71,7 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
|||||||
"future.score": "趋势评分",
|
"future.score": "趋势评分",
|
||||||
"future.todayTempTrend": "今日温度走势",
|
"future.todayTempTrend": "今日温度走势",
|
||||||
"future.targetTempTrend": "目标日小时走势",
|
"future.targetTempTrend": "目标日小时走势",
|
||||||
"future.probability": "结算概率分布",
|
"future.probability": "模型结算概率分布",
|
||||||
"future.models": "多模型预报",
|
"future.models": "多模型预报",
|
||||||
"future.structureToday": "今日日内结构信号",
|
"future.structureToday": "今日日内结构信号",
|
||||||
"future.structureDate": "未来 6-48 小时趋势",
|
"future.structureDate": "未来 6-48 小时趋势",
|
||||||
@@ -91,7 +91,7 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
|||||||
|
|
||||||
"section.todayTempTrend": "今日温度走势",
|
"section.todayTempTrend": "今日温度走势",
|
||||||
"section.chartEmpty": "暂无小时级数据",
|
"section.chartEmpty": "暂无小时级数据",
|
||||||
"section.probability": "结算概率分布",
|
"section.probability": "模型结算概率分布",
|
||||||
"section.mu": "动态分布中心 μ = {value}{unit}",
|
"section.mu": "动态分布中心 μ = {value}{unit}",
|
||||||
"section.noProb": "暂无概率数据",
|
"section.noProb": "暂无概率数据",
|
||||||
"section.models": "多模型预报",
|
"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.",
|
"No scenery image matched. You can still review station and observation profile below.",
|
||||||
"detail.profile": "City Profile",
|
"detail.profile": "City Profile",
|
||||||
"detail.todayMiniTrend": "Today's Intraday Trend (Compact)",
|
"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.title": "Multi-day Forecast",
|
||||||
"forecast.empty": "No multi-day forecast available",
|
"forecast.empty": "No multi-day forecast available",
|
||||||
@@ -171,7 +172,7 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
|||||||
"future.score": "Trend Score",
|
"future.score": "Trend Score",
|
||||||
"future.todayTempTrend": "Today's Temperature Trend",
|
"future.todayTempTrend": "Today's Temperature Trend",
|
||||||
"future.targetTempTrend": "Target-day Hourly Trend",
|
"future.targetTempTrend": "Target-day Hourly Trend",
|
||||||
"future.probability": "Settlement Probability Distribution",
|
"future.probability": "Model Settlement Probabilities",
|
||||||
"future.models": "Multi-model Forecast",
|
"future.models": "Multi-model Forecast",
|
||||||
"future.structureToday": "Intraday Structural Signal",
|
"future.structureToday": "Intraday Structural Signal",
|
||||||
"future.structureDate": "6-48h Structural Trend",
|
"future.structureDate": "6-48h Structural Trend",
|
||||||
@@ -179,11 +180,13 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
|||||||
"future.confidence": "Confidence",
|
"future.confidence": "Confidence",
|
||||||
"future.maxPrecip": "Max Precip Probability",
|
"future.maxPrecip": "Max Precip Probability",
|
||||||
"future.ai": "AI Deep Analysis",
|
"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.weatherGov": "weather.gov text",
|
||||||
"future.risk": "Settlement & Deviation Risk",
|
"future.risk": "Settlement & Deviation Risk",
|
||||||
"future.climate": "What Mainly Drives Local Climate",
|
"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.high": "High",
|
||||||
"confidence.medium": "Medium",
|
"confidence.medium": "Medium",
|
||||||
@@ -191,13 +194,14 @@ const MESSAGES: Record<Locale, Record<string, string>> = {
|
|||||||
|
|
||||||
"section.todayTempTrend": "Today's Temperature Trend",
|
"section.todayTempTrend": "Today's Temperature Trend",
|
||||||
"section.chartEmpty": "No hourly data available",
|
"section.chartEmpty": "No hourly data available",
|
||||||
"section.probability": "Settlement Probability Distribution",
|
"section.probability": "Model Settlement Probabilities",
|
||||||
"section.mu": "Dynamic center μ = {value}{unit}",
|
"section.mu": "Dynamic center μ = {value}{unit}",
|
||||||
"section.noProb": "No probability data available",
|
"section.noProb": "No probability data available",
|
||||||
"section.models": "Multi-model Forecast",
|
"section.models": "Multi-model Forecast",
|
||||||
"section.noModels": "No multi-model forecast available",
|
"section.noModels": "No multi-model forecast available",
|
||||||
"section.ai": "AI Deep Analysis",
|
"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.risk": "Data Deviation Risk",
|
||||||
"section.noRiskProfile": "No risk profile available",
|
"section.noRiskProfile": "No risk profile available",
|
||||||
"section.airport": "Airport",
|
"section.airport": "Airport",
|
||||||
|
|||||||
@@ -292,6 +292,20 @@ export interface MarketScan {
|
|||||||
liquidity: number | null;
|
liquidity: number | null;
|
||||||
volume: number | null;
|
volume: number | null;
|
||||||
sparkline: number[];
|
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[];
|
recent_trades: Trade[];
|
||||||
websocket: any;
|
websocket: any;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -421,6 +421,111 @@ def _join_trigger_types_cn(rules: Dict[str, Dict[str, Any]]) -> str:
|
|||||||
return " + ".join(parts)
|
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(
|
def _build_advice_cn(
|
||||||
rules: Dict[str, Dict[str, Any]],
|
rules: Dict[str, Dict[str, Any]],
|
||||||
temp_symbol: str,
|
temp_symbol: str,
|
||||||
@@ -472,6 +577,7 @@ def _build_telegram_messages(
|
|||||||
city_weather: Dict[str, Any],
|
city_weather: Dict[str, Any],
|
||||||
rules: Dict[str, Dict[str, Any]],
|
rules: Dict[str, Dict[str, Any]],
|
||||||
map_url: Optional[str],
|
map_url: Optional[str],
|
||||||
|
market_snapshot: Optional[Dict[str, Any]] = None,
|
||||||
suppression: Optional[Dict[str, Any]] = None,
|
suppression: Optional[Dict[str, Any]] = None,
|
||||||
) -> Dict[str, str]:
|
) -> Dict[str, str]:
|
||||||
temp_symbol = city_weather.get("temp_symbol", "°C")
|
temp_symbol = city_weather.get("temp_symbol", "°C")
|
||||||
@@ -482,6 +588,7 @@ def _build_telegram_messages(
|
|||||||
center_deb = rules.get("ankara_center_deb_hit", {})
|
center_deb = rules.get("ankara_center_deb_hit", {})
|
||||||
momentum = rules.get("momentum_spike", {})
|
momentum = rules.get("momentum_spike", {})
|
||||||
advection = rules.get("advection", {})
|
advection = rules.get("advection", {})
|
||||||
|
market_snapshot = market_snapshot or _extract_market_snapshot(city_weather)
|
||||||
|
|
||||||
if current_temp is None:
|
if current_temp is None:
|
||||||
return {"zh": "", "en": ""}
|
return {"zh": "", "en": ""}
|
||||||
@@ -559,6 +666,30 @@ def _build_telegram_messages(
|
|||||||
lines_zh.append(peak_line)
|
lines_zh.append(peak_line)
|
||||||
if lead_line:
|
if lead_line:
|
||||||
lines_zh.append(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"AI 建议:{advice}")
|
||||||
lines_zh.append(f"点击查看实时地图:{final_map}")
|
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"Peak state: intraday high {max_so_far:.1f}{temp_symbol} at {max_temp_time}, "
|
||||||
f"now off by {rollback:.1f}{temp_symbol}"
|
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"Action: {advice}")
|
||||||
lines_en.append(f"Map: {final_map}")
|
lines_en.append(f"Map: {final_map}")
|
||||||
|
|
||||||
@@ -618,6 +773,7 @@ def build_trading_alerts(
|
|||||||
temp_symbol = city_weather.get("temp_symbol", "°C")
|
temp_symbol = city_weather.get("temp_symbol", "°C")
|
||||||
city = city_weather.get("name", "")
|
city = city_weather.get("name", "")
|
||||||
now = datetime.now(timezone.utc).isoformat()
|
now = datetime.now(timezone.utc).isoformat()
|
||||||
|
market_snapshot = _extract_market_snapshot(city_weather)
|
||||||
|
|
||||||
rules: Dict[str, Dict[str, Any]] = {
|
rules: Dict[str, Dict[str, Any]] = {
|
||||||
"ankara_center_deb_hit": _calc_ankara_center_deb_alert(city_weather, temp_symbol),
|
"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,
|
city_weather=city_weather,
|
||||||
rules=rules,
|
rules=rules,
|
||||||
map_url=map_url,
|
map_url=map_url,
|
||||||
|
market_snapshot=market_snapshot,
|
||||||
suppression=suppression,
|
suppression=suppression,
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -668,6 +825,7 @@ def build_trading_alerts(
|
|||||||
"severity": severity,
|
"severity": severity,
|
||||||
"trigger_count": len(triggered),
|
"trigger_count": len(triggered),
|
||||||
"rules": rules,
|
"rules": rules,
|
||||||
|
"market_snapshot": market_snapshot,
|
||||||
"suppression": suppression,
|
"suppression": suppression,
|
||||||
"triggered_alerts": triggered,
|
"triggered_alerts": triggered,
|
||||||
"telegram": telegram,
|
"telegram": telegram,
|
||||||
|
|||||||
@@ -394,6 +394,7 @@ class PolymarketReadOnlyLayer:
|
|||||||
"liquidity": None,
|
"liquidity": None,
|
||||||
"volume": None,
|
"volume": None,
|
||||||
"sparkline": fallback_sparkline or [],
|
"sparkline": fallback_sparkline or [],
|
||||||
|
"top_buckets": [],
|
||||||
"recent_trades": [],
|
"recent_trades": [],
|
||||||
"websocket": {},
|
"websocket": {},
|
||||||
}
|
}
|
||||||
@@ -485,6 +486,13 @@ class PolymarketReadOnlyLayer:
|
|||||||
|
|
||||||
signal_label, confidence = self._derive_signal(edge_percent, liquidity)
|
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 = {
|
yes_payload = {
|
||||||
"outcome": yes_token.get("outcome") or "Yes",
|
"outcome": yes_token.get("outcome") or "Yes",
|
||||||
"token_id": yes_token.get("token_id"),
|
"token_id": yes_token.get("token_id"),
|
||||||
@@ -551,6 +559,7 @@ class PolymarketReadOnlyLayer:
|
|||||||
"liquidity": liquidity,
|
"liquidity": liquidity,
|
||||||
"volume": volume,
|
"volume": volume,
|
||||||
"sparkline": sparkline_values,
|
"sparkline": sparkline_values,
|
||||||
|
"top_buckets": top_buckets,
|
||||||
"websocket": {
|
"websocket": {
|
||||||
"market_url": market_url,
|
"market_url": market_url,
|
||||||
"asset_ids": [
|
"asset_ids": [
|
||||||
@@ -1174,3 +1183,232 @@ class PolymarketReadOnlyLayer:
|
|||||||
if slug:
|
if slug:
|
||||||
return f"https://polymarket.com/market/{slug}"
|
return f"https://polymarket.com/market/{slug}"
|
||||||
return None
|
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 [])
|
for alert in (alert_payload.get("triggered_alerts") or [])
|
||||||
if alert.get("type")
|
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)
|
return "|".join(trigger_types)
|
||||||
|
|
||||||
|
|
||||||
@@ -127,6 +133,7 @@ def _alert_signature(alert_payload: Dict[str, Any]) -> str:
|
|||||||
breakthrough = rules.get("forecast_breakthrough") or {}
|
breakthrough = rules.get("forecast_breakthrough") or {}
|
||||||
advection = rules.get("advection") or {}
|
advection = rules.get("advection") or {}
|
||||||
suppression = alert_payload.get("suppression") or {}
|
suppression = alert_payload.get("suppression") or {}
|
||||||
|
market = alert_payload.get("market_snapshot") or {}
|
||||||
|
|
||||||
signature_payload = {
|
signature_payload = {
|
||||||
"city": alert_payload.get("city"),
|
"city": alert_payload.get("city"),
|
||||||
@@ -149,6 +156,18 @@ def _alert_signature(alert_payload: Dict[str, Any]) -> str:
|
|||||||
"suppression_reason": suppression.get("reason"),
|
"suppression_reason": suppression.get("reason"),
|
||||||
"suppression_peak_time": suppression.get("max_temp_time"),
|
"suppression_peak_time": suppression.get("max_temp_time"),
|
||||||
"suppression_rollback": round(float(suppression.get("rollback") or 0.0), 1),
|
"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)
|
raw = json.dumps(signature_payload, sort_keys=True, ensure_ascii=True)
|
||||||
return hashlib.sha1(raw.encode("utf-8")).hexdigest()
|
return hashlib.sha1(raw.encode("utf-8")).hexdigest()
|
||||||
@@ -160,10 +179,18 @@ def build_trade_alert_for_city(
|
|||||||
force_refresh: bool = False,
|
force_refresh: bool = False,
|
||||||
target_date: Optional[str] = None,
|
target_date: Optional[str] = None,
|
||||||
) -> Dict[str, Any]:
|
) -> 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
|
from src.analysis.market_alert_engine import build_trading_alerts
|
||||||
|
|
||||||
city_weather = _analyze(city, force_refresh=force_refresh)
|
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")
|
resolved_target_date = target_date or city_weather.get("local_date")
|
||||||
if resolved_target_date:
|
if resolved_target_date:
|
||||||
datetime.strptime(resolved_target_date, "%Y-%m-%d")
|
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_sig_ts = int((state.get("by_signature") or {}).get(signature) or 0)
|
||||||
last_city_active = bool(last_city.get("active"))
|
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
|
return False
|
||||||
|
|
||||||
if last_city_ts and now_ts - last_city_ts < cooldown_sec:
|
if last_city_ts and now_ts - last_city_ts < cooldown_sec:
|
||||||
|
|||||||
+7
-3
@@ -681,11 +681,15 @@ def _build_city_detail_payload(
|
|||||||
) -> Dict[str, Any]:
|
) -> Dict[str, Any]:
|
||||||
distribution = data.get("probabilities", {}).get("distribution", []) or []
|
distribution = data.get("probabilities", {}).get("distribution", []) or []
|
||||||
primary_bucket = distribution[0] if distribution else None
|
primary_bucket = distribution[0] if distribution 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 = (
|
model_probability = (
|
||||||
(primary_bucket.get("probability") / 100.0)
|
raw_probability / 100.0 if raw_probability > 1.0 else raw_probability
|
||||||
if isinstance(primary_bucket, dict) and primary_bucket.get("probability") is not None
|
|
||||||
else None
|
|
||||||
)
|
)
|
||||||
|
except Exception:
|
||||||
|
model_probability = None
|
||||||
fallback_sparkline = [
|
fallback_sparkline = [
|
||||||
p.get("probability", 0)
|
p.get("probability", 0)
|
||||||
for p in distribution[:8]
|
for p in distribution[:8]
|
||||||
|
|||||||
Reference in New Issue
Block a user