# Time-series data

> The table shape forecasts expect, how columns are found, and what the client fixes before sending.

Every forecast starts from a table of the past: **one row per time**, holding the value you want to forecast.

## One series

This is Melbourne's daily minimum temperature, the public dataset most examples on these pages use:

| Date | Temp |
|---|---|
| 1981-01-01 | 20.7 |
| 1981-01-02 | 17.9 |
| 1981-01-03 | 18.8 |
| ... | ... |
| 1990-12-31 | 13.0 |

- `Date` is the **time** column: when each value was measured. The times are regular (one per day here; hourly, weekly or
  monthly work the same way). A missing day is fine.
- `Temp` is the **target**: the quantity the forecast continues.

```python
fc = yh.forecast(temps, h=28, time_col="Date", target_col="Temp")  # the next 28 days
```

## Many series

To forecast several series in one call (every country, store, meter or product), stack them in one table and add an **id**
column saying which series each row belongs to. This is yearly population for India and the United States:

```python
import pandas as pd
from yhatlabs import Client

pop = pd.read_csv("https://raw.githubusercontent.com/datasets/population/main/data/population.csv")
pop = pop[pop["Country Code"].isin(["IND", "USA"])][["Country Code", "Year", "Value"]]  # two series, one long table
print(pop.groupby("Country Code").tail(2).to_string(index=False))

yh = Client()
fc = yh.forecast(pop, h=3, id_col="Country Code", time_col="Year", target_col="Value", freq="YS")
print((fc.df.set_index(["Country Code", "Year"]) / 1e6).round(1))  # millions
```

Output:

```
Country Code  Year      Value
     IND  2024 1450935791
     IND  2025 1463865525
     USA  2024  340003797
     USA  2025  341784857
                  q10  median     q90
Country Code Year                        
IND          2026  1475.9  1476.6  1477.2
         2027  1487.7  1489.1  1490.4
         2028  1499.2  1501.4  1503.4
USA          2026   342.4   343.7   344.8
         2027   343.6   345.7   347.4
         2028   345.2   347.9   350.1
```

- `Country Code` is the **id**, `Year` the time and `Value` the target. One row per series and time is called the **long
  format**.
- Each series is forecast on its own, from its own last time; series may start and end at different times.
- Quota counts series, not rows: this call uses 2.

## Columns that help the forecast

Any other column you name is a **covariate**: something that moves the target, such as the temperature for electricity load
or a promotion for sales. A covariate whose future you know (a calendar, a planned price) goes in `known=` with its future
values; one known only up to now (yesterday's load) goes in `past=`. See
[Covariates](https://yhatlabs.com/models/docs/time-series/covariates).

## Column names

The column roles are found by name, so with standard names you pass nothing:

| Role | Found automatically | Otherwise |
|---|---|---|
| time | `ds`, `timestamp`, `time`, `date`, `datetime` | `time_col=` |
| target | `y`, `target`, `value`, or the only numeric column | `target_col=` |
| id | `unique_id`, `id`, `item_id`, `series_id` | `id_col=`; without one, the table is a single series, labelled `series_0` |

Other columns are ignored, with a warning, unless you name them as covariates. A pandas Series with a date index, a polars
DataFrame, or plain arrays with `freq=` work too. Integer time columns (1, 2, 3, ...) are read as steps; pass `freq=` to say
what one step is, as `freq="YS"` above says the years are yearly.

## What the client fixes before sending

- Parses the timestamps and sorts the rows.
- Infers each series' frequency (hourly, daily, monthly, ...). A mix of frequencies is an error: forecast them separately, or
  pass `freq=`.
- Adds missing timestamps as empty rows, so each series is on a regular grid. Missing values are sent as gaps; the model
  handles them.
- Keeps the most recent 32,768 points of a very long series.
- Splits large inputs into several requests and sends them in parallel.

It warns whenever it changes something. Two rows with the same id and timestamp are an error: aggregate them first.

## What is refused, and what is read differently

Some inputs cannot be forecast as they are, and a few are easy to misread. The client stops before sending, with a message
that says what to change:

```python
import numpy as np
import pandas as pd
from yhatlabs import Client, DataError

yh = Client()

# 50 readings at random times over seven months: no regular grid to forecast on
rng = np.random.default_rng(0)
when = pd.Timestamp("2026-01-01") + pd.to_timedelta(np.sort(rng.choice(5000, 50, replace=False)), unit="h")
try:
yh.forecast(pd.DataFrame({"ds": when, "y": rng.normal(size=50)}), h=3)
except DataError as e:
print("irregular:", str(e)[:150], "...")

# integer time steps: kept as steps; freq= says what one step is
steps = pd.DataFrame({"step": range(100, 160), "y": np.sin(np.arange(60) / 4)})
print(yh.forecast(steps, h=3, time_col="step", freq="h").df[["step", "median"]].round(2).to_string(index=False))

# a 2-D array: one series per row
print(yh.forecast(np.arange(40.0).reshape(2, 20), h=2, freq="D").df[["unique_id", "ds", "median"]].round(1).to_string(index=False))
```

Output:

```
irregular: Series 'series_0' has 50 rows, but on a regular grid at frequency '13h' 320 of 370 timestamps would be missing. The timestamps look irregular: pass fr ...
 step  median
  160    0.65
  161    0.44
  162    0.20
unique_id  ds  median
 series_0  20    20.0
 series_0  21    21.0
 series_1  20    40.0
 series_1  21    41.0
```

| Input | What happens |
|---|---|
| timestamps so irregular that more than half the regular grid would be empty | refused: pass `freq=` for the spacing you want, or resample first |
| rows without a series id | refused, naming the rows |
| more targets or covariates than the API takes (256 of each) | refused before sending |
| an empty table | refused |
| integers in the time column (`1, 2, 3` or years) | read as steps; the forecast continues them, and `freq=` says what one step is |
| a 2-D array or a list of lists | one series per row (`series_0`, `series_1`, ...) |
| infinite values | sent as missing, with a warning |

## Check the data first

This checks the Melbourne temperatures locally, without a key, before anything is sent:

```python
import pandas as pd
import yhatlabs

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")

report = yhatlabs.check(temps, h=28, time_col="Date", target="Temp")
print(report)
print(report.issues[["severity", "code", "detail"]].to_string(index=False))
```

Output:

```
DataCheck(timeseries: 1 series, 1 note)
severity               code                                 detail
note missing_timestamps 2 missing timestamps (0% of the grid).
```

```bash
curl -sO https://raw.githubusercontent.com/jbrownlee/Datasets/master/daily-min-temperatures.csv
yhatlabs check daily-min-temperatures.csv --h 28 --time-col Date --target Temp
```

Output:

```
DataCheck(timeseries: 1 series, 1 note)
severity               code    where                                 detail                                                                         suggestion
note missing_timestamps series_0 2 missing timestamps (0% of the grid). They are sent as gaps; yh.fill_gaps() fills them from the history before each gap.
```

The one finding is a note: two dates are missing from the ten years (the last day of two leap years). They are sent as
gaps, so nothing needs fixing. See [Data checks](https://yhatlabs.com/models/docs/tools/data-checks) for everything `check` looks for.
