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.
- pymetrix_eviews/__init__.py +83 -0
- pymetrix_eviews/_version.py +1 -0
- pymetrix_eviews/app.py +374 -0
- pymetrix_eviews/bundle-1.schema.json +104 -0
- pymetrix_eviews/bundle.py +889 -0
- pymetrix_eviews/dates.py +196 -0
- pymetrix_eviews/export/pymetrix_export.prg +476 -0
- pymetrix_eviews/panel.py +326 -0
- pymetrix_eviews/program/__init__.py +292 -0
- pymetrix_eviews/program/control.py +1368 -0
- pymetrix_eviews/program/data.py +1479 -0
- pymetrix_eviews/program/estimation.py +1133 -0
- pymetrix_eviews/program/ir.py +395 -0
- pymetrix_eviews/program/left.py +89 -0
- pymetrix_eviews/program/models.py +462 -0
- pymetrix_eviews/program/parse.py +124 -0
- pymetrix_eviews/program/report.py +155 -0
- pymetrix_eviews/program/script.py +258 -0
- pymetrix_eviews/program/steps.py +234 -0
- pymetrix_eviews-0.1.0a1.dist-info/METADATA +248 -0
- pymetrix_eviews-0.1.0a1.dist-info/RECORD +24 -0
- pymetrix_eviews-0.1.0a1.dist-info/WHEEL +4 -0
- pymetrix_eviews-0.1.0a1.dist-info/entry_points.txt +8 -0
- pymetrix_eviews-0.1.0a1.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1,889 @@
|
|
|
1
|
+
"""EViews workfile bundles (format version 1): what ``pymetrix_export.prg`` writes, read into pymetrix.
|
|
2
|
+
|
|
3
|
+
A bundle is a folder with a JSON manifest (``<workfile>.evbundle``) and the files it names: each page's series as
|
|
4
|
+
CSV, long texts, small CSV files for vectors, matrices, value maps and each equation's estimates. The manifest's
|
|
5
|
+
schema ships with the plugin (``bundle_schema()``); docs/design/eviews-plugin.md, section 1, is the format's
|
|
6
|
+
description and this module follows it.
|
|
7
|
+
|
|
8
|
+
quarterly = Dataset.read("C:/work/macro-export/macro.evbundle", page="quarterly") # through pymetrix.io
|
|
9
|
+
pages = bundle_pages("C:/work/macro-export/macro.evbundle") # what the bundle holds
|
|
10
|
+
objects = eviews_objects(quarterly) # its groups, samples, scalars, strings, matrices and models
|
|
11
|
+
compare_estimates(quarterly) # each least-squares equation refitted, against EViews's estimates
|
|
12
|
+
|
|
13
|
+
What does not read is refused at its place (the file, line and column, or the manifest's key), never misread: a
|
|
14
|
+
folder without its manifest (an incomplete export), a newer ``format_version``, a CSV without a column the manifest
|
|
15
|
+
lists, a value that is not a number, a date that does not start a period of the page's frequency, and frequencies
|
|
16
|
+
pandas has no period for (semi-annual, multi-year, intraday, bimonthly, fortnightly, ten-day: read such a page with
|
|
17
|
+
``undated=True``). Within version 1 changes are additive: keys this reader does not know are kept in
|
|
18
|
+
``meta.extra["eviews"]["unknown"]`` with a note. Files are read as UTF-8; one that is not falls back to Windows-1252,
|
|
19
|
+
with a note.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
from __future__ import annotations
|
|
23
|
+
|
|
24
|
+
import csv
|
|
25
|
+
import io
|
|
26
|
+
import json
|
|
27
|
+
import keyword
|
|
28
|
+
import math
|
|
29
|
+
import re
|
|
30
|
+
import warnings
|
|
31
|
+
from collections.abc import Mapping
|
|
32
|
+
from dataclasses import dataclass, field
|
|
33
|
+
from datetime import date, datetime
|
|
34
|
+
from pathlib import Path
|
|
35
|
+
from typing import Any
|
|
36
|
+
|
|
37
|
+
from pymetrix.errors import DataError, NotFoundError
|
|
38
|
+
|
|
39
|
+
__all__ = ["FORMAT", "FORMAT_VERSIONS", "PROGRAM_VERSION", "SUFFIX", "EViewsBundleNote", "bundle_model", "bundle_pages",
|
|
40
|
+
"bundle_schema", "compare_estimates", "eviews_objects", "eviews_sample", "export_program", "read_bundle",
|
|
41
|
+
"save_export_program"]
|
|
42
|
+
|
|
43
|
+
FORMAT = "pymetrix-eviews-bundle"
|
|
44
|
+
FORMAT_VERSIONS = (1,) # the versions this reader reads; a newer one is refused with "update pymetrix-eviews"
|
|
45
|
+
PROGRAM_VERSION = "1.0" # the version of the export program this plugin ships (export/pymetrix_export.prg)
|
|
46
|
+
SUFFIX = ".evbundle"
|
|
47
|
+
|
|
48
|
+
_HERE = Path(__file__).resolve().parent
|
|
49
|
+
|
|
50
|
+
# EViews's frequency codes as pandas period frequencies. Weekly takes its anchor from the dates (W-SUN: weeks from
|
|
51
|
+
# Monday to Sunday); the others pandas has no period for are refused with the reason (_refused_frequency).
|
|
52
|
+
_FREQ = {"A": "Y", "Y": "Y", "Q": "Q", "M": "M", "D5": "B", "5": "B", "D7": "D", "7": "D"}
|
|
53
|
+
_WEEKDAYS = ("MON", "TUE", "WED", "THU", "FRI", "SAT", "SUN")
|
|
54
|
+
_NUMBER = re.compile(r"^[+-]?(\d+\.?\d*|\.\d+)([eE][+-]?\d+)?$")
|
|
55
|
+
|
|
56
|
+
_KNOWN = {
|
|
57
|
+
"": {"format", "format_version", "exporter", "workfile", "na", "pages"},
|
|
58
|
+
"exporter": {"program_version", "eviews_version", "exported"},
|
|
59
|
+
"workfile": {"name", "path", "active_page"},
|
|
60
|
+
"page": {"name", "structure", "frequency", "range", "sample", "file", "date_column", "id_columns", "series", "groups",
|
|
61
|
+
"samples", "scalars", "strings", "arrays", "value_maps", "equations", "models", "skipped"},
|
|
62
|
+
"series": {"name", "kind", "display_name", "description", "units", "source", "remarks", "attributes", "value_map"},
|
|
63
|
+
"groups": {"name", "members"},
|
|
64
|
+
"samples": {"name", "text"},
|
|
65
|
+
"scalars": {"name", "value"},
|
|
66
|
+
"strings": {"name", "value"},
|
|
67
|
+
"arrays": {"name", "type", "rows", "cols", "file"},
|
|
68
|
+
"value_maps": {"name", "file"},
|
|
69
|
+
"equations": {"name", "command", "command_file", "method", "sample", "ncoef", "estimates"},
|
|
70
|
+
"models": {"name", "text"},
|
|
71
|
+
"skipped": {"name", "type", "reason"},
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
class EViewsBundleNote(UserWarning):
|
|
76
|
+
"""Something about a bundle the user should know, which did not stop it being read: a file that was not UTF-8, a
|
|
77
|
+
bundle from an older export program, keys this reader does not know, names changed to be valid Python names."""
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
# -- the files -----------------------------------------------------------------------------------------------------
|
|
81
|
+
|
|
82
|
+
|
|
83
|
+
def _manifest_path(source: str | Path) -> Path:
|
|
84
|
+
path = Path(source)
|
|
85
|
+
if path.is_dir():
|
|
86
|
+
found = sorted(path.glob(f"*{SUFFIX}"))
|
|
87
|
+
if not found:
|
|
88
|
+
raise DataError(f"{path} has no manifest (*{SUFFIX}): the export did not finish (the program writes the "
|
|
89
|
+
"manifest last), or this is not a bundle")
|
|
90
|
+
if len(found) > 1:
|
|
91
|
+
raise DataError(f"{path} has several manifests ({', '.join(p.name for p in found)}): open one of them")
|
|
92
|
+
return found[0]
|
|
93
|
+
if not path.is_file():
|
|
94
|
+
raise DataError(f"no manifest {path}: a folder without its {SUFFIX} file is an incomplete export, which is "
|
|
95
|
+
"refused (run the export program again)")
|
|
96
|
+
return path
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def _decode(raw: bytes, where: str, notes: list[str]) -> str:
|
|
100
|
+
try:
|
|
101
|
+
return raw.decode("utf-8-sig")
|
|
102
|
+
except UnicodeDecodeError as exc:
|
|
103
|
+
notes.append(f"{where} is not UTF-8 (byte {exc.start + 1}): read as Windows-1252")
|
|
104
|
+
return raw.decode("cp1252", errors="replace")
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
@dataclass
|
|
108
|
+
class _Bundle:
|
|
109
|
+
manifest_path: Path
|
|
110
|
+
manifest: dict[str, Any]
|
|
111
|
+
notes: list[str] = field(default_factory=list)
|
|
112
|
+
unknown: dict[str, Any] = field(default_factory=dict)
|
|
113
|
+
|
|
114
|
+
@property
|
|
115
|
+
def root(self) -> Path:
|
|
116
|
+
return self.manifest_path.parent
|
|
117
|
+
|
|
118
|
+
def file(self, relative: Any, where: str) -> Path:
|
|
119
|
+
"""A file the manifest names, inside the bundle's folder."""
|
|
120
|
+
text = str(relative).replace("\\", "/")
|
|
121
|
+
parts = text.split("/")
|
|
122
|
+
if text.startswith("/") or re.match(r"^[A-Za-z]:", text) or ".." in parts:
|
|
123
|
+
raise DataError(f"{self.manifest_path.name}: {where} = {relative!r}: files must be inside the bundle's folder")
|
|
124
|
+
path = self.root.joinpath(*parts)
|
|
125
|
+
if not path.is_file():
|
|
126
|
+
raise DataError(f"{self.manifest_path.name}: {where} names {text}, which is not in the bundle ({self.root})")
|
|
127
|
+
return path
|
|
128
|
+
|
|
129
|
+
def text(self, relative: Any, where: str) -> tuple[str, str]:
|
|
130
|
+
path = self.file(relative, where)
|
|
131
|
+
name = str(relative).replace("\\", "/")
|
|
132
|
+
return _decode(path.read_bytes(), name, self.notes), name
|
|
133
|
+
|
|
134
|
+
@property
|
|
135
|
+
def na(self) -> str:
|
|
136
|
+
return str(self.manifest.get("na", "NA"))
|
|
137
|
+
|
|
138
|
+
def page(self, name: str | None) -> tuple[int, dict[str, Any]]:
|
|
139
|
+
pages = self.manifest["pages"]
|
|
140
|
+
names = [str(p["name"]) for p in pages]
|
|
141
|
+
if name is None:
|
|
142
|
+
if len(pages) == 1:
|
|
143
|
+
return 0, pages[0]
|
|
144
|
+
raise DataError(f"{self.manifest_path.name} has {len(pages)} pages ({', '.join(names)}): give page=")
|
|
145
|
+
for i, p in enumerate(pages):
|
|
146
|
+
if str(p["name"]).lower() == str(name).lower():
|
|
147
|
+
return i, p
|
|
148
|
+
raise NotFoundError(f"{self.manifest_path.name} has no page {name!r}; its pages: {', '.join(names)}")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _open(source: str | Path) -> _Bundle:
|
|
152
|
+
path = _manifest_path(source)
|
|
153
|
+
notes: list[str] = []
|
|
154
|
+
text = _decode(path.read_bytes(), path.name, notes)
|
|
155
|
+
manifest = _load_json(text, path.name)
|
|
156
|
+
bundle = _Bundle(path, manifest, notes)
|
|
157
|
+
_check_manifest(bundle)
|
|
158
|
+
return bundle
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def _load_json(text: str, where: str) -> Any:
|
|
162
|
+
"""Strict JSON: no NaN or Infinity, no key twice in an object; an error says its line and column."""
|
|
163
|
+
|
|
164
|
+
def pairs(items: list[tuple[str, Any]]) -> dict[str, Any]:
|
|
165
|
+
out: dict[str, Any] = {}
|
|
166
|
+
for key, value in items:
|
|
167
|
+
if key in out:
|
|
168
|
+
raise DataError(f"{where}: the key {key!r} is given twice in one object")
|
|
169
|
+
out[key] = value
|
|
170
|
+
return out
|
|
171
|
+
|
|
172
|
+
def constant(name: str) -> Any:
|
|
173
|
+
raise DataError(f"{where}: {name} is not JSON (a missing number is null)")
|
|
174
|
+
|
|
175
|
+
try:
|
|
176
|
+
return json.loads(text, object_pairs_hook=pairs, parse_constant=constant)
|
|
177
|
+
except json.JSONDecodeError as exc:
|
|
178
|
+
raise DataError(f"{where}, line {exc.lineno}, column {exc.colno}: not valid JSON ({exc.msg})") from None
|
|
179
|
+
|
|
180
|
+
|
|
181
|
+
# -- the manifest's checks -----------------------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _need(obj: Mapping[str, Any], key: str, kind: type | tuple[type, ...], where: str, bundle: _Bundle) -> Any:
|
|
185
|
+
if key not in obj:
|
|
186
|
+
raise DataError(f"{bundle.manifest_path.name}: {where} has no {key!r}")
|
|
187
|
+
value = obj[key]
|
|
188
|
+
if not isinstance(value, kind) or (isinstance(value, bool) and bool not in (kind if isinstance(kind, tuple) else (kind,))):
|
|
189
|
+
raise DataError(f"{bundle.manifest_path.name}: {where}.{key} should be {_kind(kind)}, not {type(value).__name__}")
|
|
190
|
+
return value
|
|
191
|
+
|
|
192
|
+
|
|
193
|
+
def _kind(kind: type | tuple[type, ...]) -> str:
|
|
194
|
+
names = {str: "text", int: "a whole number", float: "a number", list: "a list", dict: "an object", type(None): "null"}
|
|
195
|
+
kinds = kind if isinstance(kind, tuple) else (kind,)
|
|
196
|
+
if float in kinds: # a whole number is a number
|
|
197
|
+
kinds = tuple(k for k in kinds if k is not int)
|
|
198
|
+
return " or ".join(names.get(k, k.__name__) for k in kinds)
|
|
199
|
+
|
|
200
|
+
|
|
201
|
+
def _unknown(obj: Mapping[str, Any], known: str, where: str, bundle: _Bundle) -> None:
|
|
202
|
+
for key in obj:
|
|
203
|
+
if key not in _KNOWN[known]:
|
|
204
|
+
bundle.unknown[f"{where}.{key}" if where else key] = obj[key]
|
|
205
|
+
|
|
206
|
+
|
|
207
|
+
def _check_manifest(b: _Bundle) -> None:
|
|
208
|
+
m = b.manifest
|
|
209
|
+
name = b.manifest_path.name
|
|
210
|
+
if not isinstance(m, dict):
|
|
211
|
+
raise DataError(f"{name}: the manifest should be a JSON object")
|
|
212
|
+
if m.get("format") != FORMAT:
|
|
213
|
+
raise DataError(f"{name}: not a pymetrix EViews bundle (its \"format\" is {m.get('format')!r}, not {FORMAT!r})")
|
|
214
|
+
version = _need(m, "format_version", int, "the manifest", b)
|
|
215
|
+
if version > max(FORMAT_VERSIONS):
|
|
216
|
+
raise DataError(f"{name}: format_version {version} is newer than this pymetrix-eviews reads "
|
|
217
|
+
f"({', '.join(map(str, FORMAT_VERSIONS))}): update pymetrix-eviews (pip install -U pymetrix-eviews)")
|
|
218
|
+
if version not in FORMAT_VERSIONS:
|
|
219
|
+
raise DataError(f"{name}: format_version {version} is not one this reader knows ({', '.join(map(str, FORMAT_VERSIONS))})")
|
|
220
|
+
_unknown(m, "", "", b)
|
|
221
|
+
exporter = _need(m, "exporter", dict, "the manifest", b)
|
|
222
|
+
program = str(_need(exporter, "program_version", str, "exporter", b))
|
|
223
|
+
_unknown(exporter, "exporter", "exporter", b)
|
|
224
|
+
if _version_tuple(program) < _version_tuple(PROGRAM_VERSION):
|
|
225
|
+
b.notes.append(f"the bundle was written by export program {program}; this plugin ships {PROGRAM_VERSION} "
|
|
226
|
+
"(Get the export program): export again with it for what it adds")
|
|
227
|
+
workfile = _need(m, "workfile", dict, "the manifest", b)
|
|
228
|
+
_need(workfile, "name", str, "workfile", b)
|
|
229
|
+
_unknown(workfile, "workfile", "workfile", b)
|
|
230
|
+
if "na" in m:
|
|
231
|
+
_need(m, "na", str, "the manifest", b)
|
|
232
|
+
pages = _need(m, "pages", list, "the manifest", b)
|
|
233
|
+
if not pages:
|
|
234
|
+
raise DataError(f"{name}: the bundle has no pages")
|
|
235
|
+
seen: set[str] = set()
|
|
236
|
+
for i, page in enumerate(pages):
|
|
237
|
+
where = f"pages[{i}]"
|
|
238
|
+
if not isinstance(page, dict):
|
|
239
|
+
raise DataError(f"{name}: {where} should be an object")
|
|
240
|
+
pname = _need(page, "name", str, where, b)
|
|
241
|
+
if pname.lower() in seen:
|
|
242
|
+
raise DataError(f"{name}: {where}: a second page called {pname!r}")
|
|
243
|
+
seen.add(pname.lower())
|
|
244
|
+
structure = _need(page, "structure", str, where, b)
|
|
245
|
+
if structure not in ("dated", "undated", "panel"):
|
|
246
|
+
raise DataError(f"{name}: {where}.structure is {structure!r}: dated, undated or panel")
|
|
247
|
+
_need(page, "file", str, where, b)
|
|
248
|
+
if structure in ("dated", "panel"):
|
|
249
|
+
_need(page, "frequency", str, where, b)
|
|
250
|
+
_need(page, "date_column", str, where, b)
|
|
251
|
+
if structure == "panel" and not _need(page, "id_columns", list, where, b):
|
|
252
|
+
raise DataError(f"{name}: {where}.id_columns: a panel page names its cross-section id column")
|
|
253
|
+
_unknown(page, "page", where, b)
|
|
254
|
+
series = _need(page, "series", list, where, b)
|
|
255
|
+
for j, s in enumerate(series):
|
|
256
|
+
sw = f"{where}.series[{j}]"
|
|
257
|
+
if not isinstance(s, dict):
|
|
258
|
+
raise DataError(f"{name}: {sw} should be an object")
|
|
259
|
+
_need(s, "name", str, sw, b)
|
|
260
|
+
kind = _need(s, "kind", str, sw, b)
|
|
261
|
+
if kind not in ("numeric", "alpha"):
|
|
262
|
+
raise DataError(f"{name}: {sw}.kind is {kind!r}: numeric or alpha")
|
|
263
|
+
for key in ("display_name", "description", "units", "source", "remarks"):
|
|
264
|
+
if key in s:
|
|
265
|
+
_need(s, key, str, sw, b)
|
|
266
|
+
if "attributes" in s:
|
|
267
|
+
attrs = _need(s, "attributes", dict, sw, b)
|
|
268
|
+
bad = [k for k, v in attrs.items() if not isinstance(v, str)]
|
|
269
|
+
if bad:
|
|
270
|
+
raise DataError(f"{name}: {sw}.attributes.{bad[0]} should be text")
|
|
271
|
+
if s.get("value_map") is not None:
|
|
272
|
+
_need(s, "value_map", str, sw, b)
|
|
273
|
+
_unknown(s, "series", sw, b)
|
|
274
|
+
for key, required in (("groups", {"name": str, "members": list}), ("samples", {"name": str, "text": str}),
|
|
275
|
+
("scalars", {"name": str, "value": (int, float, type(None))}), ("strings", {"name": str, "value": str}),
|
|
276
|
+
("arrays", {"name": str, "type": str, "rows": int, "cols": int, "file": str}),
|
|
277
|
+
("value_maps", {"name": str, "file": str}), ("equations", {"name": str, "method": str}),
|
|
278
|
+
("models", {"name": str, "text": str}), ("skipped", {"name": str, "type": str})):
|
|
279
|
+
for j, item in enumerate(_need(page, key, list, where, b) if key in page else []):
|
|
280
|
+
iw = f"{where}.{key}[{j}]"
|
|
281
|
+
if not isinstance(item, dict):
|
|
282
|
+
raise DataError(f"{name}: {iw} should be an object")
|
|
283
|
+
for k, kind in required.items():
|
|
284
|
+
_need(item, k, kind, iw, b)
|
|
285
|
+
if key == "equations" and "command" not in item and "command_file" not in item:
|
|
286
|
+
raise DataError(f"{name}: {iw} has no 'command' (or 'command_file')")
|
|
287
|
+
_unknown(item, key, iw, b)
|
|
288
|
+
if b.unknown:
|
|
289
|
+
b.notes.append(f"keys this reader does not know, kept in meta['eviews']['unknown']: {', '.join(sorted(b.unknown))}")
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
def _version_tuple(text: str) -> tuple[int, ...]:
|
|
293
|
+
return tuple(int(p) for p in re.findall(r"\d+", text)) or (0,)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
# -- frequencies and names -----------------------------------------------------------------------------------------
|
|
297
|
+
|
|
298
|
+
|
|
299
|
+
def _refused_frequency(code: str) -> str | None:
|
|
300
|
+
"""Why pymetrix cannot give a page of this EViews frequency a time axis (None when it can)."""
|
|
301
|
+
c = code.strip().upper()
|
|
302
|
+
if c in _FREQ or c == "W":
|
|
303
|
+
return None
|
|
304
|
+
if c in ("S", "SA"):
|
|
305
|
+
return "semi-annual: pandas has no half-year period (a known gap)"
|
|
306
|
+
if re.fullmatch(r"\d+A|\d+Y", c):
|
|
307
|
+
return "multi-year: pandas has no period of several years"
|
|
308
|
+
if re.match(r"^\d*(H|MIN|SEC)", c) or c.endswith(("H", "MIN", "SEC")):
|
|
309
|
+
return "intraday: pymetrix reads periods of a day or longer"
|
|
310
|
+
return {"BM": "bimonthly: pandas has no two-month period", "F": "fortnightly: pandas has no two-week period",
|
|
311
|
+
"T": "ten-day: pandas has no ten-day period",
|
|
312
|
+
"D": "daily with a custom week: give the page five-day (D5) or seven-day (D7) dates in EViews"}.get(
|
|
313
|
+
c, f"{code!r} is not a frequency this reader knows")
|
|
314
|
+
|
|
315
|
+
|
|
316
|
+
def _py_name(text: str) -> str:
|
|
317
|
+
"""A name pymetrix can use as a series or object: lower case, letters, digits and _, not a Python keyword."""
|
|
318
|
+
name = re.sub(r"\W+", "_", str(text).strip().lower()).strip("_") or "x"
|
|
319
|
+
if name[0].isdigit():
|
|
320
|
+
name = f"x_{name}"
|
|
321
|
+
if keyword.iskeyword(name) or keyword.issoftkeyword(name):
|
|
322
|
+
name = f"{name}_v"
|
|
323
|
+
return name
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _axis_name(column: str) -> str:
|
|
327
|
+
"""An id or date column as an axis name: pmx_crossid -> crossid (the export program's own columns)."""
|
|
328
|
+
name = _py_name(column)
|
|
329
|
+
return name[4:] if name.startswith("pmx_") and len(name) > 4 else name
|
|
330
|
+
|
|
331
|
+
|
|
332
|
+
# -- reading a page ------------------------------------------------------------------------------------------------
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
def read_bundle(source: str | Path, page: str | None = None, undated: bool = False) -> Any:
|
|
336
|
+
"""One page of an EViews bundle as a Dataset (``Dataset.read(path, page=...)`` comes here for ``.evbundle``).
|
|
337
|
+
|
|
338
|
+
``page`` is the page's name, as in EViews (any case); it may be left out when the bundle has one page.
|
|
339
|
+
``undated=True`` reads a dated page as undated (rows numbered from 1, the dates kept as the text series
|
|
340
|
+
``date``): for frequencies pandas has no period for, such as semi-annual.
|
|
341
|
+
|
|
342
|
+
Each series keeps its EViews metadata: the label (the display name, else the description), description, units
|
|
343
|
+
and source; the remarks, attributes, value map and EViews's own name, when changed, in ``Variable.extra``.
|
|
344
|
+
``meta.extra["eviews"]`` keeps the rest of the page: its frequency, range and sample, the groups, samples,
|
|
345
|
+
scalars, strings, matrices, equations (with EViews's estimates) and models, the objects the program skipped, and
|
|
346
|
+
the notes on the reading. ``eviews_objects(data)`` turns them into pymetrix objects."""
|
|
347
|
+
import pandas as pd
|
|
348
|
+
|
|
349
|
+
from pymetrix.data import Dataset
|
|
350
|
+
from pymetrix.metadata import DatasetMeta, Variable
|
|
351
|
+
|
|
352
|
+
b = _open(source)
|
|
353
|
+
index, p = b.page(page)
|
|
354
|
+
where = f"pages[{index}]"
|
|
355
|
+
notes = b.notes
|
|
356
|
+
structure = p["structure"]
|
|
357
|
+
if undated and structure == "panel":
|
|
358
|
+
raise DataError(f"{b.manifest_path.name}: page {p['name']!r} is a panel: it cannot be read as undated")
|
|
359
|
+
text, file = b.text(p["file"], f"{where}.file")
|
|
360
|
+
header, rows, lines = _csv(text, file)
|
|
361
|
+
column = {h.strip().lower(): k for k, h in enumerate(header)}
|
|
362
|
+
if len(column) < len(header):
|
|
363
|
+
raise DataError(f"{file}, line 1: a column name is given twice (names are read in any case)")
|
|
364
|
+
|
|
365
|
+
def col(name: str, what: str) -> int:
|
|
366
|
+
k = column.get(str(name).strip().lower())
|
|
367
|
+
if k is None:
|
|
368
|
+
raise DataError(f"{file}: no column {name!r} ({what}); the file has {', '.join(header) or 'no columns'}")
|
|
369
|
+
return k
|
|
370
|
+
|
|
371
|
+
freq_code = str(p.get("frequency") or "")
|
|
372
|
+
date_column = p.get("date_column") or None
|
|
373
|
+
id_columns = list(p.get("id_columns") or [])
|
|
374
|
+
used = set()
|
|
375
|
+
data: dict[str, Any] = {}
|
|
376
|
+
axes: list[str] = []
|
|
377
|
+
frame_freq = None
|
|
378
|
+
pd_freq = None
|
|
379
|
+
if structure in ("dated", "panel") and not undated:
|
|
380
|
+
why = _refused_frequency(freq_code)
|
|
381
|
+
if why is not None:
|
|
382
|
+
raise DataError(f"{b.manifest_path.name}: {where} ({p['name']}) has frequency {freq_code!r}, {why}; read the "
|
|
383
|
+
"page as undated (Dataset.read(path, page=..., undated=True))")
|
|
384
|
+
k = col(date_column, f"{where}.date_column")
|
|
385
|
+
used.add(k)
|
|
386
|
+
dates = [_iso_date(r[k], file, lines[i], header[k]) for i, r in enumerate(rows)]
|
|
387
|
+
pd_freq = _pandas_freq(freq_code, dates, file)
|
|
388
|
+
periods = [pd.Period(d, freq=pd_freq) for d in dates]
|
|
389
|
+
for d, per, line in zip(dates, periods, lines):
|
|
390
|
+
if per.start_time.date() != d:
|
|
391
|
+
raise DataError(f"{file}, line {line}, column {header[k]}: {d.isoformat()} is not the first day of a "
|
|
392
|
+
f"{freq_code} period (it falls in {per}): is the page's frequency right?")
|
|
393
|
+
data["time"] = pd.PeriodIndex(periods, freq=pd_freq)
|
|
394
|
+
axes.append("time")
|
|
395
|
+
frame_freq = pd_freq
|
|
396
|
+
elif structure in ("dated", "panel") and undated:
|
|
397
|
+
k = col(date_column, f"{where}.date_column")
|
|
398
|
+
used.add(k)
|
|
399
|
+
data["obs"] = list(range(1, len(rows) + 1))
|
|
400
|
+
axes.append("obs")
|
|
401
|
+
dates_text = pd.array([r[k] or None for r in rows], dtype="string")
|
|
402
|
+
notes.append(f"page {p['name']} ({freq_code}) read as undated: rows numbered from 1, its dates in the text series date")
|
|
403
|
+
if structure == "panel" and not undated:
|
|
404
|
+
for name in id_columns:
|
|
405
|
+
k = col(name, f"{where}.id_columns")
|
|
406
|
+
used.add(k)
|
|
407
|
+
values = [r[k] for r in rows]
|
|
408
|
+
data[_axis_name(name)] = [int(v) for v in values] if all(re.fullmatch(r"[+-]?\d+", v) for v in values) else values
|
|
409
|
+
axes.append(_axis_name(name))
|
|
410
|
+
if structure == "undated":
|
|
411
|
+
names = id_columns or (["obs"] if "obs" in column else [])
|
|
412
|
+
if names:
|
|
413
|
+
for name in names:
|
|
414
|
+
k = col(name, f"{where}.id_columns")
|
|
415
|
+
used.add(k)
|
|
416
|
+
values = [r[k] for r in rows]
|
|
417
|
+
data[_axis_name(name)] = [int(v) for v in values] if all(re.fullmatch(r"[+-]?\d+", v) for v in values) else values
|
|
418
|
+
axes.append(_axis_name(name))
|
|
419
|
+
else:
|
|
420
|
+
data["obs"] = list(range(1, len(rows) + 1))
|
|
421
|
+
axes.append("obs")
|
|
422
|
+
notes.append(f"page {p['name']} has no identifier column: rows numbered from 1 (obs)")
|
|
423
|
+
|
|
424
|
+
value_maps = _value_maps(b, p, where)
|
|
425
|
+
variables: dict[str, Variable] = {}
|
|
426
|
+
renamed: dict[str, str] = {}
|
|
427
|
+
retrieved = datetime.now().isoformat(timespec="seconds") # noqa: DTZ005 - local time, as pymetrix's readers stamp it
|
|
428
|
+
for j, s in enumerate(p["series"]):
|
|
429
|
+
sw = f"{where}.series[{j}]"
|
|
430
|
+
k = col(s["name"], f"the series {s['name']} in {sw}")
|
|
431
|
+
used.add(k)
|
|
432
|
+
name = _py_name(s["name"])
|
|
433
|
+
while name in data or name in variables:
|
|
434
|
+
name = f"{name}_v"
|
|
435
|
+
if name != s["name"]:
|
|
436
|
+
renamed[s["name"]] = name
|
|
437
|
+
if s["kind"] == "numeric":
|
|
438
|
+
data[name] = [_number(r[k], b.na, file, lines[i], header[k]) for i, r in enumerate(rows)]
|
|
439
|
+
else:
|
|
440
|
+
data[name] = pd.array([r[k] if r[k] != "" else None for r in rows], dtype="string")
|
|
441
|
+
variables[name] = _variable(name, s, value_maps, b, sw, retrieved)
|
|
442
|
+
if undated and structure in ("dated", "panel"):
|
|
443
|
+
name = "date" if "date" not in data else "date_v"
|
|
444
|
+
data[name] = dates_text
|
|
445
|
+
variables[name] = Variable(name, label="the EViews dates", description=f"the page's {freq_code} dates (first days)")
|
|
446
|
+
extra_cols = [header[k] for k in range(len(header)) if k not in used]
|
|
447
|
+
if extra_cols:
|
|
448
|
+
notes.append(f"{file}: columns the manifest does not list, left out: {', '.join(extra_cols)}")
|
|
449
|
+
if renamed:
|
|
450
|
+
notes.append("names changed to be valid Python names: " + ", ".join(f"{a} -> {c}" for a, c in renamed.items()))
|
|
451
|
+
|
|
452
|
+
frame = pd.DataFrame({k: v for k, v in data.items() if k not in axes}, index=pd.RangeIndex(len(rows)))
|
|
453
|
+
for a in axes:
|
|
454
|
+
frame[a] = data[a]
|
|
455
|
+
if structure == "dated" and not undated:
|
|
456
|
+
frame = frame.set_index("time")
|
|
457
|
+
if not frame.index.is_unique:
|
|
458
|
+
dup = frame.index[frame.index.duplicated()][0]
|
|
459
|
+
raise DataError(f"{file}: the period {dup} appears twice")
|
|
460
|
+
ds = Dataset.from_frame(frame.sort_index(), variables=variables)
|
|
461
|
+
else:
|
|
462
|
+
time = "time" if "time" in axes else None
|
|
463
|
+
entities = [a for a in axes if a != "time"]
|
|
464
|
+
keys = frame[axes]
|
|
465
|
+
if keys.duplicated().any():
|
|
466
|
+
row = int(keys.duplicated().to_numpy().nonzero()[0][0])
|
|
467
|
+
raise DataError(f"{file}, line {lines[row]}: the row's {' and '.join(axes)} appear on an earlier line")
|
|
468
|
+
ds = Dataset.from_frame(frame, time=time, entity=entities, freq=frame_freq, variables=variables)
|
|
469
|
+
meta = DatasetMeta(title=f"EViews {b.manifest['workfile']['name']}: page {p['name']}",
|
|
470
|
+
description=f"read from the bundle {b.manifest_path.name} (pymetrix-eviews)",
|
|
471
|
+
extra={"eviews": _page_meta(b, p, where, renamed)})
|
|
472
|
+
out = Dataset(ds.frame, ds.axes, ds.variables, ds.flags, meta)
|
|
473
|
+
for note in notes:
|
|
474
|
+
warnings.warn(note, EViewsBundleNote, stacklevel=2)
|
|
475
|
+
return out
|
|
476
|
+
|
|
477
|
+
|
|
478
|
+
def _csv(text: str, file: str) -> tuple[list[str], list[list[str]], list[int]]:
|
|
479
|
+
"""The header, the rows and each row's line in the file. A row with the wrong number of fields is refused."""
|
|
480
|
+
reader = csv.reader(io.StringIO(text), strict=True)
|
|
481
|
+
try:
|
|
482
|
+
header = next(reader)
|
|
483
|
+
except StopIteration:
|
|
484
|
+
raise DataError(f"{file} is empty: it should start with a row of column names") from None
|
|
485
|
+
except csv.Error as exc:
|
|
486
|
+
raise DataError(f"{file}, line 1: {exc}") from None
|
|
487
|
+
rows, lines = [], []
|
|
488
|
+
try:
|
|
489
|
+
for row in reader:
|
|
490
|
+
if not row or (len(row) == 1 and not row[0].strip()):
|
|
491
|
+
continue
|
|
492
|
+
if len(row) != len(header):
|
|
493
|
+
raise DataError(f"{file}, line {reader.line_num}: {len(row)} fields; the header has {len(header)}")
|
|
494
|
+
rows.append([v.strip() for v in row])
|
|
495
|
+
lines.append(reader.line_num)
|
|
496
|
+
except csv.Error as exc:
|
|
497
|
+
raise DataError(f"{file}, line {reader.line_num}: {exc}") from None
|
|
498
|
+
return [h.strip() for h in header], rows, lines
|
|
499
|
+
|
|
500
|
+
|
|
501
|
+
def _number(text: str, na: str, file: str, line: int, column: str) -> float:
|
|
502
|
+
if text == "" or text == na:
|
|
503
|
+
return math.nan
|
|
504
|
+
if not _NUMBER.match(text):
|
|
505
|
+
raise DataError(f"{file}, line {line}, column {column}: {text!r} is not a number (a missing value is {na!r} or empty)")
|
|
506
|
+
return float(text)
|
|
507
|
+
|
|
508
|
+
|
|
509
|
+
def _iso_date(text: str, file: str, line: int, column: str) -> date:
|
|
510
|
+
try:
|
|
511
|
+
return date.fromisoformat(text)
|
|
512
|
+
except ValueError:
|
|
513
|
+
raise DataError(f"{file}, line {line}, column {column}: {text!r} is not a date written YYYY-MM-DD") from None
|
|
514
|
+
|
|
515
|
+
|
|
516
|
+
def _pandas_freq(code: str, dates: list[date], file: str) -> str:
|
|
517
|
+
c = code.strip().upper()
|
|
518
|
+
if c != "W":
|
|
519
|
+
return _FREQ[c]
|
|
520
|
+
days = {d.weekday() for d in dates}
|
|
521
|
+
if len(days) > 1:
|
|
522
|
+
raise DataError(f"{file}: weekly dates start on different days of the week ({', '.join(_WEEKDAYS[d] for d in sorted(days))})")
|
|
523
|
+
start = days.pop() if days else 0
|
|
524
|
+
return f"W-{_WEEKDAYS[(start - 1) % 7]}" # a week that starts on Monday ends on Sunday: W-SUN
|
|
525
|
+
|
|
526
|
+
|
|
527
|
+
def _variable(name: str, s: Mapping[str, Any], maps: Mapping[str, dict[str, str]], b: _Bundle, where: str, retrieved: str) -> Any:
|
|
528
|
+
from pymetrix.metadata import Variable
|
|
529
|
+
|
|
530
|
+
display, description = s.get("display_name", ""), s.get("description", "")
|
|
531
|
+
extra: dict[str, Any] = {}
|
|
532
|
+
if name != s["name"]:
|
|
533
|
+
extra["eviews_name"] = s["name"]
|
|
534
|
+
if s["kind"] == "alpha":
|
|
535
|
+
extra["eviews_kind"] = "alpha"
|
|
536
|
+
if display and description:
|
|
537
|
+
extra["display_name"] = display
|
|
538
|
+
for key in ("remarks",):
|
|
539
|
+
if s.get(key):
|
|
540
|
+
extra[key] = s[key]
|
|
541
|
+
if s.get("attributes"):
|
|
542
|
+
extra["attributes"] = dict(s["attributes"])
|
|
543
|
+
vm = s.get("value_map")
|
|
544
|
+
if vm:
|
|
545
|
+
if vm.lower() not in maps:
|
|
546
|
+
raise DataError(f"{b.manifest_path.name}: {where}.value_map names {vm!r}, which the page's value_maps do not list")
|
|
547
|
+
extra["value_map"] = {"name": vm.lower(), "labels": dict(maps[vm.lower()])}
|
|
548
|
+
return Variable(name, label=display or description, description=description, units=s.get("units", ""),
|
|
549
|
+
source=s.get("source", ""), source_key=s["name"], retrieved=retrieved, extra=extra)
|
|
550
|
+
|
|
551
|
+
|
|
552
|
+
def _value_maps(b: _Bundle, p: Mapping[str, Any], where: str) -> dict[str, dict[str, str]]:
|
|
553
|
+
out: dict[str, dict[str, str]] = {}
|
|
554
|
+
for j, vm in enumerate(p.get("value_maps", [])):
|
|
555
|
+
text, file = b.text(vm["file"], f"{where}.value_maps[{j}].file")
|
|
556
|
+
header, rows, lines = _csv(text, file)
|
|
557
|
+
if [h.lower() for h in header] != ["value", "label"]:
|
|
558
|
+
raise DataError(f"{file}, line 1: a value map's columns are value,label (found {','.join(header)})")
|
|
559
|
+
labels: dict[str, str] = {}
|
|
560
|
+
for r, line in zip(rows, lines):
|
|
561
|
+
if r[0] in labels:
|
|
562
|
+
raise DataError(f"{file}, line {line}: the value {r[0]!r} is mapped twice")
|
|
563
|
+
labels[r[0]] = r[1]
|
|
564
|
+
out[vm["name"].lower()] = labels
|
|
565
|
+
return out
|
|
566
|
+
|
|
567
|
+
|
|
568
|
+
def _page_meta(b: _Bundle, p: Mapping[str, Any], where: str, renamed: Mapping[str, str]) -> dict[str, Any]:
|
|
569
|
+
"""What the page holds besides its series, as JSON values (kept in Parquet files and projects)."""
|
|
570
|
+
m = b.manifest
|
|
571
|
+
out: dict[str, Any] = {
|
|
572
|
+
"format_version": m["format_version"], "exporter": dict(m["exporter"]), "workfile": dict(m["workfile"]),
|
|
573
|
+
"bundle": str(b.manifest_path), "page": p["name"], "structure": p["structure"],
|
|
574
|
+
"frequency": p.get("frequency"), "range": list(p.get("range", [])), "sample": p.get("sample", ""),
|
|
575
|
+
"groups": {g["name"].lower(): [str(x).lower() for x in g["members"]] for g in p.get("groups", [])},
|
|
576
|
+
"samples": {s["name"].lower(): s["text"] for s in p.get("samples", [])},
|
|
577
|
+
"scalars": {s["name"].lower(): s["value"] for s in p.get("scalars", [])},
|
|
578
|
+
"strings": {s["name"].lower(): s["value"] for s in p.get("strings", [])},
|
|
579
|
+
"arrays": {}, "equations": [], "models": {},
|
|
580
|
+
"skipped": [dict(s) for s in p.get("skipped", [])],
|
|
581
|
+
"renamed": dict(renamed), "notes": list(b.notes), "unknown": dict(b.unknown),
|
|
582
|
+
}
|
|
583
|
+
for j, a in enumerate(p.get("arrays", [])):
|
|
584
|
+
aw = f"{where}.arrays[{j}]"
|
|
585
|
+
text, file = b.text(a["file"], f"{aw}.file")
|
|
586
|
+
values = _array(text, file, b.na, a["rows"], a["cols"])
|
|
587
|
+
out["arrays"][a["name"].lower()] = {"type": a["type"], "rows": a["rows"], "cols": a["cols"], "values": values}
|
|
588
|
+
for j, e in enumerate(p.get("equations", [])):
|
|
589
|
+
ew = f"{where}.equations[{j}]"
|
|
590
|
+
command = e.get("command")
|
|
591
|
+
if command is None:
|
|
592
|
+
command, _ = b.text(e["command_file"], f"{ew}.command_file")
|
|
593
|
+
command = " ".join(command.split())
|
|
594
|
+
eq: dict[str, Any] = {"name": e["name"].lower(), "command": command, "method": e["method"], "sample": e.get("sample", ""),
|
|
595
|
+
"ncoef": e.get("ncoef")}
|
|
596
|
+
if e.get("estimates"):
|
|
597
|
+
text, file = b.text(e["estimates"], f"{ew}.estimates")
|
|
598
|
+
eq.update(_estimates(text, file, b.na, e.get("ncoef")))
|
|
599
|
+
out["equations"].append(eq)
|
|
600
|
+
for j, mdl in enumerate(p.get("models", [])):
|
|
601
|
+
text, _ = b.text(mdl["text"], f"{where}.models[{j}].text")
|
|
602
|
+
out["models"][mdl["name"].lower()] = text.replace("\r\n", "\n")
|
|
603
|
+
return out
|
|
604
|
+
|
|
605
|
+
|
|
606
|
+
def _array(text: str, file: str, na: str, rows: int, cols: int) -> list[list[float | None]]:
|
|
607
|
+
"""A matrix's CSV: one line per row, no header; missing values as the bundle's NA, read as null."""
|
|
608
|
+
reader = csv.reader(io.StringIO(text))
|
|
609
|
+
out: list[list[float | None]] = []
|
|
610
|
+
for row in reader:
|
|
611
|
+
if not row or (len(row) == 1 and not row[0].strip()):
|
|
612
|
+
continue
|
|
613
|
+
if len(row) != cols:
|
|
614
|
+
raise DataError(f"{file}, line {reader.line_num}: {len(row)} values; the manifest says {cols} columns")
|
|
615
|
+
values = []
|
|
616
|
+
for k, v in enumerate(row):
|
|
617
|
+
x = _number(v.strip(), na, file, reader.line_num, f"{k + 1}")
|
|
618
|
+
values.append(None if math.isnan(x) else x)
|
|
619
|
+
out.append(values)
|
|
620
|
+
if len(out) != rows:
|
|
621
|
+
raise DataError(f"{file}: {len(out)} rows; the manifest says {rows}")
|
|
622
|
+
return out
|
|
623
|
+
|
|
624
|
+
|
|
625
|
+
def _estimates(text: str, file: str, na: str, ncoef: Any) -> dict[str, Any]:
|
|
626
|
+
header, rows, lines = _csv(text, file)
|
|
627
|
+
if [h.lower() for h in header] != ["coefficient", "estimate", "std_error"]:
|
|
628
|
+
raise DataError(f"{file}, line 1: an equation's estimates have the columns coefficient,estimate,std_error "
|
|
629
|
+
f"(found {','.join(header)})")
|
|
630
|
+
if ncoef is not None and len(rows) != ncoef:
|
|
631
|
+
raise DataError(f"{file}: {len(rows)} coefficients; the manifest's ncoef is {ncoef}")
|
|
632
|
+
|
|
633
|
+
def num(v: str, line: int, column: str) -> float | None:
|
|
634
|
+
x = _number(v, na, file, line, column)
|
|
635
|
+
return None if math.isnan(x) else x
|
|
636
|
+
|
|
637
|
+
return {"coefficients": [r[0] for r in rows], "estimates": [num(r[1], ln, "estimate") for r, ln in zip(rows, lines)],
|
|
638
|
+
"std_errors": [num(r[2], ln, "std_error") for r, ln in zip(rows, lines)]}
|
|
639
|
+
|
|
640
|
+
|
|
641
|
+
# -- what a bundle holds -------------------------------------------------------------------------------------------
|
|
642
|
+
|
|
643
|
+
|
|
644
|
+
def bundle_pages(source: str | Path) -> list[dict[str, Any]]:
|
|
645
|
+
"""The pages of a bundle, without reading their data: name, structure, frequency, how many series, and why the
|
|
646
|
+
page cannot be read with a time axis (``refused``; None when it can)."""
|
|
647
|
+
b = _open(source)
|
|
648
|
+
out = []
|
|
649
|
+
for p in b.manifest["pages"]:
|
|
650
|
+
refused = _refused_frequency(str(p.get("frequency") or "")) if p["structure"] != "undated" else None
|
|
651
|
+
out.append({"name": p["name"], "structure": p["structure"], "frequency": p.get("frequency"),
|
|
652
|
+
"series": len(p["series"]), "refused": refused})
|
|
653
|
+
return out
|
|
654
|
+
|
|
655
|
+
|
|
656
|
+
def bundle_schema() -> dict[str, Any]:
|
|
657
|
+
"""The JSON Schema of the manifest (format version 1)."""
|
|
658
|
+
return json.loads((_HERE / "bundle-1.schema.json").read_text(encoding="utf-8"))
|
|
659
|
+
|
|
660
|
+
|
|
661
|
+
def _eviews(data: Any) -> dict[str, Any]:
|
|
662
|
+
ev = (getattr(getattr(data, "meta", None), "extra", None) or {}).get("eviews")
|
|
663
|
+
if not isinstance(ev, Mapping):
|
|
664
|
+
raise DataError("this dataset was not read from an EViews bundle (it has no meta.extra['eviews'])")
|
|
665
|
+
return dict(ev)
|
|
666
|
+
|
|
667
|
+
|
|
668
|
+
def eviews_sample(text: str, frequency: str | None = None) -> Any:
|
|
669
|
+
"""An EViews sample's text as a pymetrix ``Sample``, or None when it does not translate: ``@all``, and one pair
|
|
670
|
+
of ends (``1980q1 2007q4``, ``@first 2000q4``, ``1990:1 @last`` with the page's ``frequency``, ``Q`` or ``M``).
|
|
671
|
+
Conditions (``if ...``) and several pairs are not translated."""
|
|
672
|
+
from pymetrix import Sample
|
|
673
|
+
|
|
674
|
+
tokens = str(text).strip().lower().split()
|
|
675
|
+
if not tokens or tokens == ["@all"]:
|
|
676
|
+
return Sample()
|
|
677
|
+
if len(tokens) != 2:
|
|
678
|
+
return None
|
|
679
|
+
ends = []
|
|
680
|
+
for token in tokens:
|
|
681
|
+
if token in ("@first", "@last"):
|
|
682
|
+
ends.append(None)
|
|
683
|
+
continue
|
|
684
|
+
period = _period(token, frequency)
|
|
685
|
+
if period is None:
|
|
686
|
+
return None
|
|
687
|
+
ends.append(period)
|
|
688
|
+
return Sample(start=ends[0], end=ends[1])
|
|
689
|
+
|
|
690
|
+
|
|
691
|
+
def _period(token: str, frequency: str | None) -> str | None:
|
|
692
|
+
f = (frequency or "").upper()
|
|
693
|
+
if m := re.fullmatch(r"(\d{4})q([1-4])", token):
|
|
694
|
+
return f"{m.group(1)}Q{m.group(2)}"
|
|
695
|
+
if m := re.fullmatch(r"(\d{4})m(\d{1,2})", token):
|
|
696
|
+
return f"{m.group(1)}-{int(m.group(2)):02d}" if 1 <= int(m.group(2)) <= 12 else None
|
|
697
|
+
if m := re.fullmatch(r"(\d{4}):(\d{1,2})", token):
|
|
698
|
+
if f == "Q" and 1 <= int(m.group(2)) <= 4:
|
|
699
|
+
return f"{m.group(1)}Q{m.group(2)}"
|
|
700
|
+
if f == "M" and 1 <= int(m.group(2)) <= 12:
|
|
701
|
+
return f"{m.group(1)}-{int(m.group(2)):02d}"
|
|
702
|
+
return None
|
|
703
|
+
if re.fullmatch(r"\d{4}", token) and f in ("A", "Y"):
|
|
704
|
+
return token
|
|
705
|
+
return None
|
|
706
|
+
|
|
707
|
+
|
|
708
|
+
def eviews_objects(data: Any) -> dict[str, Any]:
|
|
709
|
+
"""The page's other EViews objects, as pymetrix's: groups as ``Selection`` (``data.series(...)``; a group with a
|
|
710
|
+
member that is not a series of the page is left out), samples as ``Sample`` (where ``eviews_sample`` translates
|
|
711
|
+
them), scalars as numbers, strings as text, vectors and matrices as ``Matrix``, and models as templates
|
|
712
|
+
(``bundle_model``; a model the core reader refuses is left out). What is left out is listed under ``"_left_out"``
|
|
713
|
+
with the reason."""
|
|
714
|
+
import numpy as np
|
|
715
|
+
|
|
716
|
+
from pymetrix import Matrix
|
|
717
|
+
|
|
718
|
+
ev = _eviews(data)
|
|
719
|
+
out: dict[str, Any] = {}
|
|
720
|
+
left: dict[str, str] = {}
|
|
721
|
+
columns = set(data.frame.columns)
|
|
722
|
+
for name, members in ev.get("groups", {}).items():
|
|
723
|
+
missing = [m for m in members if m not in columns]
|
|
724
|
+
if missing:
|
|
725
|
+
left[name] = f"group: {', '.join(missing)} {'is' if len(missing) == 1 else 'are'} not series of the page"
|
|
726
|
+
continue
|
|
727
|
+
out[name] = data.series(*members)
|
|
728
|
+
for name, text in ev.get("samples", {}).items():
|
|
729
|
+
sample = eviews_sample(text, ev.get("frequency"))
|
|
730
|
+
if sample is None:
|
|
731
|
+
left[name] = f"sample {text!r}: only @all and one pair of ends translate"
|
|
732
|
+
else:
|
|
733
|
+
out[name] = sample
|
|
734
|
+
for name, value in ev.get("scalars", {}).items():
|
|
735
|
+
out[name] = math.nan if value is None else float(value)
|
|
736
|
+
out.update(ev.get("strings", {}))
|
|
737
|
+
for name, a in ev.get("arrays", {}).items():
|
|
738
|
+
values = np.array([[math.nan if v is None else v for v in row] for row in a["values"]], dtype=float).reshape(a["rows"], a["cols"])
|
|
739
|
+
out[name] = Matrix(values, title=name)
|
|
740
|
+
for name in ev.get("models", {}):
|
|
741
|
+
try:
|
|
742
|
+
out[name] = bundle_model(data, name)
|
|
743
|
+
except Exception as exc: # noqa: BLE001 - the reason is given, the rest still returned
|
|
744
|
+
left[name] = f"model: {exc}"
|
|
745
|
+
if left:
|
|
746
|
+
out["_left_out"] = left
|
|
747
|
+
return out
|
|
748
|
+
|
|
749
|
+
|
|
750
|
+
def _model_program(ev: Mapping[str, Any], name: str) -> str:
|
|
751
|
+
"""The model as a program the core reader takes: its equations (``equation eq.ls ...`` on their samples), then
|
|
752
|
+
``model m``, ``m.merge eq`` for each linked equation (``:eq`` in the text) and ``m.append`` for the rest."""
|
|
753
|
+
models = ev.get("models", {})
|
|
754
|
+
if name.lower() not in models:
|
|
755
|
+
raise NotFoundError(f"the page has no model {name!r}; its models: {', '.join(models) or 'none'}")
|
|
756
|
+
equations = {e["name"]: e for e in ev.get("equations", [])}
|
|
757
|
+
lines = [ln.strip() for ln in models[name.lower()].splitlines()]
|
|
758
|
+
links = [ln[1:].strip().lower() for ln in lines if ln.startswith(":")]
|
|
759
|
+
program = []
|
|
760
|
+
for eq in links:
|
|
761
|
+
if eq not in equations:
|
|
762
|
+
raise DataError(f"model {name}: the linked equation {eq} is not in the bundle's equations")
|
|
763
|
+
e = equations[eq]
|
|
764
|
+
if e.get("sample"):
|
|
765
|
+
program.append(f"smpl {e['sample']}")
|
|
766
|
+
program.append(f"equation {eq}.{e['command']}")
|
|
767
|
+
program.append(f"model {name.lower()}")
|
|
768
|
+
for ln in lines:
|
|
769
|
+
if not ln or ln.startswith("'"):
|
|
770
|
+
continue
|
|
771
|
+
program.append(f"{name.lower()}.merge {ln[1:].strip().lower()}" if ln.startswith(":") else f"{name.lower()}.append {ln}")
|
|
772
|
+
return "\n".join(program) + "\n"
|
|
773
|
+
|
|
774
|
+
|
|
775
|
+
def bundle_model(data: Any, name: str) -> Any:
|
|
776
|
+
"""A model of the page, read by ``read_eviews``: its text, with the equations it links fitted to ``data`` by the
|
|
777
|
+
core reader (least squares, on each equation's sample) and the page's scalars that the text names as its
|
|
778
|
+
parameters. EViews's own estimates are not used; ``compare_estimates`` sets the two side by side."""
|
|
779
|
+
from pymetrix import read_eviews
|
|
780
|
+
|
|
781
|
+
ev = _eviews(data)
|
|
782
|
+
program = _model_program(ev, name)
|
|
783
|
+
scalars = {k: v for k, v in ev.get("scalars", {}).items()
|
|
784
|
+
if v is not None and re.search(rf"(?<![\w@]){re.escape(k)}(?!\w)", program, flags=re.IGNORECASE)}
|
|
785
|
+
return read_eviews(program, params=scalars or None, data=data, name=name.lower())
|
|
786
|
+
|
|
787
|
+
|
|
788
|
+
def _top_level_split(text: str) -> list[str]:
|
|
789
|
+
out, depth, word = [], 0, ""
|
|
790
|
+
for ch in text:
|
|
791
|
+
if ch == "(":
|
|
792
|
+
depth += 1
|
|
793
|
+
elif ch == ")":
|
|
794
|
+
depth -= 1
|
|
795
|
+
if ch.isspace() and depth == 0:
|
|
796
|
+
if word:
|
|
797
|
+
out.append(word)
|
|
798
|
+
word = ""
|
|
799
|
+
else:
|
|
800
|
+
word += ch
|
|
801
|
+
if word:
|
|
802
|
+
out.append(word)
|
|
803
|
+
return out
|
|
804
|
+
|
|
805
|
+
|
|
806
|
+
def compare_estimates(data: Any, tolerance: float = 1e-6) -> Any:
|
|
807
|
+
"""Each least-squares equation of the page refitted in pymetrix, against EViews's own estimates: a ``Table`` with
|
|
808
|
+
a row per coefficient, saying *matches* (within ``tolerance``, relative, for the estimate and its standard error)
|
|
809
|
+
or how much they differ. Equations by other methods, or with options (``ls(cov=white)``), are listed as not
|
|
810
|
+
compared, with the reason. The refit is the core reader's (``read_eviews`` with the data), on each equation's
|
|
811
|
+
sample; a list specification's ``c`` is pymetrix's ``const``."""
|
|
812
|
+
import numpy as np
|
|
813
|
+
import pandas as pd
|
|
814
|
+
|
|
815
|
+
from pymetrix import read_eviews
|
|
816
|
+
from pymetrix.extension import parse_eviews_expression, render_eviews_expression
|
|
817
|
+
from pymetrix.output import Table
|
|
818
|
+
|
|
819
|
+
def term(text: str) -> str: # a regressor of a list specification as pymetrix writes it: cons(-1) -> cons[-1]
|
|
820
|
+
return "const" if text.lower() == "c" else render_eviews_expression(parse_eviews_expression(text, 0, {"c"}))
|
|
821
|
+
|
|
822
|
+
ev = _eviews(data)
|
|
823
|
+
rows = []
|
|
824
|
+
for e in ev.get("equations", []):
|
|
825
|
+
command = str(e["command"]).strip()
|
|
826
|
+
method = command.split()[0].lower() if command else ""
|
|
827
|
+
reason = None
|
|
828
|
+
if str(e.get("method", "")).lower() not in ("ls", "least squares") or not method.startswith("ls"):
|
|
829
|
+
reason = f"method {e.get('method')}: only least squares (ls) is compared in this version"
|
|
830
|
+
elif method != "ls":
|
|
831
|
+
reason = f"options {method[2:]}: the core reader ignores them, so its fit would not be the same estimator"
|
|
832
|
+
elif "estimates" not in e:
|
|
833
|
+
reason = "the bundle has no estimates for it"
|
|
834
|
+
if reason:
|
|
835
|
+
rows.append({"equation": e["name"], "coefficient": "", "EViews": np.nan, "pymetrix": np.nan, "EViews s.e.": np.nan,
|
|
836
|
+
"pymetrix s.e.": np.nan, "result": f"not compared: {reason}"})
|
|
837
|
+
continue
|
|
838
|
+
program = (f"smpl {e['sample']}\n" if e.get("sample") else "") + f"equation {e['name']}.{command}\nmodel _m\n_m.merge {e['name']}\n"
|
|
839
|
+
try:
|
|
840
|
+
fit = read_eviews(program, data=data).model.equations[0]
|
|
841
|
+
names = list(fit.params.names)
|
|
842
|
+
values = np.asarray(fit.params.values, dtype=float)
|
|
843
|
+
ses = np.sqrt(np.diag(np.asarray(fit.params.cov, dtype=float)))
|
|
844
|
+
spec = command[2:].strip()
|
|
845
|
+
if "=" in spec: # an expression: c(i) is pymetrix's c_i
|
|
846
|
+
order = [f"c_{i + 1}" for i in range(len(e["estimates"]))]
|
|
847
|
+
else: # a list: the dependent variable, then the regressors in EViews's order of c(1), c(2) ...
|
|
848
|
+
order = [term(t) for t in _top_level_split(spec)[1:]]
|
|
849
|
+
except (DataError, ValueError) as exc:
|
|
850
|
+
rows.append({"equation": e["name"], "coefficient": "", "EViews": np.nan, "pymetrix": np.nan, "EViews s.e.": np.nan,
|
|
851
|
+
"pymetrix s.e.": np.nan, "result": f"not compared: pymetrix could not fit it ({exc})"})
|
|
852
|
+
continue
|
|
853
|
+
for i, (coef, b, s) in enumerate(zip(e["coefficients"], e["estimates"], e["std_errors"])):
|
|
854
|
+
name = order[i] if i < len(order) else None
|
|
855
|
+
if name not in names:
|
|
856
|
+
rows.append({"equation": e["name"], "coefficient": coef, "EViews": b, "pymetrix": np.nan, "EViews s.e.": s,
|
|
857
|
+
"pymetrix s.e.": np.nan, "result": f"not compared: no term {name} in pymetrix's fit"})
|
|
858
|
+
continue
|
|
859
|
+
k = names.index(name)
|
|
860
|
+
ours, our_se = float(values[k]), float(ses[k])
|
|
861
|
+
gaps = [abs(ours - b) / max(abs(b), 1e-300) if b is not None else math.inf,
|
|
862
|
+
abs(our_se - s) / max(abs(s), 1e-300) if s is not None else math.inf]
|
|
863
|
+
result = "matches" if max(gaps) <= tolerance else f"differs: relative {max(gaps):.3g}"
|
|
864
|
+
rows.append({"equation": e["name"], "coefficient": f"{coef} ({name})", "EViews": b, "pymetrix": ours, "EViews s.e.": s,
|
|
865
|
+
"pymetrix s.e.": our_se, "result": result})
|
|
866
|
+
frame = pd.DataFrame(rows, columns=["equation", "coefficient", "EViews", "pymetrix", "EViews s.e.", "pymetrix s.e.", "result"])
|
|
867
|
+
frame.index = pd.RangeIndex(1, len(frame) + 1)
|
|
868
|
+
return Table.from_frame(frame, title="EViews's estimates and pymetrix's refit",
|
|
869
|
+
notes=(f"matches: within {tolerance:g}, relative, for the estimate and its standard error",))
|
|
870
|
+
|
|
871
|
+
|
|
872
|
+
# -- the export program --------------------------------------------------------------------------------------------
|
|
873
|
+
|
|
874
|
+
|
|
875
|
+
def export_program() -> str:
|
|
876
|
+
"""The text of ``pymetrix_export.prg``, the program that writes a bundle from EViews. EXPERIMENTAL: written from
|
|
877
|
+
EViews's documentation and never run in EViews (the project has no licence); every *(verify)* comment in it is
|
|
878
|
+
a point to check. Saving the workfile from EViews as CSV or Excel is the supported way in."""
|
|
879
|
+
return (_HERE / "export" / "pymetrix_export.prg").read_text(encoding="utf-8")
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def save_export_program(path: str | Path) -> str:
|
|
883
|
+
"""Save a copy of the export program (EXPERIMENTAL, untested in EViews) at ``path`` (a folder: as
|
|
884
|
+
pymetrix_export.prg in it), with Windows line ends, as EViews expects; returns where it was saved."""
|
|
885
|
+
out = Path(path)
|
|
886
|
+
if out.is_dir():
|
|
887
|
+
out = out / "pymetrix_export.prg"
|
|
888
|
+
out.write_bytes(export_program().replace("\r\n", "\n").replace("\n", "\r\n").encode("utf-8"))
|
|
889
|
+
return str(out)
|