# Anomalies and gaps

> Flag recent points the model did not expect, and fill missing values from each series' own history.

The model that forecasts can also tell you which recent points it did not expect, and what a missing value most likely was.
Both use only the data before the point in question.

## Find anomalies

This plants one faulty reading in the temperatures, 12°C too warm, then scores the last 56 days:

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

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")
temps.loc[temps.index[-10], "Temp"] += 12  # plant one faulty reading, 10 days before the end

yh = Client()
flags = yh.detect_anomalies(temps, h=28, windows=2, time_col="Date", target_col="Temp")
print(flags[flags["anomaly"]][["Date", "y", "median", "q10", "q90", "score"]].round(1).to_string(index=False))
```

Output:

```
  Date    y  median  q10  q90  score
1990-11-07 19.2    12.5  9.9 15.6    3.0
1990-12-22 25.2    14.3 11.5 18.0    4.3
```

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

Output:

```
unique_id,Date,y,median,q10,q90,score,anomaly
series_0,1990-11-07,19.2,12.501609400889498,9.87606544219341,15.571764253749585,3.014321242374082,True
```

Each recent point is compared with a forecast made from the data before it:

- `score` is how far the actual value is from the median, in units of that forecast's own spread. A point the model was unsure
  about needs a larger miss to count.
- A point is an anomaly when `|score|` is above `threshold` (default 3).
- Here the planted reading (22 December, score 4.3) is caught. One genuinely unusual warm night is flagged as well.

| Argument | Meaning |
|---|---|
| `h=28` | the length of each scored window; default one season of the series |
| `windows=2` | how many windows, ending at the last point: 2 x 28 = the last 56 days |
| `threshold` | the score above which a point is flagged; raise it for fewer alerts |

`yhatlabs.plots.anomalies(flags)` draws the series, its expected range and the flagged points:

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

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")
temps["Date"] = pd.to_datetime(temps["Date"])
temps.loc[temps.index[-10], "Temp"] += 12  # one faulty reading

yh = Client()
flags = yh.detect_anomalies(temps, h=28, windows=2, time_col="Date", target_col="Temp")
plots.anomalies(flags).savefig("anomalies.png", dpi=110)
print("saved anomalies.png; flagged:", int(flags["anomaly"].sum()))
```

Output:

```
saved anomalies.png; flagged: 2
```

![The last two months of temperatures, the q10 to q90 expected range, and two flagged readings](https://yhatlabs.com/models/docs/img/ts_plot_anomalies-anomalies.png)

## Score points as they arrive

For monitoring, `anomaly_stream` keeps the recent history of every series and scores only the points each update brings:

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

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")
temps.loc[temps.index[-3], "Temp"] += 12  # a faulty reading among the newest points

yh = Client()
stream = yh.anomaly_stream(window=512, time_col="Date", target_col="Temp")
stream.update(temps.iloc[:-7])  # the history so far: kept as context (the last 512 days)
new = stream.update(temps.iloc[-7:])  # a week arrives: only these 7 points are scored
print(new[["Date", "y", "median", "score", "anomaly"]].round(1).to_string(index=False))
```

Output:

```
  Date    y  median  score  anomaly
1990-12-25 12.9    12.3    0.3    False
1990-12-26 14.6    13.9    0.3    False
1990-12-27 14.0    14.3   -0.1    False
1990-12-28 13.6    14.5   -0.3    False
1990-12-29 25.5    14.6    4.1     True
1990-12-30 15.7    14.8    0.3    False
1990-12-31 13.0    14.8   -0.7    False
```

- `stream.update(new_points)` returns the scores (`score`, `anomaly`, ...) for the new points only, and keeps the last `window`
  points of every series (512 by default) for the next update.
- Each update is one `detect_anomalies` call, however many series it holds. A series is scored once it has enough history
  before the new points; until then its points are only kept, as with the first update here.
- `threshold=`, covariates and the column arguments work as for `detect_anomalies`.

## Fill gaps

This removes five days from the temperatures, then fills every gap from the history before it:

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

url = "https://raw.githubusercontent.com/jbrownlee/Datasets/master/"
temps = pd.read_csv(url + "daily-min-temperatures.csv")
truth = temps.iloc[3000:3005]["Temp"].tolist()
temps = temps.drop(index=range(3000, 3005))  # remove five days

yh = Client()
filled = yh.fill_gaps(temps, time_col="Date", target_col="Temp")
print(filled[filled["Temp_filled"]][["Date", "Temp"]].round(1).to_string(index=False))
print("actual:", truth)
```

Output:

```
  Date  Temp
1984-12-31  15.0
1988-12-31  14.2
1989-03-22  16.2
1989-03-23  15.6
1989-03-24  15.3
1989-03-25  15.0
1989-03-26  15.0
actual: [16.9, 16.5, 13.6, 13.2, 9.4]
```

- Every gap inside a series (missing values or missing timestamps) gets the median forecast from the data before it.
- `<target>_filled` marks what was filled; here, the five removed days and the two dates already missing from the data.
- The filled values follow the level of the series, not every swing: compare them with the actual values printed below them.
- A gap at the very start of a series, or longer than `max_gap`, stays empty. Known covariates passed as `known=` are used
  for the filled steps.
