Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,18 @@ compiled C engine.

## Unreleased

**`-O g`: the origin of the forecast report, as in the C (atsw-gui #231).**
The ladder forecast with fixed parameters from every origin
(`Ladder.recursive`), but the report always left from the end of the
estimation sample. `-O g` puts its origin at observation `g` of the first
series and `-O -1` at the current end of the data; `Ladder.forecast(L,
origin=...)` is the same in Python. The parameters and σ² stay the
estimation's. `-estwin N -O -1` is the tracking mode: new observations, the
same parameters, the forecast from the last datum. Without `-O` nothing
changes. On a VAR(1) of the three price indices the port writes the C's
`.forecast` number for number, from the last datum and from an inner origin
(`tests/test_origin.py`).

**`-deseason` is the C's again (BUG-0003).** The port had moved to Box-Cox →
d=1 → deseasonalization in 0.2.0; the C of record now does the same
(atsw-gui `engines/drvarma` BUG-0010). On the seven full-sample `-deseason`
Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ and a pure-Python vs hybrid vs C performance study.
```sh
drvarma ES.pre FR.pre DE.pre 0 0 -diagcov -forecast 24 -estwin 216 -o diag # the univariates
drvarma ES.pre FR.pre DE.pre 1 0 -forecast 24 -estwin 216 -o var1 # + cross dynamics
drvarma ES.pre FR.pre DE.pre 1 0 -forecast 24 -estwin 216 -O -1 -o seg # tracking: same parameters, origin at the last datum
drvarma -split IPC3.inp -mean -ar 1 -dir specs/ # the old multivariate .inp -> fue .inp
```

Expand Down
65 changes: 58 additions & 7 deletions src/drvarma/ladder.py
Original file line number Diff line number Diff line change
Expand Up @@ -2157,9 +2157,44 @@ def _inv(s, z):
from fue.forecast import _inv_boxcox
return _inv_boxcox(float(z), s.model.boxlam, s.model.refactor)

def forecast(self, L):
"""L-step forecasts from the current end of every series, with the
fitted parameters held fixed. Returns one dict per series."""
def origin_shift(self, origin):
"""How many periods before the end of the data the origin ``origin``
is: an observation of the FIRST series, or -1 for the end of the data.
The C's checks and messages (``-O g``)."""
full = self.series[0].nobs_full
if origin == -1:
return 0
if not isinstance(origin, (int, np.integer)) or origin < 1:
raise LadderError("-O needs an observation number, or -1 for the end "
"of the data")
if origin > full:
raise LadderError(f"-O {origin} is beyond the {full} observations of "
f"{self.series[0].name}")
for s in self.series:
if s.nobs_full - (full - origin) < 2:
raise LadderError(f"-O {origin} leaves {s.name} without data")
return full - int(origin)

def forecast(self, L, origin=None):
"""L-step forecasts with the fitted parameters held fixed. Returns one
dict per series.

``origin`` is the ORIGIN OF THE REPORT, independent of the estimation
window, as in the C (``-O g``) and in drtran: observation ``origin`` of
the first series, or -1 for the current end of the data. The
parameters and sigma2 stay the estimation's; the residuals come from
the data cut at the origin. With ``estwin`` and ``origin=-1`` it is
the tracking mode: new observations, the same parameters, the forecast
from the last datum. ``None``: the end of the estimation sample.
"""
if origin is not None:
k = self.origin_shift(origin)
k_est = self.series[0].nobs_full - self.series[0].nobs
self.set_origin(k)
try:
return self.forecast(L)
finally:
self.set_origin(k_est)
from .forecast import forecast_w, lead_sd as _lead_sd, series_psi
from .irf import psi_weights
if self.result is None:
Expand Down Expand Up @@ -2190,7 +2225,7 @@ def lead_sd(l, d):
lvl = np.array([self._inv(s, ystar[n + l - 1]) for l in range(1, L + 1)])
lo = np.array([self._inv(s, ystar[n + l - 1] - 1.96 * sd[l - 1]) for l in range(1, L + 1)])
hi = np.array([self._inv(s, ystar[n + l - 1] + 1.96 * sd[l - 1]) for l in range(1, L + 1)])
out.append({"series": s.name, "origin": s.date_of(n),
out.append({"series": s.name, "origin": s.date_of(n), "nobs": n,
"dates": [s.date_of(n + l) for l in range(1, L + 1)],
"level": lvl, "low95": lo, "high95": hi, "sd": sd,
"sd_period": np.array([lead_sd(l, 1) for l in range(1, L + 1)]),
Expand Down Expand Up @@ -2496,7 +2531,9 @@ def _forecast_lines(forecasts, L):
# BUG-0025, as the C (escalera.c, its BUG-0005): a percentage only
# with logs; otherwise the change of the transformed series.
sc = (100.0 if abs(s.model.boxlam) < 1e-8 else 1.0) / s.model.refactor
n = s.nobs
# the history the forecast used: with an origin other than the
# estimation end (-O) it is not the series' current length
n = fc.get("nobs", s.nobs)
ys = fc["ystar"]
out += [f"Series {fc['series']} (from {p}/{y}):",
f" date {'Level':>10} {'Low95':>10} {'High95':>10} {'mon%':>8} {'std':>7}"
Expand Down Expand Up @@ -2535,7 +2572,7 @@ def write_recursive(L, rows, H, path):

def main(argv):
"""drvarma F1 F2 [...] p q [-diagcov] [-redet] [-fixarma] [-m M] [-o NAME]
[-forecast H [-estwin N]]"""
[-forecast H [-estwin N] [-O g]]"""
import argparse
import os
ap = argparse.ArgumentParser(prog="drvarma", description=
Expand All @@ -2551,6 +2588,12 @@ def main(argv):
ap.add_argument("-o", default=None, dest="name")
ap.add_argument("-forecast", type=int, default=None)
ap.add_argument("-estwin", type=int, default=None)
ap.add_argument("-O", type=int, default=None, dest="origin",
help="the ORIGIN of the forecast report: observation g of the "
"first series, or -1 for the current end of the data. "
"Independent of -estwin: the parameters and sigma2 stay "
"the estimation's (-estwin N -O -1: tracking). Default: "
"the estimation end")
ap.add_argument("-lik", choices=("elf", "shea", "both"), default="elf",
help="exact likelihood: elf (AS 311, default), shea (AS 242), "
"or both (elf checked against Shea at every point)")
Expand All @@ -2566,20 +2609,28 @@ def main(argv):
files, p, q = a.items[:-2], int(a.items[-2]), int(a.items[-1])
if a.estwin and not a.forecast:
raise SystemExit("ERROR: -estwin needs a horizon: give -forecast H")
if a.origin is not None and (a.origin == 0 or a.origin < -1):
raise SystemExit("ERROR: -O needs an observation number, or -1 for the end "
"of the data")
if a.origin is not None and not a.forecast:
raise SystemExit("ERROR: -O needs a horizon: give -forecast H")
name = a.name or "_".join(os.path.splitext(os.path.basename(f))[0] for f in files)
try:
L = Ladder(files, p, q, diagcov=a.diagcov, redet=a.redet, det=a.det,
detbase=a.detbase, fixarma=a.fixarma, route=a.route,
method=a.method, estwin=a.estwin, hessian=a.hessian,
lik=a.lik, links=a.links)
if a.origin is not None:
L.origin_shift(a.origin) # refused before estimating, as the C
L.forecast_origin = a.origin
L.fit()
except GateError as e:
print(f"ERROR: {e}"); return 5
except LadderError as e:
print(f"ERROR: {e}"); return 4 if "same date" in str(e) or "per-year" in str(e) else 2
fc = rec = None
if a.forecast:
fc = L.forecast(a.forecast)
fc = L.forecast(a.forecast, origin=a.origin)
write_forecast(L, fc, name + ".forecast")
if a.estwin:
rec = L.recursive(a.forecast)
Expand Down
12 changes: 12 additions & 0 deletions tests/data/ladder/origin/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
# The C's forecast report from an origin other than the estimation end (`-O g`)

Written by the C of record (atsw-gui `engines/drvarma`, main e964abd, where
`-O` came in with #231):

```
drvarma IPC_ES_ext.pre IPC_FR_ext.pre IPC_DE_ext.pre 1 0 -forecast 6 -estwin 216 -O -1 -o X
drvarma IPC_ES_ext.pre IPC_FR_ext.pre IPC_DE_ext.pre 1 0 -forecast 6 -estwin 216 -O 240 -o X
```

`tests/test_origin.py` asks the port for the same two and compares every
number of `X.forecast`.
31 changes: 31 additions & 0 deletions tests/data/ladder/origin/var1_estwin216_O-1.forecast
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
Forecasts from the ladder VARMA (cross orders p=1 q=0)
horizon=6, freq=12; each series with its own .pre transformation
Level/Low95/High95 in original units. mon%/ann% = period/annual variation and std (100*delta/refactor; % for lambda=0).

Series 1 (IPC_ES):
date Level Low95 High95 mon% std ann% std
12/2023 112.4205 111.8751 112.9686 -0.2210 0.2481 2.6537 0.2481
1/2024 111.1386 110.2024 112.0828 -1.1468 0.2715 0.5698 0.4316
2/2024 111.2198 109.9542 112.4999 0.0730 0.2747 -0.4002 0.5839
3/2024 111.8910 110.3362 113.4676 0.6016 0.2752 0.2324 0.7139
4/2024 113.1371 111.3202 114.9837 1.1076 0.2753 1.6530 0.8260
5/2024 113.4795 111.4393 115.5571 0.3022 0.2753 2.1055 0.9256

Series 2 (IPC_FR):
date Level Low95 High95 mon% std ann% std
12/2023 118.1496 117.7377 118.5628 -0.0173 0.1781 3.4350 0.1781
1/2024 117.9021 117.2563 118.5516 -0.2096 0.1870 2.8407 0.2803
2/2024 118.5244 117.6757 119.3793 0.5264 0.1884 2.3427 0.3667
3/2024 119.3342 118.3074 120.3698 0.6809 0.1886 2.1550 0.4409
4/2024 119.7238 118.5434 120.9160 0.3260 0.1886 1.8749 0.5055
5/2024 119.8761 118.5600 121.2068 0.1271 0.1886 2.0531 0.5632

Series 3 (IPC_DE):
date Level Low95 High95 mon% std ann% std
12/2023 117.5524 117.0204 118.0868 0.2149 0.2314 3.7728 0.2314
1/2024 117.4610 116.7025 118.2244 -0.0778 0.2333 2.7280 0.3305
2/2024 118.2059 117.2382 119.1815 0.6321 0.2345 2.5758 0.4194
3/2024 118.8052 117.6869 119.9341 0.5058 0.2354 2.3033 0.4825
4/2024 119.0661 117.8123 120.3333 0.2194 0.2355 2.0930 0.5401
5/2024 119.1902 117.8180 120.5783 0.1041 0.2355 2.2829 0.5908

31 changes: 31 additions & 0 deletions tests/data/ladder/origin/var1_estwin216_O240.forecast
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
Forecasts from the ladder VARMA (cross orders p=1 q=0)
horizon=6, freq=12; each series with its own .pre transformation
Level/Low95/High95 in original units. mon%/ann% = period/annual variation and std (100*delta/refactor; % for lambda=0).

Series 1 (IPC_ES):
date Level Low95 High95 mon% std ann% std
1/2022 103.2346 102.7337 103.7378 -0.7051 0.2481 5.6300 0.2481
2/2022 103.4893 102.6175 104.3685 0.2465 0.2715 6.4675 0.4316
3/2022 104.1291 102.9442 105.3276 0.6163 0.2747 6.1184 0.5839
4/2022 105.2719 103.8091 106.7552 1.0915 0.2752 6.0366 0.7139
5/2022 105.5589 103.8636 107.2818 0.2723 0.2753 5.8388 0.8260
6/2022 105.7305 103.8296 107.6663 0.1625 0.2753 5.5264 0.9256

Series 2 (IPC_FR):
date Level Low95 High95 mon% std ann% std
1/2022 107.8520 107.4761 108.2292 0.0018 0.1781 2.5657 0.1781
2/2022 108.2083 107.6156 108.8044 0.3299 0.1870 2.8956 0.2803
3/2022 108.8955 108.1157 109.6809 0.6330 0.1884 2.9311 0.3667
4/2022 109.0928 108.1541 110.0396 0.1810 0.1886 3.0081 0.4409
5/2022 109.3398 108.2617 110.4286 0.2262 0.1886 2.9136 0.5055
6/2022 109.4476 108.2460 110.6625 0.0986 0.1886 2.8804 0.5632

Series 3 (IPC_DE):
date Level Low95 High95 mon% std ann% std
1/2022 104.7394 104.2653 105.2155 0.0376 0.2314 3.6354 0.2314
2/2022 105.3012 104.6212 105.9855 0.5349 0.2333 3.5781 0.3305
3/2022 105.7278 104.8623 106.6004 0.4043 0.2345 3.4915 0.4194
4/2022 105.9007 104.9039 106.9070 0.1634 0.2354 3.3615 0.4825
5/2022 106.0722 104.9552 107.2010 0.1618 0.2355 3.3282 0.5401
6/2022 106.2848 105.0611 107.5226 0.2002 0.2355 3.2364 0.5908

87 changes: 87 additions & 0 deletions tests/test_origin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
"""-O g: the origin of the forecast report, independent of the estimation
window, as in the C (atsw-gui #231) and in drtran. The parameters and sigma2
stay the estimation's."""
import os
import re

import pytest

from drvarma.ladder import Ladder, LadderError, main

D = os.path.join(os.path.dirname(__file__), "data", "ladder")
EXT = [os.path.join(D, f"IPC_{c}_ext.pre") for c in ("ES", "FR", "DE")]
REF = os.path.join(D, "origin")


def _table(path):
out, cur = {}, None
for line in open(path):
m = re.match(r"\s*Series (?:\d+ \()?(\w+)", line)
if m:
cur = m.group(1)
continue
t = line.split()
if cur and len(t) >= 8 and re.match(r"\d+/\d{4}$", t[0]):
out[(cur, t[0])] = [float(x) for x in t[1:8]]
return out


@pytest.fixture(scope="module")
def var1():
L = Ladder(EXT, 1, 0, estwin=216)
L.fit()
return L


@pytest.mark.parametrize("flag, ref", [("-1", "var1_estwin216_O-1.forecast"),
("240", "var1_estwin216_O240.forecast")])
def test_the_report_from_another_origin_is_the_cs(tmp_path, flag, ref):
"""Level, band, period and annual variation with their s.d.: the C's file."""
name = str(tmp_path / "X")
assert main(EXT + ["1", "0", "-forecast", "6", "-estwin", "216", "-O", flag,
"-o", name]) == 0
ours, c = _table(name + ".forecast"), _table(os.path.join(REF, ref))
assert len(c) == 18 and set(ours) == set(c)
assert max(abs(a - b) for k in c for a, b in zip(ours[k], c[k])) < 1.5e-4


def test_the_origin_is_the_last_row_of_the_recursive_evaluation(var1):
"""The fixed-parameter forecast from the last datum was already there, in
recursive(): the report now leaves from it."""
rows, _ = var1.recursive(6)
last = max(o for o, *_ in rows)
ref = {(s, h): v for o, s, h, v, _a in rows if o == last}
fc = var1.forecast(6, origin=-1)
assert fc[0]["origin"] == last == (2023, 11)
for f in fc:
for h in range(1, 7):
assert f["level"][h - 1] == pytest.approx(ref[(f["series"], h)], rel=1e-12)


def test_the_origin_does_not_move_the_estimation_sample(var1):
before = [s.nobs for s in var1.series]
a = var1.forecast(3)
var1.forecast(3, origin=-1)
var1.forecast(3, origin=240)
assert [s.nobs for s in var1.series] == before
assert var1.forecast(3)[0]["level"][0] == a[0]["level"][0]
# the window end named as an origin is the default
assert var1.forecast(3, origin=216)[0]["level"][0] == a[0]["level"][0]


def test_the_scale_is_the_estimations(var1):
"""One-step s.d.: the same from the window end and from the last datum."""
a, b = var1.forecast(1), var1.forecast(1, origin=-1)
assert a[0]["sd"][0] == pytest.approx(b[0]["sd"][0], rel=1e-12)
assert a[0]["level"][0] != b[0]["level"][0]


def test_refusals_are_the_cs(var1, capsys):
with pytest.raises(LadderError, match="beyond the 263 observations of IPC_ES"):
var1.forecast(3, origin=100000)
with pytest.raises(LadderError, match="needs an observation number"):
var1.forecast(3, origin=0)
with pytest.raises(SystemExit, match="-O needs a horizon"):
main(EXT[:2] + ["0", "0", "-O", "-1"])
with pytest.raises(SystemExit, match="needs an observation number"):
main(EXT[:2] + ["0", "0", "-forecast", "3", "-O", "0"])
Loading