pymetrix-eviews 0.1.0a1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1133 @@
1
+ """Phase 2: estimation and tests. Equations (``ls``, ``tsls``, ``gmm``, ``liml``, ``arch``, ``binary``, ``ordered``,
2
+ ``censored``, ``count``, ``qreg``, ``heckit``, ``ardl``), VARs and VECs, systems, the tests on an equation, unit-root
3
+ and cointegration tests, forecasts and residuals added to a page, and the values a program reads from a result
4
+ (``eq.@coefs(2)``, ``@r2``, ``c(2)`` after an estimation).
5
+
6
+ A list specification ``y c x y(-1)`` becomes ``y ~ x + y[-1]`` (``- 1`` without ``c``); an expression specification
7
+ ``y = c(1) + c(2)*x`` an explicit-form equation with parameters ``c_1``, ``c_2``. Each estimation keeps its
8
+ coefficient map: EViews's ``c(i)`` against pymetrix's term (``const``, ``x``, ``y[-1]``) or parameter (``c_2``), which
9
+ later lines use (``eq.@coefs(2)``, ``eq.wald c(2)=0``).
10
+
11
+ Every option is either mapped or the line is left out naming it: an estimator that runs with an option dropped would
12
+ give other numbers without saying so. Where EViews's defaults differ from pymetrix's (HAC bandwidths, the ARMA and
13
+ GARCH estimators, information criteria per observation), the line is translated with a note saying what to check.
14
+ """
15
+
16
+ from __future__ import annotations
17
+
18
+ import re
19
+ from dataclasses import dataclass, field
20
+ from typing import Any
21
+
22
+ from .ir import Arg, Cmd, Code, New, Op, RefTo, SampleSpec, Step, Var, quote
23
+
24
+ __all__ = ["ESTIMATORS", "Estimation", "Fit", "LEFT_ESTIMATORS"]
25
+
26
+ # EViews's estimation commands translated here
27
+ ESTIMATORS = ("ls", "tsls", "gmm", "liml", "arch", "binary", "logit", "probit", "ordered", "censored", "count", "qreg", "heckit",
28
+ "ardl")
29
+ # left out, naming pymetrix's equivalents (design note: phase 2b if wanted)
30
+ LEFT_ESTIMATORS = {
31
+ "stepls": "stepwise least squares has no pymetrix equivalent; choose the regressors, then Equation(...).fit(data)",
32
+ "breakls": "least squares with breaks: bai_perron(...) finds the breaks; then fit each regime (Equation(...).fit(data, span=...))",
33
+ "threshold": "threshold regression: ThresholdAR(...).fit(data) (Model → Threshold autoregression)",
34
+ "switchreg": "switching regression: MarkovSwitching(...).fit(data)",
35
+ "glm": "generalised linear models: Equation(..., family=Logit(), Probit(), Poisson() ...).fit(data, method=ML())",
36
+ "nls": "EViews's nls options are not translated: an expression specification with ls is (Equation in explicit form)",
37
+ }
38
+ _NOTE_HAC = ("HAC (Newey-West) standard errors: EViews's default bandwidth and kernel may differ from pymetrix's "
39
+ "(Bartlett, floor(4(n/100)^(2/9)) lags); check them and give hac_lags= to match")
40
+ _NOTE_ARMA = ("ARMA errors are estimated by exact maximum likelihood (method=ML()); EViews's default ARMA estimator differs "
41
+ "by version (verify: conditional least squares, or ML/GLS from EViews 10), so estimates may differ")
42
+
43
+
44
+ @dataclass
45
+ class Fit:
46
+ """An estimated object of the program: its Python name, what it is, its page, its coefficient map (pymetrix's names
47
+ in EViews's c(i) order) and what its re-reading by the model reader needs."""
48
+
49
+ var: str
50
+ kind: str # equation, var, vecm, system, ardl
51
+ page: Any
52
+ coefs: list[str] = field(default_factory=list)
53
+ method: str = "ls"
54
+ classic: bool = True # least squares with classic standard errors
55
+ spec: str = "" # the EViews specification (for m.merge)
56
+ sample: Any = None # the page's sample when it was estimated
57
+ dependent: str = ""
58
+ vector: str = "c"
59
+
60
+
61
+ def _split_top(text: str, at: int) -> list[tuple[str, int]]:
62
+ """Words separated by spaces outside brackets, with their offsets."""
63
+ out, depth, start = [], 0, None
64
+ for i, ch in enumerate(text + " "):
65
+ if ch == "(":
66
+ depth += 1
67
+ elif ch == ")":
68
+ depth -= 1
69
+ if ch.isspace() and depth <= 0:
70
+ if start is not None:
71
+ out.append((text[start:i], at + start))
72
+ start = None
73
+ elif start is None:
74
+ start = i
75
+ return out
76
+
77
+
78
+ def _commas(text: str | None) -> list[str]:
79
+ """Options split at commas outside brackets."""
80
+ out, depth, word = [], 0, ""
81
+ for ch in text or "":
82
+ depth += (ch == "(") - (ch == ")")
83
+ if ch == "," and depth == 0:
84
+ out.append(word.strip())
85
+ word = ""
86
+ else:
87
+ word += ch
88
+ if word.strip():
89
+ out.append(word.strip())
90
+ return out
91
+
92
+
93
+ def _options(text: str | None) -> tuple[dict[str, str], list[str]]:
94
+ """``key=value`` options (keys lower case) and the flags, in order."""
95
+ named: dict[str, str] = {}
96
+ flags: list[str] = []
97
+ for part in _commas(text):
98
+ if "=" in part:
99
+ k, _, v = part.partition("=")
100
+ named[k.strip().lower()] = v.strip().strip('"')
101
+ else:
102
+ flags.append(part.strip().lower())
103
+ return named, flags
104
+
105
+
106
+ def _value(text: str, what: str, kind: Any = int) -> Any:
107
+ """An option's number, or the line left out saying it is not one (a scalar's name, say)."""
108
+ from .data import _left
109
+
110
+ try:
111
+ return kind(text)
112
+ except (TypeError, ValueError):
113
+ raise _left(f"{what}={text} is not translated: a number is") from None
114
+
115
+
116
+ def _term_name(term: str) -> str:
117
+ """The name pymetrix gives a term's coefficient: its text, without brackets around all of it."""
118
+ t = term.strip()
119
+ while t.startswith("(") and t.endswith(")"):
120
+ depth = 0
121
+ for i, ch in enumerate(t):
122
+ depth += (ch == "(") - (ch == ")")
123
+ if depth == 0 and i < len(t) - 1:
124
+ return t
125
+ t = t[1:-1].strip()
126
+ return t
127
+
128
+
129
+ def _in_restriction(name: str) -> str:
130
+ return name if re.fullmatch(r"[A-Za-z_]\w*(\[-?\d+\])?|const|[A-Za-z_]\w*\([^()]*\)", name) else f"({name})"
131
+
132
+
133
+ @dataclass
134
+ class _Spec:
135
+ formula: str
136
+ params: list[str]
137
+ coefs: list[str] # by c(i), from 1
138
+ dependent: str
139
+ terms: list[str] # regressors as pymetrix writes them (no c)
140
+ intercept: bool
141
+ ar: list[int]
142
+ ma: list[int]
143
+ explicit: bool
144
+ vector: str = "c"
145
+
146
+
147
+ class Estimation:
148
+ """The phase 2 handlers for estimation and tests, mixed into the ``Translator`` (``data.py``)."""
149
+
150
+ # -- specifications ---------------------------------------------------------------------------------------------
151
+
152
+ def _list_terms(self, words: list[tuple[str, int]], page: Any, arma: bool, what: str) -> tuple[list[str], bool, list[int], list[int]]:
153
+ from .data import _left
154
+
155
+ terms: list[str] = []
156
+ intercept = False
157
+ ar: list[int] = []
158
+ ma: list[int] = []
159
+ for word, at in words:
160
+ low = word.lower()
161
+ if low == "c":
162
+ intercept = True
163
+ terms.append("const")
164
+ continue
165
+ m = re.fullmatch(r"(ar|ma)\(\s*(\d+)\s*\)", low)
166
+ if m:
167
+ if not arma:
168
+ raise _left(f"{word}: ARMA terms are translated for ls only")
169
+ (ar if m.group(1) == "ar" else ma).append(int(m.group(2)))
170
+ terms.append(f"{m.group(1)}[{int(m.group(2))}]")
171
+ continue
172
+ if re.match(r"(sar|sma|ar|ma)\(", low):
173
+ raise _left(f"{word}: seasonal ARMA terms and ARMA ranges are not translated: Equation(..., errors=ARMA(ar=[...], "
174
+ "ma=[...])) with the lags listed")
175
+ if low.startswith(("pdl(", "@expand(")) or low in ("@expand", "pdl"):
176
+ raise _left(f"{word}: polynomial distributed lags and @expand are not translated: write the terms out")
177
+ text = self.expression(word, at, page)
178
+ if text.names:
179
+ raise _left(f"{word} uses the program's scalars ({', '.join(text.names)}): a {what}'s regressors are series")
180
+ terms.append(str(text))
181
+ return terms, intercept, ar, ma
182
+
183
+ def _spec(self, text: str, at: int, page: Any, arma: bool = False, what: str = "specification") -> _Spec:
184
+ """A list or expression specification as pymetrix's formula, with the coefficient map."""
185
+ from .data import _error, _left, _top_level
186
+
187
+ if _top_level(text, "="):
188
+ split = _top_level(text, "=")
189
+ if len(split) != 1:
190
+ raise _error("an expression specification has one '=': y = c(1) + c(2)*x")
191
+ lhs = self.expression(text[:split[0]], at, page)
192
+ rhs = self.expression(text[split[0] + 1:], at + split[0] + 1, page, coefs=True)
193
+ if lhs.names or rhs.names:
194
+ raise _left("an expression specification that uses the program's scalars is not translated: put their values in")
195
+ found = sorted({(m.group(1), int(m.group(2))) for m in re.finditer(r"(?<![\w.])([A-Za-z_]\w*)_(\d+)(?!\w)", str(rhs))
196
+ if m.group(1) in self._vectors()}, key=lambda p: (p[0], p[1]))
197
+ if not found:
198
+ raise _error("an expression specification needs coefficients: c(1), c(2) ...")
199
+ vectors = {v for v, _ in found}
200
+ if len(vectors) > 1:
201
+ raise _left("an expression specification with two coefficient vectors is not translated")
202
+ vector = vectors.pop()
203
+ params = [f"{vector}_{i}" for _, i in found]
204
+ top = max(i for _, i in found)
205
+ coefs = [f"{vector}_{i}" for i in range(1, top + 1)]
206
+ dependent = _term_name(str(lhs))
207
+ return _Spec(f"{lhs} ~ {rhs}", params, coefs, dependent, [], False, [], [], True, vector)
208
+ words = _split_top(text, at)
209
+ if len(words) < 2:
210
+ raise _error("a specification is: dependent regressor ... (c the constant), or y = c(1) + c(2)*x")
211
+ dep = self.expression(words[0][0], words[0][1], page)
212
+ if dep.names:
213
+ raise _left("a dependent variable that uses the program's scalars is not translated")
214
+ if words[0][0].lower() == "c":
215
+ raise _error("the first in a list specification is the dependent variable, not c")
216
+ terms, intercept, ar, ma = self._list_terms(words[1:], page, arma, what)
217
+ regressors = [t for t in terms if t != "const" and not re.fullmatch(r"(ar|ma)\[\d+\]", t)]
218
+ if not regressors and not intercept:
219
+ raise _error("a specification with nothing to estimate")
220
+ rhs = " + ".join(f"({t})" if t.startswith("-") else t for t in regressors) or "1"
221
+ if not intercept and regressors:
222
+ rhs += " - 1"
223
+ coefs = [_term_name(t) if t not in ("const",) else "const" for t in terms]
224
+ return _Spec(f"{dep} ~ {rhs}", [], coefs, _term_name(str(dep)), regressors, intercept, ar, ma, False)
225
+
226
+ def _vectors(self) -> set[str]:
227
+ return {"c"} | {k for k, v in self.types.items() if v == "coef"}
228
+
229
+ # -- equations --------------------------------------------------------------------------------------------------
230
+
231
+ def _cmd_equation(self, st: Any) -> tuple[list[Op], str]:
232
+ from .data import _error
233
+ from .parse import _options as bracket
234
+
235
+ m = re.match(r"\s*([A-Za-z_]\w*)(?:\.(\w+))?", st.rest)
236
+ if m is None:
237
+ raise _error("equation names the equation: equation eq.ls y c x")
238
+ name, method = m.group(1), (m.group(2) or "").lower()
239
+ options, after = bracket(st.rest, m.end())
240
+ spec = st.rest[after:]
241
+ spec_at = st.rest_at + after + (len(spec) - len(spec.lstrip()))
242
+ self.types[name.lower()] = "equation"
243
+ if not method:
244
+ if spec.strip():
245
+ return self._estimate(st, "ls", options, spec.strip(), spec_at, name)
246
+ return [], "the equation is declared; a later line estimates it (no step)"
247
+ return self._estimate(st, method, options, spec.strip(), spec_at, name)
248
+
249
+ def _estimator(self, st: Any) -> tuple[list[Op], str]:
250
+ """A bare estimation command (``ls y c x``): an equation EViews calls untitled."""
251
+ return self._estimate(st, st.word, st.options, st.rest, st.rest_at, None)
252
+
253
+ _cmd_ls = _cmd_tsls = _cmd_gmm = _cmd_liml = _cmd_arch = _cmd_binary = _cmd_logit = _cmd_probit = _estimator
254
+ _cmd_ordered = _cmd_censored = _cmd_count = _cmd_qreg = _cmd_heckit = _cmd_ardl = _estimator
255
+
256
+ def _left_estimator(self, st: Any) -> tuple[list[Op], str]:
257
+ from .data import _left
258
+
259
+ raise _left(f"{st.word}: {LEFT_ESTIMATORS[st.word]}")
260
+
261
+ _cmd_stepls = _cmd_breakls = _cmd_threshold = _cmd_switchreg = _cmd_glm = _cmd_nls = _left_estimator
262
+
263
+ def _estimate(self, st: Any, method: str, options: str | None, spec: str, at: int, name: str | None) -> tuple[list[Op], str]:
264
+ from .data import _error, _left
265
+
266
+ if method in LEFT_ESTIMATORS:
267
+ raise _left(f"{method}: {LEFT_ESTIMATORS[method]}")
268
+ if method not in ESTIMATORS:
269
+ raise _left(f"{method} is not an estimation method translated here: ls, tsls, gmm, liml, arch, binary, ordered, "
270
+ "censored, count, qreg, heckit and ardl are")
271
+ if not spec.strip():
272
+ raise _error(f"{method} needs a specification")
273
+ page = self._page()
274
+ if method == "ardl":
275
+ return self._ardl(st, options, spec, at, name, page)
276
+ named, flags = _options(options)
277
+ notes: list[str] = []
278
+ instruments: list[str] | None = None
279
+ selection: str | None = None
280
+ main, main_at = spec, at
281
+ if method in ("tsls", "gmm", "liml", "heckit"):
282
+ parts = re.split(r"(?:^|\s)@(?:\s|$)", spec)
283
+ if len(parts) != 2:
284
+ raise _error(f"{method} takes the specification, then @ and the {'selection equation' if method == 'heckit' else 'instruments'}: "
285
+ f"{method} y c x @ c z")
286
+ main = parts[0]
287
+ rest_at = at + spec.index(parts[1], len(parts[0]))
288
+ if method == "heckit":
289
+ selection = parts[1]
290
+ sel_at = rest_at
291
+ else:
292
+ words = _split_top(parts[1], rest_at)
293
+ ins, has_c, _, _ = self._list_terms(words, page, False, "instrument list")
294
+ instruments = [t for t in ins if t != "const"]
295
+ if not has_c:
296
+ notes.append("the instruments have no c: pymetrix's IV, GMM and LIML add the constant (verify that EViews's "
297
+ "estimate has it among its instruments)")
298
+ elif "@" in re.sub(r"@\w+", "", spec):
299
+ raise _left(f"{method} with @ in its specification is not translated")
300
+ s = self._spec(main, main_at, page, arma=(method == "ls"), what="specification")
301
+ if s.ar or s.ma:
302
+ if s.explicit:
303
+ raise _left("ARMA terms in an expression specification are not translated")
304
+ eq_args: list[Arg] = [Arg("text", s.formula, "pos")]
305
+ if s.params:
306
+ eq_args.append(Arg("params", tuple(s.params)))
307
+ method_new: New | None = None
308
+ classic = True
309
+ used: set[str] = set()
310
+
311
+ def take(*keys: str) -> None:
312
+ used.update(keys)
313
+
314
+ if method == "ls":
315
+ cov = self._cov(named, flags, notes, take)
316
+ classic = cov == "classic"
317
+ if s.ar or s.ma:
318
+ orders = [Arg(k, _order(v)) for k, v in (("ar", s.ar), ("ma", s.ma)) if v]
319
+ eq_args.append(Arg("errors", New("ARMA", tuple(orders))))
320
+ method_new = New("ML", (Arg("cov", cov),) if cov != "classic" else ())
321
+ notes.append(_NOTE_ARMA)
322
+ if cov == "hac":
323
+ raise _left("HAC standard errors with ARMA terms are not translated: ML gives classic or white (sandwich)")
324
+ elif cov != "classic":
325
+ method_new = New("OLS", (Arg("cov", cov),))
326
+ elif method in ("tsls", "liml"):
327
+ assert instruments is not None
328
+ cov = self._cov(named, flags, notes, take)
329
+ classic = False
330
+ names = set(instruments)
331
+ endog = [t for t in s.terms if t not in names]
332
+ excluded = [t for t in instruments if t not in s.terms]
333
+ if s.explicit:
334
+ raise _left(f"{method} with an expression specification is not translated: GMM(instruments=[...]) takes one")
335
+ if not endog:
336
+ notes.append("every regressor is among the instruments: the estimate is least squares'")
337
+ args = [Arg("endog", tuple(endog)), Arg("instruments", tuple(excluded))]
338
+ if cov != "classic":
339
+ args.append(Arg("cov", cov))
340
+ method_new = New("IV" if method == "tsls" else "LIML", tuple(args))
341
+ elif method == "gmm":
342
+ assert instruments is not None
343
+ classic = False
344
+ take("instwgt", "cov")
345
+ wgt = named.get("instwgt", "white").lower()
346
+ if wgt not in ("white", "hac"):
347
+ raise _left(f"gmm(instwgt={wgt}) is not translated: white and hac weights are")
348
+ args = [Arg("instruments", tuple(instruments))]
349
+ if wgt == "hac":
350
+ args.append(Arg("cov", "hac"))
351
+ notes.append(_NOTE_HAC)
352
+ method_new = New("GMM", tuple(args))
353
+ notes.append("GMM: pymetrix's two-step estimator with White weights; EViews's default iterations of the weighting "
354
+ "matrix and its covariance options may differ (verify: gmm's instwgt=, w= and iteration options)")
355
+ elif method == "arch":
356
+ classic = False
357
+ numbers = [f for f in flags if re.fullmatch(r"\d+", f)]
358
+ p, q = (int(numbers[0]), int(numbers[1])) if len(numbers) >= 2 else ((int(numbers[0]), 1) if numbers else (1, 1))
359
+ take(*numbers)
360
+ dist = "normal"
361
+ if "tdist" in flags or named.get("dist", "").lower() in ("t", "tdist"):
362
+ dist = "t"
363
+ take("tdist", "dist")
364
+ elif "ged" in flags or named.get("dist", "").lower() == "ged":
365
+ dist = "ged"
366
+ take("ged", "dist")
367
+ elif "dist" in named and named["dist"].lower() not in ("n", "normal"):
368
+ raise _left(f"arch(dist={named['dist']}) is not translated: normal, t and ged errors are")
369
+ take("dist")
370
+ var_args = [Arg("arch", p), Arg("garch", q)]
371
+ if "egarch" in flags:
372
+ take("egarch")
373
+ cls = "EGARCH"
374
+ else:
375
+ cls = "GARCH"
376
+ if "thrsh" in named:
377
+ take("thrsh")
378
+ var_args.append(Arg("asym", _value(named["thrsh"], "thrsh")))
379
+ notes.append("thrsh= (TARCH): pymetrix's GARCH(asym=...), the GJR form with the threshold on the variance, "
380
+ "as EViews's TARCH (verify)")
381
+ if dist != "normal":
382
+ var_args.append(Arg("dist", dist))
383
+ eq_args.append(Arg("variance", New(cls, tuple(var_args))))
384
+ method_new = New("ML", ())
385
+ notes.append("GARCH by maximum likelihood: EViews backcasts the first conditional variance and uses Marquardt "
386
+ "steps (verify the presample variance), so estimates may differ in the last digits")
387
+ if s.explicit:
388
+ raise _left("arch with an expression specification is not translated")
389
+ elif method in ("binary", "logit", "probit"):
390
+ classic = False
391
+ d = (named.get("d") or {"logit": "l", "probit": "n"}.get(method, "n")).lower()
392
+ take("d")
393
+ if d == "x":
394
+ raise _left("binary(d=x), the extreme-value (complementary log-log) link, has no pymetrix family: a gap "
395
+ "(docs/known-gaps.md); Logit() and Probit() are translated")
396
+ if d not in ("l", "n"):
397
+ raise _left(f"binary(d={d}) is not translated: d=l (logit) and d=n (probit) are")
398
+ eq_args.append(Arg("family", New("Logit" if d == "l" else "Probit")))
399
+ method_new = New("ML", ())
400
+ if "d" not in named and method == "binary":
401
+ notes.append("binary without d=: probit, EViews's default (verify)")
402
+ elif method == "ordered":
403
+ classic = False
404
+ d = named.get("d", "n").lower()
405
+ take("d")
406
+ if d not in ("l", "n"):
407
+ raise _left(f"ordered(d={d}) is not translated: d=l (OrderedLogit) and d=n (OrderedProbit) are; the "
408
+ "extreme-value link is a gap")
409
+ if s.intercept:
410
+ notes.append("the constant is dropped: the cut points stand for it, as in EViews")
411
+ s.coefs = [c for c in s.coefs if c != "const"]
412
+ eq_args.append(Arg("family", New("OrderedLogit" if d == "l" else "OrderedProbit")))
413
+ method_new = New("ML", ())
414
+ elif method == "censored":
415
+ classic = False
416
+ d = named.get("d", "n").lower()
417
+ take("d", "l", "r")
418
+ if d != "n":
419
+ raise _left(f"censored(d={d}) is not translated: normal errors (Tobit) are; logistic and extreme-value errors "
420
+ "are a gap")
421
+ if any(f in flags for f in ("i", "t")):
422
+ raise _left("censored with limits given as series (i) or truncation (t) is not translated: Tobit(left=, right=) "
423
+ "takes numbers")
424
+ try:
425
+ left = float(named["l"]) if named.get("l", "") != "" else 0.0
426
+ right = float(named["r"]) if named.get("r", "") != "" else None
427
+ except ValueError:
428
+ raise _left("censoring limits given as series are not translated: Tobit(left=, right=) takes numbers") from None
429
+ tob = [Arg("left", left)] + ([Arg("right", right)] if right is not None else [])
430
+ if "l" not in named:
431
+ notes.append("censored at zero from below, EViews's default (verify)")
432
+ eq_args.append(Arg("family", New("Tobit", tuple(tob))))
433
+ method_new = New("ML", ())
434
+ elif method == "count":
435
+ classic = False
436
+ d = named.get("d", "p").lower()
437
+ take("d")
438
+ if d not in ("p", "n"):
439
+ raise _left(f"count(d={d}) is not translated: d=p (Poisson) and d=n (negative binomial) are")
440
+ eq_args.append(Arg("family", New("Poisson" if d == "p" else "NegativeBinomial")))
441
+ method_new = New("ML", ())
442
+ if d == "n":
443
+ notes.append("the negative binomial: pymetrix's NB2 with its dispersion estimated; check EViews's v= option "
444
+ "(verify)")
445
+ elif method == "qreg":
446
+ classic = False
447
+ take("quant")
448
+ try:
449
+ q = float(named.get("quant", "0.5"))
450
+ except ValueError:
451
+ raise _left(f"qreg(quant={named.get('quant')}) is not a number") from None
452
+ method_new = New("Quantile", (Arg("q", q),) if q != 0.5 else ())
453
+ notes.append("quantile regression: the estimates are the same; the standard errors use pymetrix's Hall-Sheather "
454
+ "sandwich, and EViews's default covariance and bandwidth may differ (verify)")
455
+ elif method == "heckit":
456
+ classic = False
457
+ assert selection is not None
458
+ words = _split_top(selection, sel_at)
459
+ if len(words) < 2:
460
+ raise _error("heckit's selection equation is: s c z1 z2 (after @)")
461
+ sel = self._spec(selection, sel_at, page, what="selection equation")
462
+ take("2step", "ml")
463
+ args = [Arg("selection", sel.formula)]
464
+ if "2step" in flags:
465
+ args.append(Arg("estimator", "twostep"))
466
+ else:
467
+ args.append(Arg("estimator", "ml"))
468
+ notes.append("maximum likelihood, EViews's default for heckit (verify; 2step gives Heckman's two steps)")
469
+ method_new = New("Heckman", tuple(args))
470
+ unused = [k for k in named if k not in used] + [f for f in flags if f not in used]
471
+ if unused:
472
+ raise _left(f"{method}'s option{'s' if len(unused) > 1 else ''} {', '.join(unused)} {'are' if len(unused) > 1 else 'is'} "
473
+ "not translated: the estimate would differ without saying so")
474
+ return self._fit_step(st, name, page, s, eq_args, method_new, method, classic, spec, notes)
475
+
476
+ def _cov(self, named: dict[str, str], flags: list[str], notes: list[str], take: Any) -> str:
477
+ from .data import _left
478
+
479
+ cov = "classic"
480
+ if "cov" in named:
481
+ take("cov")
482
+ value = named["cov"].lower()
483
+ cov = {"white": "white", "hac": "hac", "ordinary": "classic", "default": "classic"}.get(value, "")
484
+ if not cov:
485
+ raise _left(f"cov={value} is not translated: white, hac and ordinary are")
486
+ if "h" in flags:
487
+ take("h")
488
+ cov = "white"
489
+ notes.append("h, an older letter for White's standard errors (cov=white from EViews 8): verify for your version")
490
+ if "n" in flags:
491
+ take("n")
492
+ cov = "hac"
493
+ notes.append("n, an older letter for Newey-West standard errors (cov=hac from EViews 8): verify for your version")
494
+ if cov == "white":
495
+ notes.append("White's standard errors: HC1, as EViews's (docs/design/definitions.md)")
496
+ if cov == "hac":
497
+ notes.append(_NOTE_HAC)
498
+ return cov
499
+
500
+ def _fit_name(self, name: str | None) -> str:
501
+ if name is None:
502
+ var, _ = self._name("untitled", "equation untitled")
503
+ return var
504
+ var, _ = self._name(name, f"equation {name.lower()}")
505
+ return var
506
+
507
+ def _fit_step(self, st: Any, name: str | None, page: Any, s: _Spec, eq_args: list[Arg], method_new: New | None, method: str,
508
+ classic: bool, spec_text: str, notes: list[str]) -> tuple[list[Op], str]:
509
+ var = self._fit_name(name)
510
+ if name is not None:
511
+ eq_args.append(Arg("name", name.lower()))
512
+ equation = New("Equation", tuple(eq_args))
513
+ args = [Arg("data", RefTo(page.var), "pos")]
514
+ if method_new is not None:
515
+ args.append(Arg("method", method_new))
516
+ step = Step("pymetrix:equation.fit", equation, var, f"{equation.code()}.fit", tuple(args))
517
+ fit = Fit(var, "equation", page, s.coefs, method, classic and method == "ls" and not (s.ar or s.ma), spec_text,
518
+ page.sample, s.dependent, s.vector)
519
+ self.fits[(name or "untitled").lower()] = fit
520
+ self.types[(name or "untitled").lower()] = "equation"
521
+ self._fit_line[(name or "untitled").lower()] = self.line
522
+ if s.vector == "c":
523
+ self.last_fit = fit
524
+ if name is None:
525
+ notes.insert(0, f"an equation EViews calls untitled: kept as {var}")
526
+ return [step], "; ".join(notes)
527
+
528
+ def _ardl(self, st: Any, options: str | None, spec: str, at: int, name: str | None, page: Any) -> tuple[list[Op], str]:
529
+ from .data import _error, _left
530
+
531
+ named, flags = _options(options)
532
+ parts = re.split(r"(?:^|\s)@(?:\s|$)", spec)
533
+ if len(parts) > 1:
534
+ raise _left("ardl with fixed regressors after @ is not translated: ARDL(...) takes the distributed-lag regressors")
535
+ words = _split_top(spec, at)
536
+ if len(words) < 2:
537
+ raise _error("ardl takes the dependent variable and the regressors: ardl y x1 x2")
538
+ terms, intercept, _, _ = self._list_terms(words, page, False, "ARDL")
539
+ if intercept:
540
+ raise _left("ardl with c in the list is not translated: the constant is trend= (trend=const)")
541
+ dep, regs = terms[0], terms[1:]
542
+ if not regs:
543
+ raise _error("ardl needs at least one regressor")
544
+ trend = {"none": "n", "const": "c", "linear": "ct"}.get(named.pop("trend", "const").lower())
545
+ if trend is None:
546
+ raise _left("ardl(trend=...) is not translated: none, const and linear are")
547
+ try:
548
+ deplags = int(named.pop("deplags", "4"))
549
+ reglags = int(named.pop("reglags", "4"))
550
+ except ValueError:
551
+ raise _left("ardl's lags are not whole numbers") from None
552
+ ic = named.pop("ic", "aic").lower()
553
+ notes = []
554
+ args = [Arg("formula", f"{dep} ~ {' + '.join(regs)}", "pos")]
555
+ if "fixed" in flags:
556
+ flags.remove("fixed")
557
+ args += [Arg("lags", deplags), Arg("order", reglags)]
558
+ else:
559
+ crit = {"aic": "aic", "sic": "bic", "bic": "bic", "hq": "hqic", "hqc": "hqic"}.get(ic)
560
+ if crit is None:
561
+ raise _left(f"ardl(ic={ic}) is not translated: aic, sic and hq are")
562
+ args += [Arg("select", crit), Arg("max_lags", deplags), Arg("max_order", reglags)]
563
+ notes.append(f"the lags chosen by {ic.upper()} up to {deplags} and {reglags}, as EViews's default search (verify the "
564
+ "default maximum lags and whether EViews searches each regressor's lag separately)")
565
+ if trend != "c":
566
+ args.append(Arg("trend", trend))
567
+ if named or flags:
568
+ raise _left(f"ardl's options {', '.join([*named, *flags])} are not translated")
569
+ var = self._fit_name(name)
570
+ ardl = New("ARDL", tuple(args))
571
+ step = Step("pymetrix:ardl.fit", ardl, var, f"{ardl.code()}.fit", (Arg("data", RefTo(page.var), "pos"),))
572
+ self.fits[(name or "untitled").lower()] = Fit(var, "ardl", page, [], "ardl", False, spec, page.sample, _term_name(dep))
573
+ self.types[(name or "untitled").lower()] = "equation"
574
+ return [step], "; ".join(notes)
575
+
576
+ # -- VARs and VECs ----------------------------------------------------------------------------------------------
577
+
578
+ def _cmd_var(self, st: Any) -> tuple[list[Op], str]:
579
+ from .data import _error
580
+ from .parse import _options as bracket
581
+
582
+ m = re.match(r"\s*([A-Za-z_]\w*)(?:\.(\w+))?", st.rest)
583
+ if m is None:
584
+ raise _error("var names the VAR: var v.ls 1 4 y1 y2 @ c")
585
+ name, method = m.group(1), (m.group(2) or "").lower()
586
+ options, after = bracket(st.rest, m.end())
587
+ self.types[name.lower()] = "var"
588
+ if not method:
589
+ return [], "the VAR is declared; a later line estimates it (no step)"
590
+ rest = st.rest[after:]
591
+ rest_at = st.rest_at + after + (len(rest) - len(rest.lstrip()))
592
+ if method == "ec":
593
+ return self._vec(name, options, rest.strip(), rest_at)
594
+ return self._var(name, method, options, rest.strip(), rest_at)
595
+
596
+ def _var(self, name: str, method: str, options: str | None, spec: str, at: int) -> tuple[list[Op], str]:
597
+ from .data import _error, _left
598
+
599
+ page = self._page()
600
+ named, flags = _options(options)
601
+ endo_text, _, exo_text = spec.partition("@")
602
+ words = _split_top(endo_text, at)
603
+ lags: list[int] = []
604
+ while words and re.fullmatch(r"\d+", words[0][0]):
605
+ lags.append(int(words.pop(0)[0]))
606
+ if len(lags) % 2 or not lags:
607
+ raise _error("a VAR's lags come in pairs before the variables: v.ls 1 4 y1 y2")
608
+ pairs = list(zip(lags[::2], lags[1::2]))
609
+ if pairs != [(1, pairs[0][1])]:
610
+ raise _left("lags other than one range from 1 (1 4) are not translated: VAR(..., lags=n) takes lags 1 to n")
611
+ n = pairs[0][1]
612
+ endog, has_c, _, _ = self._list_terms(words, page, False, "VAR")
613
+ if has_c:
614
+ raise _error("c goes after @ in a VAR")
615
+ if not all(re.fullmatch(r"[A-Za-z_]\w*", v) for v in endog):
616
+ raise _left("a VAR's endogenous variables must be series: make the transformed series first")
617
+ exo: list[str] = []
618
+ trend = "n"
619
+ notes: list[str] = []
620
+ if exo_text.strip():
621
+ exo_words = _split_top(exo_text, at + len(endo_text) + 1)
622
+ for w, _ in exo_words:
623
+ if w.lower() in ("@trend",):
624
+ if trend != "c":
625
+ raise _left("@trend without c in a VAR is not translated")
626
+ trend = "ct"
627
+ continue
628
+ exo_words = [(w, a) for w, a in exo_words if w.lower() != "@trend"]
629
+ terms, has_c, _, _ = self._list_terms(exo_words, page, False, "VAR")
630
+ if has_c:
631
+ trend = "ct" if trend == "ct" else "c"
632
+ exo = [t for t in terms if t != "const"]
633
+ else:
634
+ notes.append("no c after @: the VAR has no constant, as EViews writes it (verify)")
635
+ if named or flags:
636
+ raise _left(f"the VAR's options {', '.join([*named, *flags])} are not translated")
637
+ var, _ = self._name(name, f"var {name.lower()}")
638
+ if method == "ls":
639
+ args = [Arg("variables", tuple(endog), "pos"), Arg("lags", n)]
640
+ if exo:
641
+ args.append(Arg("exog", tuple(exo)))
642
+ if trend != "c":
643
+ args.append(Arg("trend", trend))
644
+ model = New("VAR", tuple(args))
645
+ step = Step("pymetrix:var.fit", model, var, f"{model.code()}.fit", (Arg("data", RefTo(page.var), "pos"),))
646
+ self.fits[name.lower()] = Fit(var, "var", page, [], "var", False, spec, page.sample)
647
+ return [step], "; ".join(notes)
648
+ raise _left(f"{name}.{method} is not translated: ls and ec are")
649
+
650
+ def _vec(self, name: str, options: str | None, spec: str, at: int) -> tuple[list[Op], str]:
651
+ from .data import _error, _left
652
+
653
+ page = self._page()
654
+ parts = _commas(options)
655
+ case = (parts[0].lower() if parts else "c")
656
+ try:
657
+ rank = int(parts[1]) if len(parts) > 1 else 1
658
+ except ValueError:
659
+ raise _left(f"ec({options}): the number of cointegrating relations is not a number") from None
660
+ if len(parts) > 2:
661
+ raise _left(f"ec's options {', '.join(parts[2:])} are not translated")
662
+ det = {"a": "n", "b": "ci", "c": "co", "d": "coli"}.get(case)
663
+ if det is None:
664
+ raise _left(f"ec({case}): EViews's case {case} is not translated: a, b, c and d are (VECM(deterministic=...))")
665
+ endo_text, _, exo_text = spec.partition("@")
666
+ if exo_text.strip():
667
+ raise _left("exogenous variables in a VEC are not translated: VECM(..., exog=[...])")
668
+ words = _split_top(endo_text, at)
669
+ lags: list[int] = []
670
+ while words and re.fullmatch(r"\d+", words[0][0]):
671
+ lags.append(int(words.pop(0)[0]))
672
+ if len(lags) != 2 or lags[0] != 1:
673
+ raise _error("a VEC's lags are one range from 1 before the variables: v.ec(c, 1) 1 4 y1 y2")
674
+ endog, has_c, _, _ = self._list_terms(words, page, False, "VEC")
675
+ if has_c or not all(re.fullmatch(r"[A-Za-z_]\w*", v) for v in endog):
676
+ raise _left("a VEC's variables must be series")
677
+ var, _ = self._name(name, f"var {name.lower()}")
678
+ args = [Arg("variables", tuple(endog), "pos"), Arg("lags", lags[1]), Arg("rank", rank)]
679
+ if det != "co":
680
+ args.append(Arg("deterministic", det))
681
+ model = New("VECM", tuple(args))
682
+ step = Step("pymetrix:vecm.fit", model, var, f"{model.code()}.fit", (Arg("data", RefTo(page.var), "pos"),))
683
+ self.fits[name.lower()] = Fit(var, "vecm", page, [], "ec", False, spec, page.sample)
684
+ note = (f"EViews's lags 1 {lags[1]} of the VEC are in first differences: VECM(lags={lags[1]}); case {case} is "
685
+ f"deterministic={det!r} (verify the cases against EViews's table of the five)")
686
+ return [step], note
687
+
688
+ # -- systems ----------------------------------------------------------------------------------------------------
689
+
690
+ def _cmd_system(self, st: Any) -> tuple[list[Op], str]:
691
+ from .data import _error
692
+
693
+ m = re.fullmatch(r"\s*([A-Za-z_]\w*)\s*", st.rest)
694
+ if m is None:
695
+ raise _error("system names the system: system s")
696
+ self.systems[m.group(1).lower()] = {"lines": [], "instruments": [], "name": m.group(1)}
697
+ self.types[m.group(1).lower()] = "system"
698
+ return [], "the system's equations are collected; a later line estimates it (no step)"
699
+
700
+ def _system_method(self, st: Any, key: str) -> tuple[list[Op], str]:
701
+ from .data import _error, _left
702
+
703
+ sysinfo = self.systems[key]
704
+ page = self._page()
705
+ if st.word == "append":
706
+ text = st.rest.strip()
707
+ if text.lower().startswith("@inst"):
708
+ words = _split_top(text[5:], st.rest_at + 5)
709
+ ins, has_c, _, _ = self._list_terms(words, page, False, "instrument list")
710
+ sysinfo["instruments"] += [t for t in ins if t != "const"]
711
+ return [], "instruments of the system (no step)"
712
+ if text.startswith("@"):
713
+ raise _left(f"{text.split()[0]} in a system is not translated: equations and @inst are")
714
+ s = self._spec(text, st.rest_at, page)
715
+ if not s.explicit:
716
+ raise _left("a system's equations are written with their coefficients: y = c(1) + c(2)*x")
717
+ sysinfo["lines"].append(s)
718
+ return [], "an equation of the system (no step)"
719
+ methods = {"sur": "SUR", "3sls": "ThreeSLS", "fiml": "FIML", "tsls": "TwoSLS"}
720
+ if st.word in methods:
721
+ if not sysinfo["lines"]:
722
+ raise _error(f"the system {sysinfo['name']} has no equations")
723
+ if st.word in ("3sls", "tsls") and not sysinfo["instruments"]:
724
+ raise _error(f"{st.word} needs instruments: {sysinfo['name']}.append @inst z1 z2")
725
+ if st.options:
726
+ raise _left(f"{st.word}({st.options}): the system's estimation options are not translated")
727
+ eqs = tuple(New("Equation", (Arg("text", s.formula, "pos"), Arg("params", tuple(s.params)))) for s in sysinfo["lines"])
728
+ sargs = [Arg("equations", eqs, "pos")]
729
+ if sysinfo["instruments"]:
730
+ sargs.append(Arg("instruments", tuple(dict.fromkeys(sysinfo["instruments"]))))
731
+ system = New("System", tuple(sargs))
732
+ var, _ = self._name(sysinfo["name"], f"system {key}")
733
+ step = Step("pymetrix:system.fit", system, var, f"{system.code()}.fit",
734
+ (Arg("data", RefTo(page.var), "pos"), Arg("method", New(methods[st.word]))))
735
+ coefs = sorted({c for s in sysinfo["lines"] for c in s.params}, key=lambda c: int(c.rpartition("_")[2]))
736
+ fit = Fit(var, "system", page, [f"c_{i}" for i in range(1, max(int(c.rpartition('_')[2]) for c in coefs) + 1)],
737
+ st.word, False, "", page.sample)
738
+ self.fits[key] = fit
739
+ self.last_fit = fit
740
+ return [step], ("the coefficients c(i) shared across the equations are the parameters c_i; EViews's default "
741
+ "iteration of the weights may differ (verify: the system's estimation options)")
742
+ if st.word == "ls":
743
+ raise _left(f"{sysinfo['name']}.ls (each equation by least squares) is not translated: fit each equation, "
744
+ "Equation(...).fit(data)")
745
+ raise _left(f"{sysinfo['name']}.{st.word} is not translated: append, sur, 3sls, fiml and tsls are")
746
+
747
+ # -- methods on fitted objects ----------------------------------------------------------------------------------
748
+
749
+ def _fit_method(self, st: Any, key: str) -> tuple[list[Op], str]:
750
+ from .data import _left
751
+
752
+ word = st.word
753
+ if word in ESTIMATORS or word in LEFT_ESTIMATORS:
754
+ return self._estimate(st, word, st.options, st.rest, st.rest_at, st.obj)
755
+ fit = self.fits.get(key)
756
+ kind = self.types.get(key)
757
+ if kind == "var":
758
+ if word == "ls":
759
+ return self._var(st.obj, "ls", st.options, st.rest, st.rest_at)
760
+ if word == "ec":
761
+ return self._vec(st.obj, st.options, st.rest, st.rest_at)
762
+ if fit is None:
763
+ raise _left(f"{st.obj} is not estimated by a line translated so far (a loop, a subroutine or a line left out may "
764
+ "estimate it)" if self.lost else f"{st.obj} is not estimated before this line")
765
+ if fit.kind != "equation":
766
+ if word in ("forecast", "fit") and fit.kind in ("var", "vecm"):
767
+ raise _left(f"{st.obj}.{word}: a VAR's forecast in EViews goes through a model (makemodel); in pymetrix: "
768
+ f"{fit.var}.forecast(data, span)")
769
+ raise _left(f"{st.obj}.{word} is not translated for a {fit.kind}")
770
+ handler = getattr(self, f"_eq_{word}", None)
771
+ if handler is None:
772
+ raise _left(f"{st.obj}.{word} is not translated" + (": testadd (omitted variables) has no pymetrix equivalent, a gap "
773
+ "(docs/known-gaps.md); add the variables and compare the fits, or "
774
+ "eq.test('wald', ...) on the larger equation" if word == "testadd" else ""))
775
+ if fit.kind == "equation" and fit.method == "ardl" and word not in ("forecast", "fit", "makeresids"):
776
+ raise _left(f"{st.obj}.{word} on an ARDL is not translated")
777
+ return handler(st, fit)
778
+
779
+ def _test_step(self, fit: Fit, test: str, what: str, opts: dict[str, Any], args: tuple[Any, ...] = ()) -> Step:
780
+ out, _ = self._name(f"{fit.var}_{what}", f"result {fit.var}_{what}")
781
+ step_args = [Arg("name", test, "pos")]
782
+ if args:
783
+ step_args.append(Arg("args", args, "star"))
784
+ if opts:
785
+ step_args.append(Arg("opts", opts, "varkw"))
786
+ return Step("pymetrix:fitted_equation.test", fit.var, out, f"{fit.var}.test", tuple(step_args))
787
+
788
+ def _restriction(self, text: str, fit: Fit) -> str:
789
+ from .data import _error, _left
790
+
791
+ def coef(m: re.Match[str]) -> str:
792
+ i = int(m.group(2))
793
+ if m.group(1).lower() != fit.vector:
794
+ raise _left(f"{m.group(0)}: only the equation's own coefficients ({fit.vector}) are translated")
795
+ if not 1 <= i <= len(fit.coefs):
796
+ raise _error(f"{m.group(0)}: the equation has {len(fit.coefs)} coefficients")
797
+ return _in_restriction(fit.coefs[i - 1])
798
+
799
+ out = re.sub(r"(?<![\w.])([A-Za-z_]\w*)\s*\(\s*(\d+)\s*\)", coef, text)
800
+ return " ".join(out.split())
801
+
802
+ def _eq_wald(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
803
+ from .data import _error
804
+
805
+ if not st.rest.strip():
806
+ raise _error("wald needs restrictions: eq.wald c(2)=0, c(3)=0")
807
+ restriction = self._restriction(st.rest, fit)
808
+ return [self._test_step(fit, "wald", "wald", {}, (restriction,))], \
809
+ f"EViews's c(i) as pymetrix's coefficients: {restriction}; the statistic is chi-squared, the F form in its details"
810
+
811
+ def _eq_testdrop(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
812
+ from .data import _error, _left
813
+
814
+ names = [w for w, _ in _split_top(st.rest, st.rest_at)]
815
+ if not names:
816
+ raise _error("testdrop names the regressors: eq.testdrop x z")
817
+ page = fit.page
818
+ terms = []
819
+ for w in names:
820
+ t = "const" if w.lower() == "c" else _term_name(str(self.expression(w, st.rest_at, page)))
821
+ if t not in fit.coefs:
822
+ raise _left(f"{w} is not a regressor of {st.obj}")
823
+ terms.append(t)
824
+ restriction = ", ".join(f"{_in_restriction(t)} = 0" for t in terms)
825
+ why = ("the Wald F statistic equals EViews's redundant-variables F under least squares with classic standard errors"
826
+ if fit.classic else "EViews's redundant-variables test refits the equation; with these standard errors or "
827
+ "this estimator the Wald statistic differs from it (verify)")
828
+ return [self._test_step(fit, "wald", "testdrop", {}, (restriction,))], why
829
+
830
+ def _eq_auto(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
831
+ from .data import _left
832
+
833
+ lags = (st.options or st.rest).strip()
834
+ if not re.fullmatch(r"\d+", lags):
835
+ raise _left("auto without its order is not translated: give it (eq.auto(4))")
836
+ return [self._test_step(fit, "breusch_godfrey", "auto", {"lags": int(lags)})], \
837
+ "Breusch-Godfrey: pymetrix gives the LM statistic and the F form; EViews's presample residuals are set to zero, as here (verify)"
838
+
839
+ def _eq_hettest(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
840
+ from .data import _left
841
+
842
+ named, flags = _options(st.options)
843
+ if st.rest.strip():
844
+ raise _left("hettest with its own regressors is not translated: the equation's regressors are")
845
+ kind = named.pop("type", "bpg").lower()
846
+ test = {"bpg": "breusch_pagan", "white": "white"}.get(kind)
847
+ if test is None:
848
+ raise _left(f"hettest(type={kind}) is not translated: bpg and white are")
849
+ if named or flags:
850
+ raise _left(f"hettest's options {', '.join([*named, *flags])} are not translated")
851
+ note = "type=bpg, EViews's default (verify)" if "type" not in (st.options or "") else ""
852
+ if test == "white":
853
+ note = "White's test with cross terms, as pymetrix's (verify EViews's c option for the cross terms)"
854
+ return [self._test_step(fit, test, "hettest", {})], note
855
+
856
+ def _eq_archtest(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
857
+ from .data import _left
858
+
859
+ lags = (st.options or st.rest or "1").strip()
860
+ if not re.fullmatch(r"\d+", lags):
861
+ raise _left(f"archtest({lags}) is not translated: a number of lags is")
862
+ return [self._test_step(fit, "arch", "archtest", {"lags": int(lags)})], ""
863
+
864
+ def _eq_reset(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
865
+ from .data import _left
866
+
867
+ n = (st.options or st.rest or "1").strip()
868
+ if not re.fullmatch(r"\d+", n):
869
+ raise _left(f"reset({n}) is not translated: a number of fitted terms is")
870
+ return [self._test_step(fit, "reset", "reset", {"power": int(n) + 1})], \
871
+ f"EViews's {n} fitted term{'s' if int(n) > 1 else ''} are powers 2 to {int(n) + 1}: power={int(n) + 1}"
872
+
873
+ def _eq_chow(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
874
+ from .data import _left
875
+
876
+ dates = st.rest.split()
877
+ if len(dates) != 1 or st.options:
878
+ raise _left("chow with several dates or options is not translated: one break date is")
879
+ page = fit.page
880
+ at = self._end(dates[0], page, True)
881
+ if at is None:
882
+ raise _left(f"{dates[0]} is not a date read here")
883
+ return [self._test_step(fit, "chow", "chow", {"at": at})], "the breakpoint test (F), the second regime from the date"
884
+
885
+ def _eq_hist(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
886
+ return [self._test_step(fit, "jarque_bera", "hist", {})], "the residuals' histogram view: its Jarque-Bera statistic"
887
+
888
+ def _eq_rls(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
889
+ from .data import _left
890
+
891
+ view = (st.options or "q").strip().lower()
892
+ if view not in ("q", "c", "r"):
893
+ raise _left(f"rls({view}) is not translated: r, c and q (recursive residuals, CUSUM, CUSUM of squares) are")
894
+ out, _ = self._name(f"{fit.var}_rls", f"result {fit.var}_rls")
895
+ return [Code(f"{out} = {fit.var}.recursive_residuals()", (out,))], \
896
+ "recursive residuals with the CUSUM and CUSUM-of-squares paths and their 5% bands (verify the view letters)"
897
+
898
+ def _forecast(self, st: Any, fit: Fit, dynamic: bool) -> tuple[list[Op], str]:
899
+ from pymetrix.commands import AddToDataset
900
+
901
+ from .data import _error, _left
902
+
903
+ named, flags = _options(st.options)
904
+ if named or flags:
905
+ raise _left(f"{st.word}'s options {', '.join([*named, *flags])} are not translated")
906
+ words = st.rest.split()
907
+ if not words or len(words) > 2:
908
+ raise _error(f"{st.word} names the forecast series, and optionally its standard error: eq.{st.word} yf yf_se")
909
+ page = self._page()
910
+ span = self._span(page, st.word)
911
+ out, _ = self._name(f"{fit.var}_{st.word}", f"result {fit.var}_{st.word}")
912
+ fc = Step("pymetrix:fitted_equation.forecast", fit.var, out, f"{fit.var}.forecast",
913
+ (Arg("data", RefTo(page.var), "pos"), Arg("span", span, "pos"), Arg("dynamic", dynamic)))
914
+ ops: list[Op] = [fc]
915
+ for word, column in zip(words, ("forecast", "se")):
916
+ series = self._series_name(word, page)
917
+ ops.append(Cmd(AddToDataset(source=out, item=f"column:{column}", data=page.var, series_name=series, replace=True), (out,)))
918
+ notes = [f"{'dynamic' if dynamic else 'static (one step ahead)'} forecast over the page's sample, {span[0]} to {span[1]}"]
919
+ if fit.dependent and not re.fullmatch(r"[A-Za-z_]\w*", fit.dependent):
920
+ notes.append(f"the left-hand side is {fit.dependent}: EViews forecasts its first series by default; check which "
921
+ "pymetrix's forecast column holds")
922
+ if fit.method == "ardl":
923
+ raise _left("an ARDL's forecast is not translated here")
924
+ if any(m in fit.spec.lower() for m in ("ar(", "ma(")):
925
+ notes.append("with ARMA errors (verify how EViews starts the MA terms)")
926
+ return ops, "; ".join(notes)
927
+
928
+ def _eq_forecast(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
929
+ return self._forecast(st, fit, True)
930
+
931
+ def _eq_fit(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
932
+ return self._forecast(st, fit, False)
933
+
934
+ def _eq_makeresids(self, st: Any, fit: Fit) -> tuple[list[Op], str]:
935
+ from pymetrix.commands import AddToDataset
936
+
937
+ from .data import _error, _left
938
+
939
+ if st.options:
940
+ raise _left(f"makeresids({st.options}): standardized and generalized residuals are not translated")
941
+ words = st.rest.split()
942
+ if len(words) != 1:
943
+ raise _error("makeresids names the series: eq.makeresids r")
944
+ page = fit.page
945
+ series = self._series_name(words[0], page)
946
+ return [Cmd(AddToDataset(source=fit.var, item="resid", data=page.var, series_name=series, replace=True), (fit.var,))], ""
947
+
948
+ def _series_name(self, word: str, page: Any) -> str:
949
+ from ..bundle import _py_name
950
+ from .data import _left
951
+
952
+ if not re.fullmatch(r"[A-Za-z_]\w*", word):
953
+ raise _left(f"{word}: a series name is needed")
954
+ series = _py_name(word)
955
+ self._made_series(page, series)
956
+ return series
957
+
958
+ def _span(self, page: Any, what: str) -> tuple[str, str]:
959
+ from .data import _left
960
+
961
+ sample = page.sample
962
+ if isinstance(sample, Var) or (isinstance(sample, SampleSpec) and sample.where is not None):
963
+ raise _left(f"{what} over a named sample or a sample with a condition is not translated: one with two dates is")
964
+ start = sample.start if isinstance(sample, SampleSpec) and sample.start else page.first
965
+ end = sample.end if isinstance(sample, SampleSpec) and sample.end else page.last
966
+ if start is None or end is None:
967
+ raise _left(f"{what}: the page's first or last period is not known here: set the sample with two dates first")
968
+ return (start, end)
969
+
970
+ # -- tests on series and groups ---------------------------------------------------------------------------------
971
+
972
+ def _uroot(self, st: Any) -> tuple[list[Op], str]:
973
+ from ..bundle import _py_name
974
+ from .data import _error, _left
975
+
976
+ page = self._page()
977
+ series = _py_name(st.obj)
978
+ from .data import _has_series
979
+
980
+ if not _has_series(page, series):
981
+ raise _error(f"{st.obj} is not a series of page {page.eviews}")
982
+ named, flags = _options(st.options)
983
+ tests = {"adf": "adf", "pp": "phillips_perron", "kpss": "kpss", "dfgls": "dfgls", "ers": "ers_point_optimal",
984
+ "np": "ng_perron"}
985
+ chosen = [f for f in flags if f in tests]
986
+ if len(chosen) > 1:
987
+ raise _error("uroot takes one test: adf, pp, kpss, dfgls, ers or np")
988
+ test = tests[chosen[0]] if chosen else "adf"
989
+ opts: dict[str, Any] = {}
990
+ trend = [f for f in flags if f in ("const", "trend", "none")]
991
+ if trend:
992
+ opts["trend"] = {"const": "c", "trend": "ct", "none": "n"}[trend[0]]
993
+ if opts["trend"] == "n" and test not in ("adf", "phillips_perron"):
994
+ raise _left(f"{chosen[0] if chosen else 'adf'} without a constant is not translated: pymetrix's has c or ct")
995
+ if "dif" in named or any(f.startswith("dif") for f in flags):
996
+ raise _left("uroot on differences (dif=) is not translated: make the differenced series first, then test it")
997
+ notes = []
998
+ if test in ("adf", "dfgls"):
999
+ if "lag" in named:
1000
+ opts["lags"] = _value(named.pop("lag"), "lag")
1001
+ else:
1002
+ ic = named.pop("info", "sic").lower()
1003
+ crit = {"aic": "aic", "sic": "bic", "bic": "bic", "tstat": "t-stat"}.get(ic)
1004
+ if crit is None:
1005
+ raise _left(f"uroot(info={ic}) is not translated: aic, sic and tstat are")
1006
+ if test == "adf":
1007
+ opts["lags"] = crit
1008
+ else:
1009
+ opts["method"] = crit
1010
+ notes.append(f"the lags chosen by {ic.upper()}, EViews's default being SIC (verify its default maximum lag)")
1011
+ if "maxlag" in named:
1012
+ opts["max_lags"] = _value(named.pop("maxlag"), "maxlag")
1013
+ elif test in ("ers_point_optimal", "ng_perron"):
1014
+ notes.append("the long-run variance by the modified AIC autoregression (verify EViews's spectral estimator, hac=)")
1015
+ else:
1016
+ notes.append("the long-run variance's bandwidth: EViews's default Newey-West bandwidth may differ (verify band=)")
1017
+ used = {"lag", "info", "maxlag"}
1018
+ rest = [k for k in named if k not in used] + [f for f in flags if f not in tests and f not in ("const", "trend", "none")]
1019
+ if rest:
1020
+ raise _left(f"uroot's options {', '.join(rest)} are not translated")
1021
+ out, _ = self._name(f"{series}_uroot", f"result {series}_uroot")
1022
+ step = Step("pymetrix:dataset.test", page.var, out, f"{page.var}.test",
1023
+ (Arg("name", test, "pos"), Arg("args", (series,), "star"), *( [Arg("opts", opts, "varkw")] if opts else [])))
1024
+ return [step], "; ".join(notes)
1025
+
1026
+ def _coint(self, st: Any, group: Any) -> tuple[list[Op], str]:
1027
+ from .data import _left
1028
+
1029
+ page = self._page()
1030
+ parts = _commas(st.options)
1031
+ named = [p for p in parts if "=" in p]
1032
+ if named:
1033
+ raise _left(f"coint's options {', '.join(named)} are not translated: the Johansen test with a case letter and lags is")
1034
+ case = parts[0].lower() if parts and not parts[0].isdigit() else "c"
1035
+ lags_text = [p for p in parts if p.isdigit()]
1036
+ words = st.rest.split()
1037
+ if len(words) == 2 and words[0] == "1" and words[1].isdigit():
1038
+ lags = int(words[1])
1039
+ elif not words and lags_text:
1040
+ lags = int(lags_text[-1])
1041
+ elif not words and not lags_text:
1042
+ lags = 1
1043
+ else:
1044
+ raise _left("coint's lags other than one range from 1 (1 4) are not translated")
1045
+ det = {"a": -1, "c": 0}.get(case)
1046
+ if det is None:
1047
+ raise _left(f"coint({case}): EViews's case {case} is not translated: a (no deterministic terms) and c (a constant "
1048
+ "outside the relations) are, as data.johansen's det_order -1 and 0")
1049
+ out, _ = self._name(f"{group.name}_coint", f"result {group.name}_coint")
1050
+ step = Step("pymetrix:dataset.johansen", page.var, out, f"{page.var}.johansen",
1051
+ (Arg("variables", tuple(group.members), "pos"), Arg("lags", lags), *([Arg("det_order", det)] if det else [])))
1052
+ return [step], (f"Johansen's trace and maximum-eigenvalue tests, {lags} lagged differences (EViews's lags 1 {lags} "
1053
+ "are in differences: verify); case " + case)
1054
+
1055
+ # -- values read from results -------------------------------------------------------------------------------------
1056
+
1057
+ _MEMBERS = {"@r2": "r2", "@rbar2": "r2_adj", "@se": "se_regression", "@ssr": "ssr", "@dw": "durbin_watson",
1058
+ "@regobs": "nobs", "@logl": "loglike"}
1059
+ _CRITERIA = {"@aic": "aic", "@schwarz": "bic", "@sc": "bic", "@hq": "hq"}
1060
+
1061
+ def member_code(self, obj: str, member: str, index: int | None) -> tuple[str, str]:
1062
+ """Python for an equation's data member (``eq.@coefs(2)``) and a note, or left out."""
1063
+ from .data import _error, _left
1064
+
1065
+ fit = self.fits.get(obj.lower())
1066
+ if fit is None:
1067
+ raise _left(f"{obj} is not estimated by a line translated so far" if self.lost or obj.lower() in self.types
1068
+ else f"{obj} is not an object of the program")
1069
+ if fit.kind not in ("equation", "system") or fit.method == "ardl":
1070
+ raise _left(f"{obj}.{member} is translated for equations")
1071
+ v = fit.var
1072
+ if member in ("@coefs", "@stderrs", "@tstats"):
1073
+ if index is None:
1074
+ raise _left(f"{member} without an index (the whole vector) is not translated: {v}.params")
1075
+ if not 1 <= index <= len(fit.coefs):
1076
+ raise _error(f"{obj} has {len(fit.coefs)} coefficients, not {index}")
1077
+ name = quote(fit.coefs[index - 1])
1078
+ coef = f"{v}.params[{name}]"
1079
+ se = f"{v}.params.se[{v}.params.names.index({name})]"
1080
+ return {"@coefs": coef, "@stderrs": se, "@tstats": f"{coef} / {se}"}[member], ""
1081
+ if member in self._MEMBERS:
1082
+ return f"{v}.stats[{quote(self._MEMBERS[member])}]", ""
1083
+ if member == "@ncoef":
1084
+ return f"len({v}.params)", ""
1085
+ if member in self._CRITERIA:
1086
+ return (f"{v}.stats[{quote(self._CRITERIA[member])}] / {v}.stats[\"nobs\"]",
1087
+ f"{member} per observation, as EViews reports it: pymetrix's criteria are totals (docs/design/definitions.md)")
1088
+ raise _left(f"{obj}.{member} is not translated: @coefs, @stderrs, @tstats, @r2, @rbar2, @se, @ssr, @dw, @regobs, @logl, "
1089
+ "@ncoef, @aic, @schwarz and @hq are")
1090
+
1091
+ def members_in(self, text: str) -> tuple[str, dict[str, str], list[str]]:
1092
+ """``text`` with each result's value (``eq.@coefs(2)``, ``eq.@r2``, ``c(2)`` after an estimation) as a placeholder
1093
+ name, the Python for each placeholder, and the notes."""
1094
+ from .data import _left
1095
+
1096
+ codes: dict[str, str] = {}
1097
+ notes: list[str] = []
1098
+
1099
+ def member(m: re.Match[str]) -> str:
1100
+ code, note = self.member_code(m.group(1), m.group(2).lower(), int(m.group(3)) if m.group(3) else None)
1101
+ key = f"pmxv{len(codes)}"
1102
+ codes[key] = code
1103
+ if note and note not in notes:
1104
+ notes.append(note)
1105
+ return key
1106
+
1107
+ out = re.sub(r"(?<![\w.])([A-Za-z_]\w*)\.(@\w+)(?:\(\s*(\d+)\s*\))?", member, text)
1108
+
1109
+ def coefficient(m: re.Match[str]) -> str:
1110
+ if m.group(1).lower() != "c":
1111
+ return m.group(0)
1112
+ fit = self.last_fit
1113
+ if fit is None:
1114
+ raise _left(f"{m.group(0)}: no estimation translated so far fills c" + (" (a line left out may)" if self.lost else ""))
1115
+ i = int(m.group(2))
1116
+ if not 1 <= i <= len(fit.coefs):
1117
+ raise _left(f"{m.group(0)}: the last estimation ({fit.var}) has {len(fit.coefs)} coefficients")
1118
+ key = f"pmxv{len(codes)}"
1119
+ codes[key] = f"{fit.var}.params[{quote(fit.coefs[i - 1])}]"
1120
+ note = f"c holds the last estimation's coefficients, {fit.var}'s, as in EViews"
1121
+ if note not in notes:
1122
+ notes.append(note)
1123
+ return key
1124
+
1125
+ if codes or re.search(r"(?<![\w.])c\s*\(\s*\d+\s*\)", out, re.I):
1126
+ out = re.sub(r"(?<![\w.@])([A-Za-z_]\w*)\s*\(\s*(\d+)\s*\)", coefficient, out)
1127
+ return out, codes, notes
1128
+
1129
+
1130
+ def _order(lags: list[int]) -> Any:
1131
+ """ARMA lags as ARMA's argument: the order when they are 1 to n, else the lags."""
1132
+ lags = sorted(set(lags))
1133
+ return lags[-1] if lags == list(range(1, lags[-1] + 1)) else tuple(lags)