SuperAPI AI Directory

analyze-gas-fertilizer-contract-shock

Data & analytics

View repository

Updated 10-15 21:41

About this skill

<essential_principles>

This skill focuses on "testing narratives with data":

  • Input: social/news claims that "a natural gas surge caused fertilizer supply/price anomalies"
  • Output: results of testing the causal hypothesis on time series

Do not make price forecasts; only answer: "Does this narrative have support in the data?"

For the narrative to hold, three conditions must be satisfied simultaneously:

Stage Condition Testing method
Stage A Natural gas enters a shock regime z-score or slope breaks through threshold
Stage B Fertilizer shows a spike after Stage A Tested the same way, and the starting point is later than natural gas
Stage C Lead-lag relationship supports causality Cross-correlation shows gas leads fert

If A→B→C holds, the narrative has quantitative support; otherwise, provide alternative explanations.

Use rolling z-score + slope dual confirmation:

# z-score 偵測
z_t = (r_t - rolling_mean(r, window)) / rolling_std(r, window)
shock = z_t >= threshold_z  # 預設 3.0

# 斜率偵測(補充)
slope_t = (price_t / price_{t-k} - 1) / k
shock |= slope_t >= threshold_slope  # 預設 1.5%/day

Consecutive shock days are merged into a regime, and the start/end/peak are output.

Interpretation of cross-correlation results:

lag value Meaning Degree of narrative support
lag > 0 Natural gas leads fertilizer High (consistent with expectations)
lag ≈ 0 Simultaneous movement Medium (common driver)
lag < 0 Fertilizer leads natural gas Low (narrative is weaker)

Reasonable lead time: 1-8 weeks (7-56 days)

Primary: TradingEconomics (scraped via fully automated Chrome CDP) Fallback: FRED Henry Hub + World Bank Pink Sheet

Fully automated Chrome CDP scraping: The script automatically performs the following steps, with no manual operation required:

  1. Automatically launch Chrome in debug mode
  2. Open the TradingEconomics page and wait for the chart to load
  3. Connect via WebSocket and execute JavaScript to extract Highcharts data
  4. Automatically navigate to multiple commodity pages (e.g., natural gas→fertilizer)
  5. Automatically close Chrome when done

Completely bypasses Cloudflare, with no manual verification required.

</essential_principles>

Output three layers of analysis:

  1. Shock Regimes: parabolic/blow-off ranges in natural gas and fertilizer
  2. Lead-Lag Test: lead-lag correlation analysis
  3. Narrative Assessment: judgment of narrative credibility

<quick_start>

Fully automated mode: complete data scraping, analysis, and visualization with one click

The script will automatically launch Chrome, scrape data, and close Chrome, with no manual operation required.

Step 1: Install dependencies

pip install requests websocket-client pandas numpy matplotlib scipy

Step 2: Fully automated data scraping(automatically launches/closes Chrome)

cd scripts
python fetch_te_data.py --symbol natural-gas --symbol urea

Step 3: Run causal hypothesis analysis

python gas_fertilizer_analyzer.py \
  --gas-file ../data/cache/natural-gas.csv \
  --fert-file ../data/cache/urea.csv \
  --output ../data/analysis_result.json

Step 4: Generate visualization charts(Bloomberg style)

python visualize_shock_regimes.py
# 自動輸出到: output/gas_fert_shock_YYYY-MM-DD.png

Output example:

{
  "signal": "narrative_supported",
  "confidence": "medium",
  "gas_shock_regimes": [
    {"start": "2026-01-20", "peak": "2026-01-22", "regime_return_pct": 29.1}
  ],
  "fert_spike_regimes": [
    {"start": "2025-10-27", "peak": "2025-10-27", "regime_return_pct": 0.0}
  ],
  "lead_lag_test": {
    "best_lag_days_gas_leads_fert": 21,
    "best_corr": 0.131
  },
  "interpretation": "天然氣領先化肥約 21 天,敘事有量化支撐"
}

Note: On first run, Chrome will launch automatically and scrape data in the background (about 60 seconds), then close automatically when done.

</quick_start>

  1. Quick check - See whether there has recently been a natural gas shock and whether fertilizer followed
  2. Full analysis - Execute three-stage causal testing and generate a report
  3. Contract Hedging Hypothesis - Input contract prices and calculate the spread pressure indicator
  4. Methodology Learning - Understand the principles of shock detection and lead-lag analysis

Please select or directly provide analysis parameters.

After routing, read the corresponding document and execute.

<directory_structure>

analyze-gas-fertilizer-contract-shock/
├── SKILL.md                           # 本文件(路由器)
├── skill.yaml                         # 前端展示元數據
├── manifest.json                      # 技能元資料
├── workflows/
│   ├── analyze.md                     # 完整三段式分析工作流
│   ├── quick-check.md                 # 快速檢查工作流
│   └── hedge-hypothesis.md            # 合約對沖假說分析
├── references/
│   ├── data-sources.md                # Chrome CDP 爬蟲說明
│   ├── methodology.md                 # Shock 偵測與領先落後方法論
│   ├── input-schema.md                # 輸入參數定義
│   └── historical-episodes.md         # 歷史案例對照
├── templates/
│   ├── output-json.md                 # JSON 輸出模板
│   └── output-markdown.md             # Markdown 報告模板
├── scripts/
│   ├── fetch_te_data.py               # TradingEconomics CDP 爬蟲
│   ├── gas_fertilizer_analyzer.py     # 主分析腳本
│   └── visualize_shock_regimes.py     # Shock regime 視覺化
├── data/                              # 數據快取目錄
│   └── cache/                         # 快取檔案
└── examples/
    └── sample_output.json             # 範例輸出

</directory_structure>

<reference_index>

Methodology: references/methodology.md

  • Shock/Spike detection logic (z-score + slope)
  • Lead-lag correlation analysis
  • Regime merging algorithm

Data Sources: references/data-sources.md

  • TradingEconomics Chrome CDP scraper instructions
  • Natural gas and fertilizer commodity codes
  • Fallback data sources (FRED/World Bank)

Input Parameters: references/input-schema.md

  • Complete parameter definitions and default values
  • te_symbols, spike_detection, lead_lag, etc.

Historical Cases: references/historical-episodes.md

  • 2021-2022 European natural gas crisis
  • During the 2022 Russia-Ukraine conflict
  • Seasonal fluctuation cases

</reference_index>

<workflows_index>

Workflow Purpose When to Use
analyze.md Complete three-stage causal analysis When the narrative needs verification
quick-check.md Quickly check recent shocks Daily monitoring or quick answers
hedge-hypothesis.md Contract hedging hypothesis analysis Calculate spread pressure given contract prices
</workflows_index>

<templates_index>

Template Purpose
output-json.md JSON output structure definition
output-markdown.md Markdown report template
</templates_index>

<scripts_index>

Script Command Purpose
fetch_te_data.py --symbol natural-gas --symbol urea Fully automated CDP scraping (automatically launches/closes Chrome)
gas_fertilizer_analyzer.py --gas-file X.csv --fert-file Y.csv Complete three-stage causal analysis
visualize_shock_regimes.py (no parameters, automatically reads cache) Bloomberg-style visualization charts
</scripts_index>

<input_schema>

</input_schema>

<output_schema> See templates/output-json.md for the complete structure definition.

Summary:

{
  "signal": "narrative_supported | narrative_weak | inconclusive",
  "confidence": "high | medium | low",
  "gas_shock_regimes": [...],
  "fert_spike_regimes": [...],
  "lead_lag_test": {
    "best_lag_days": 12,
    "best_corr": 0.41,
    "interpretation": "gas 領先 fert"
  },
  "narrative_assessment": "三段式檢驗結果摘要",
  "artifacts": {
    "charts": ["output/gas_fert_shock.png"]
  }
}

</output_schema>

<success_criteria> A successful analysis should produce:

  • Shock/spike regime list for natural gas and fertilizers
  • Lead-lag correlation analysis results
  • Three-stage causal testing judgment
  • Narrative credibility and alternative explanations
  • Shock Regime comparison chart(output/gas_fert_shock_YYYY-MM-DD.png)
  • Actionable macro interpretation
  • Clearly annotate data limitations and assumptions </success_criteria>