# Writing a model

> Practical advice for forecasting DegenHive rounds, from the target format and horizons to originality, overfitting and data, with a Python skeleton.

Source: https://docs.degenhive.ai/forecasters/writing-a-model

A model turns data into one forecast per market for each round of a job. What a vault finally trades is a sparse vector of signed target weights, so this page has you produce exactly that: a map from HyperCore asset id to an int16 weight in basis points.

> [!NOTE]
> The forecast intake service opens with Season 0, and its submission format publishes then. A job's `specUri` says what it asks for; some jobs may ask for returns, volatility or crash risk rather than weights. Build the model and the backtest first, and wire the submit step when the intake opens.

## What a round asks for

| Property | What it means for your model |
|---|---|
| Markets | Only markets listed and unpaused in `HyperSignalBook` count. Read `marketCount()`, `marketIds(i)` and `markets(assetId)` |
| Asset ids | Core perps use their index in the HyperCore perp universe; HIP-3 perps use `100000 + dex × 10000 + index` |
| Weights | Signed bps of the vault: `+500` is 5% long, `-300` is 3% short. Leave a market out for 0 |
| Caps | Engines clamp each weight to the vault tier's cap; Flagship vaults also apply `maxWeightBps`. Weights past the cap buy nothing |
| Horizon | 1 hour to 7 days per job. The Flagship job predicts 24 hours ahead every 4 hours |
| Freshness | A round's targets expire after its TTL; an expired round steps the vault to flat |

Sparse is the norm. A good round names the few markets where you have a view and leaves the rest at 0.

## Be different, and right

Scoring pays accuracy against the market's baseline, plus four times your contribution beyond the weighted median of all forecasts. Copying the consensus scores zero contribution even when the consensus is right. See [Scoring](https://docs.degenhive.ai/forecasters/scoring.md).

- **Measure your overlap.** Every posted round's combined weights are public: `GET /v1/forecasting/jobs/{job_id}/rounds` returns `asset_ids` and `target_weights_bps`. Correlate your history against them. A model that tracks the consensus closely has little to add.
- **Use data other forecasters underuse.** Price momentum on BTC and ETH is a crowded signal. Funding, open interest, basis between HIP-3 stocks and their reference markets, and order-book imbalance are less so.
- **Keep it to yourself until the round starts.** A forecast posted publicly before its round opens can be copied, and the copies erase your contribution.

## Do not overfit

A day has only a handful of rounds, and a model carries weight only after at least 20 scored rounds with a t-statistic of at least 2. Noise looks like skill for a long time at this sample size.

- Validate walk-forward, never on shuffled data. Leave a gap of at least one horizon between training and test windows, so overlapping returns do not leak.
- Prefer few parameters and signals with a reason to exist. Count every variant you tried; the best of fifty backtests is mostly luck.
- Score your backtest the way the protocol does: `clip(A) + 4 × clip(C)` against a baseline and a consensus proxy, not raw PnL.
- Watch turnover. Weights that flip every round are expensive for the vault to trade, even when they score.

## Data

- **Public HyperCore data.** The Hyperliquid info API (`https://api.hyperliquid.xyz/info`) serves the perp universe, candles, funding, open interest and order books with no key. The skeleton below uses it.
- **The data marketplace.** Providers list feeds in `DataProviderRegistry`; browse them with `GET /v1/data/providers`. Feeds are sold to vaults on-chain; ask a provider about access for your own research. See [Data](https://docs.degenhive.ai/data.md).
- **Your own record.** `GET /v1/forecasting/forecasters/{account}` and `GET /v1/forecasting/payouts` show how your past rounds paid.

## A Python skeleton

The script reads public HyperCore data, builds a simple risk-scaled momentum and funding signal, and prints one round's sparse weight vector. Replace the signal with your model.

`forecast.py`

```python
"""One round's sparse weight vector for a DegenHive job. Standard library only."""
import json
import math
import statistics
import time
import urllib.request

INFO = "https://api.hyperliquid.xyz/info"
JOB_ID = 1
HORIZON_H = 24        # job(JOB_ID).horizonSecs / 3600
CAP_BPS = 2_500       # per market: min(vault tier cap, markets(assetId).maxWeightBps)
MIN_ABS_BPS = 50      # smaller views are left out: the vector stays sparse
COINS = ["BTC", "ETH", "HYPE"]  # keep to markets listed in HyperSignalBook

def info(body: dict):
    req = urllib.request.Request(
        INFO, data=json.dumps(body).encode(), headers={"Content-Type": "application/json"}
    )
    with urllib.request.urlopen(req, timeout=10) as r:
        return json.load(r)

def universe() -> dict:
    """Coin -> (asset id, hourly funding). A core perp's asset id is its index."""
    meta, ctxs = info({"type": "metaAndAssetCtxs"})
    return {
        a["name"]: (i, float(c["funding"]))
        for i, (a, c) in enumerate(zip(meta["universe"], ctxs))
    }

def hourly_closes(coin: str, hours: int) -> list[float]:
    end = int(time.time() * 1000)
    start = end - hours * 3_600_000
    rows = info({"type": "candleSnapshot",
                 "req": {"coin": coin, "interval": "1h", "startTime": start, "endTime": end}})
    return [float(r["c"]) for r in rows]

def score(coin: str, funding: float) -> float:
    """Your model goes here. Returns a signed view in units of horizon volatility."""
    px = hourly_closes(coin, 24 * 30)
    rets = [math.log(b / a) for a, b in zip(px, px[1:])]
    vol_h = statistics.pstdev(rets) * math.sqrt(HORIZON_H) or 1e-9
    lookback = 7 * HORIZON_H
    momentum = math.log(px[-1] / px[-1 - lookback]) / (vol_h * math.sqrt(7))
    carry = -funding * HORIZON_H / vol_h   # crowded longs pay funding: lean against them
    return 0.5 * momentum + 0.5 * carry

def to_bps(view: float) -> int:
    bps = int(round(max(-1.0, min(1.0, view / 2)) * CAP_BPS))
    return bps if abs(bps) >= MIN_ABS_BPS else 0

def main() -> None:
    uni = universe()
    weights = {}
    for coin in COINS:
        asset_id, funding = uni[coin]
        bps = to_bps(score(coin, funding))
        if bps != 0:
            weights[asset_id] = bps   # int16 range; engines clamp to the cap anyway

    round_forecast = {"jobId": JOB_ID, "horizonSecs": HORIZON_H * 3600, "weightsBps": weights}
    print(json.dumps(round_forecast, indent=2))

    # TODO: submit round_forecast, signed with your hot key.
    # The intake opens with Season 0; its endpoint and format publish then.

if __name__ == "__main__":
    main()
```

Run it with `python3 forecast.py`. Before you rely on it, check that each coin is listed for your job, and backtest the same function over past rounds with the walk-forward rules above.

## Related

- [Jobs & rounds](https://docs.degenhive.ai/forecasters/jobs-and-rounds.md) Markets, horizons and how engines read a round.
- [Scoring](https://docs.degenhive.ai/forecasters/scoring.md) The exact formula your backtest should use.
- [Forecaster quickstart](https://docs.degenhive.ai/forecasters.md) Bond, bind a hot key and check eligibility.
- [Data](https://docs.degenhive.ai/data.md) The feeds vaults buy, and how providers list them.
