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,196 @@
1
+ """EViews's date numbers and date strings, for translated programs: ``@dateval``, ``@datestr``, ``@dateadd``,
2
+ ``@datediff``, ``@dtoo`` and ``@otod`` act on a program's ``%`` strings and ``!`` numbers, so the translation
3
+ (``translate_program``) works them out as Python values, as it does the string functions: when the program's own
4
+ values are known before it runs, at translation time; otherwise when the script runs, with these functions
5
+ (``import pymetrix_eviews.dates as eviews_dates`` in the script).
6
+
7
+ A date number is EViews's: the number of days since Monday 1 January A.D. 1 in the proleptic Gregorian calendar,
8
+ that day being 0 (EViews's Command Reference, "Dates"; its example, ``@dateval("12/1/1999", "dd/mm/yyyy")`` =
9
+ 729765, is 12 January 1999). It is Python's ``date.toordinal()`` minus 1. Only whole days are read (EViews keeps the
10
+ time of day in the fraction).
11
+
12
+ Formats: ``yyyy`` and ``yy`` (two-digit years from 30 are 19xx, others 20xx), ``q`` (the quarter), ``mm`` and ``m``
13
+ (the month), ``dd`` and ``d`` (the day), ``f``/``F`` (the period's letter: ``q`` in a format with a quarter, ``m``
14
+ in one with a month only; lower or upper case as written), text in square brackets as it is (``yyyy[Q]q``), and
15
+ spaces and ``: - / .`` as they are. A period is its first day: ``"2001q3"`` is 1 July 2001. Without a format, a
16
+ date string is read as ``2001q3``, ``2001m7``, ``2001``, ``2001-07-01`` or ``7/1/2001`` (month first).
17
+ """
18
+
19
+ from __future__ import annotations
20
+
21
+ import calendar
22
+ import re
23
+ from datetime import date, timedelta
24
+ from typing import Any
25
+
26
+ __all__ = ["dateadd", "datediff", "datestr", "dateval", "dtoo", "otod"]
27
+
28
+ _TOKENS = re.compile(r"\[[^\]]*\]|yyyy|yy|mm|dd|[qmdf]|.", re.I | re.S)
29
+
30
+
31
+ def _number(d: date) -> float:
32
+ return float(d.toordinal() - 1)
33
+
34
+
35
+ def _date(number: Any) -> date:
36
+ n = float(number)
37
+ if n != n:
38
+ raise ValueError("an NA date number")
39
+ return date.fromordinal(int(n // 1) + 1)
40
+
41
+
42
+ def _year(text: str) -> int:
43
+ y = int(text)
44
+ return y if len(text) > 2 else (1900 + y if y >= 30 else 2000 + y)
45
+
46
+
47
+ def _tokens(fmt: str) -> list[str]:
48
+ return _TOKENS.findall(fmt)
49
+
50
+
51
+ def dateval(text: str, fmt: str | None = None) -> float:
52
+ """``@dateval``: the date number of a date string, read with ``fmt`` (EViews's date format) or, without one, as
53
+ a period or a calendar date (the module's docstring)."""
54
+ s = str(text).strip()
55
+ if fmt is None:
56
+ m = re.fullmatch(r"(\d{4})\s*([qQmM])\s*(\d{1,2})", s)
57
+ if m:
58
+ year, kind, n = int(m.group(1)), m.group(2).lower(), int(m.group(3))
59
+ if kind == "q" and 1 <= n <= 4:
60
+ return _number(date(year, 3 * n - 2, 1))
61
+ if kind == "m" and 1 <= n <= 12:
62
+ return _number(date(year, n, 1))
63
+ if re.fullmatch(r"\d{4}", s):
64
+ return _number(date(int(s), 1, 1))
65
+ m = re.fullmatch(r"(\d{4})-(\d{1,2})-(\d{1,2})", s)
66
+ if m:
67
+ return _number(date(int(m.group(1)), int(m.group(2)), int(m.group(3))))
68
+ m = re.fullmatch(r"(\d{1,2})/(\d{1,2})/(\d{2}|\d{4})", s)
69
+ if m:
70
+ return _number(date(_year(m.group(3)), int(m.group(1)), int(m.group(2))))
71
+ raise ValueError(f"{s!r} is not a date read without a format: 2001q3, 2001m7, 2001, 2001-07-01 or 7/1/2001")
72
+ pattern, fields = "", []
73
+ for tok in _tokens(fmt):
74
+ low = tok.lower()
75
+ if tok.startswith("["):
76
+ pattern += re.escape(tok[1:-1])
77
+ elif low in ("yyyy", "yy", "mm", "dd", "q", "m", "d"):
78
+ pattern += {"yyyy": r"(\d{4})", "yy": r"(\d{2})", "mm": r"(\d{1,2})", "dd": r"(\d{1,2})", "q": r"(\d)",
79
+ "m": r"(\d{1,2})", "d": r"(\d{1,2})"}[low]
80
+ fields.append(low)
81
+ elif low == "f":
82
+ pattern += r"[a-z]"
83
+ elif tok.isspace():
84
+ pattern += r"\s*"
85
+ else:
86
+ pattern += re.escape(tok)
87
+ m = re.fullmatch(pattern, s, re.I)
88
+ if m is None:
89
+ raise ValueError(f"{s!r} does not read with the format {fmt!r}")
90
+ got = dict(zip(fields, m.groups()))
91
+ year = _year(got.get("yyyy") or got["yy"]) if ("yyyy" in got or "yy" in got) else 1
92
+ month = int(got.get("mm") or got.get("m") or 1)
93
+ if "q" in got:
94
+ month = 3 * int(got["q"]) - 2
95
+ day = int(got.get("dd") or got.get("d") or 1)
96
+ return _number(date(year, month, day))
97
+
98
+
99
+ def datestr(number: Any, fmt: str) -> str:
100
+ """``@datestr``: the date number as text in EViews's date format ``fmt``."""
101
+ d = _date(number)
102
+ tokens = _tokens(fmt)
103
+ lows = [t.lower() for t in tokens]
104
+ letter = "q" if "q" in lows else "m" if ("m" in lows or "mm" in lows) else "a"
105
+ out = []
106
+ for tok, low in zip(tokens, lows):
107
+ if tok.startswith("["):
108
+ out.append(tok[1:-1])
109
+ elif low == "yyyy":
110
+ out.append(f"{d.year:04d}")
111
+ elif low == "yy":
112
+ out.append(f"{d.year % 100:02d}")
113
+ elif low == "q":
114
+ out.append(str((d.month - 1) // 3 + 1))
115
+ elif low == "mm":
116
+ out.append(f"{d.month:02d}")
117
+ elif low == "m":
118
+ out.append(str(d.month))
119
+ elif low == "dd":
120
+ out.append(f"{d.day:02d}")
121
+ elif low == "d":
122
+ out.append(str(d.day))
123
+ elif low == "f":
124
+ out.append(letter.upper() if tok == "F" else letter)
125
+ else:
126
+ out.append(tok)
127
+ return "".join(out)
128
+
129
+
130
+ _PER_YEAR = {"a": 1, "y": 1, "s": 2, "q": 4, "m": 12}
131
+
132
+
133
+ def _unit(u: str) -> str:
134
+ low = str(u).strip().lower()
135
+ if low in _PER_YEAR or low in ("w", "d"):
136
+ return low
137
+ raise ValueError(f"{u!r} is not a unit read here: a (or y), s, q, m, w or d")
138
+
139
+
140
+ def dateadd(number: Any, n: Any, u: str) -> float:
141
+ """``@dateadd``: the date number ``n`` units ``u`` later (a, y, s, q, m: calendar periods, the day of the month
142
+ kept or, past the month's end, its last day; w: weeks; d: days)."""
143
+ d, unit, k = _date(number), _unit(u), int(float(n))
144
+ if unit == "d":
145
+ return _number(d + timedelta(days=k))
146
+ if unit == "w":
147
+ return _number(d + timedelta(weeks=k))
148
+ months = d.year * 12 + d.month - 1 + k * 12 // _PER_YEAR[unit]
149
+ year, month = divmod(months, 12)
150
+ return _number(date(year, month + 1, min(d.day, calendar.monthrange(year, month + 1)[1])))
151
+
152
+
153
+ def datediff(first: Any, second: Any, u: str) -> float:
154
+ """``@datediff``: how many units ``u`` the first date number is after the second (negative when before): whole
155
+ calendar periods between the periods they fall in for a, y, s, q, m; whole weeks or days for w and d."""
156
+ a, b, unit = _date(first), _date(second), _unit(u)
157
+ if unit == "d":
158
+ return float((a - b).days)
159
+ if unit == "w":
160
+ days = (a - b).days
161
+ return float(days // 7 if days >= 0 else -((-days) // 7))
162
+ per = _PER_YEAR[unit]
163
+
164
+ def period(d: date) -> int:
165
+ return d.year * per + (d.month - 1) * per // 12
166
+ return float(period(a) - period(b))
167
+
168
+
169
+ def _periods(data: Any) -> Any:
170
+ t = data.time_axis
171
+ if t is None:
172
+ raise ValueError("@dtoo and @otod need a dated page")
173
+ return data.frame.index.get_level_values(t.name).unique().sort_values()
174
+
175
+
176
+ def dtoo(data: Any, text: str) -> float:
177
+ """``@dtoo``: the observation number (from 1) of a date in the page ``data`` (a Dataset): its period's place
178
+ among the page's periods."""
179
+ import pandas as pd
180
+
181
+ periods = _periods(data)
182
+ when = pd.Timestamp(_date(dateval(text)))
183
+ hits = [i for i, p in enumerate(periods) if p.start_time <= when <= p.end_time]
184
+ if not hits:
185
+ raise ValueError(f"{text!r} is not a period of the page ({periods[0]} to {periods[-1]})")
186
+ return float(hits[0] + 1)
187
+
188
+
189
+ def otod(data: Any, n: Any) -> str:
190
+ """``@otod``: the date of observation ``n`` (from 1) of the page ``data``, as pandas writes the period
191
+ (``2001Q3``, ``2001-07``, ``2001``)."""
192
+ periods = _periods(data)
193
+ i = int(float(n))
194
+ if not 1 <= i <= len(periods):
195
+ raise ValueError(f"observation {i} is outside the page (1 to {len(periods)})")
196
+ return str(periods[i - 1])
@@ -0,0 +1,476 @@
1
+ ' pymetrix_export.prg -- writes the open EViews workfile as a pymetrix bundle (format version 1)
2
+ '
3
+ ' EXPERIMENTAL. UNTESTED IN EVIEWS.
4
+ ' This program was written from EViews's public documentation, without EViews: the pymetrix project has no EViews
5
+ ' licence, so it has never been run. Every line marked (verify) uses syntax or behaviour that must be checked
6
+ ' against EViews's own Command and Programming Reference, in the two most recent major versions, before the
7
+ ' "experimental" label comes off. Until then, save the workfile from EViews as CSV or Excel (File > Save As, or
8
+ ' wfsave(type=...)) and load that in pymetrix: that is the supported way in.
9
+ '
10
+ ' Use: open the workfile in EViews, then run
11
+ ' exec pymetrix_export.prg C:\work\macro-export
12
+ ' and open C:\work\macro-export\<workfile>.evbundle in pymetrix (File > Import EViews workfile...).
13
+ '
14
+ ' What it writes (see the plugin's README for the format):
15
+ ' <workfile>.evbundle the manifest (JSON), written last: a folder without it is an incomplete export
16
+ ' pages\<page>.csv each page's series and alpha series, with a date column (pmx_date)
17
+ ' text\<page>\<object>.txt each model's text
18
+ ' objects\<page>\<name>.csv vectors, matrices, sym and coef objects; each equation's estimates
19
+ ' valmaps\<page>\<name>.csv value maps: value,label
20
+ ' export.log one line per object: exported, or skipped and why
21
+ '
22
+ ' It changes nothing in the workfile: its own objects are named _pmx_* and deleted at the end, and each page's
23
+ ' sample is put back as it was.
24
+ '
25
+ ' Program version 1.0. pymetrix-eviews notes when a bundle comes from an older program than the one it ships.
26
+
27
+ ' ---------------------------------------------------------------------------------------------- settings
28
+ ' User attributes to export for every series (EViews has no function that lists them (verify)): names, space
29
+ ' separated, e.g. %pmx_attrs = "seasadj base_year"
30
+ %pmx_attrs = ""
31
+
32
+ ' ---------------------------------------------------------------------------------------------- the folder
33
+ %pmx_out = %0 ' the program's first argument (exec prog arg): standard
34
+ if %pmx_out = "" then
35
+ seterr "give the folder to write to: exec pymetrix_export.prg C:\work\macro-export" ' (verify: seterr)
36
+ stop
37
+ endif
38
+ if @right(%pmx_out, 1) = "\" then
39
+ %pmx_out = @left(%pmx_out, @len(%pmx_out) - 1)
40
+ endif
41
+ shell(h) mkdir "{%pmx_out}" ' (verify: shell(h) runs a command without a window; mkdir of an existing folder only warns)
42
+ shell(h) mkdir "{%pmx_out}\pages"
43
+ shell(h) mkdir "{%pmx_out}\text"
44
+ shell(h) mkdir "{%pmx_out}\objects"
45
+ shell(h) mkdir "{%pmx_out}\valmaps"
46
+
47
+ %pmx_q = @chr(34) ' a double quote (verify: @chr)
48
+ %pmx_bs = "\"
49
+ %pmx_wf = @lower(@wfname) ' (verify: @wfname)
50
+ %pmx_wfpath = @wfpath ' (verify: @wfpath gives the folder the workfile was opened from)
51
+ %pmx_start_page = @pagename ' (verify: @pagename)
52
+
53
+ text _pmx_json ' the manifest, a line at a time (verify: text objects and .append)
54
+ text _pmx_log
55
+
56
+ ' ---------------------------------------------------------------------------------------------- JSON strings
57
+ ' %pmx_s in, %pmx_j out: the text as a JSON string, with its quotes. Backslash first, then the double quote, then
58
+ ' the control characters a label could hold. (verify: global subroutines see the program's % variables)
59
+ subroutine pmx_json(string %pmx_in)
60
+ %pmx_t = @replace(%pmx_in, %pmx_bs, %pmx_bs + %pmx_bs) ' (verify: @replace replaces every occurrence)
61
+ %pmx_t = @replace(%pmx_t, %pmx_q, %pmx_bs + %pmx_q)
62
+ %pmx_t = @replace(%pmx_t, @chr(13), %pmx_bs + "r")
63
+ %pmx_t = @replace(%pmx_t, @chr(10), %pmx_bs + "n")
64
+ %pmx_t = @replace(%pmx_t, @chr(9), %pmx_bs + "t")
65
+ %pmx_j = %pmx_q + %pmx_t + %pmx_q
66
+ endsub
67
+
68
+ ' a number as JSON: full precision, NA as null (verify: the "g.17" format keeps 17 significant digits)
69
+ subroutine pmx_num(scalar !pmx_x)
70
+ if @isna(!pmx_x) then
71
+ %pmx_n = "null"
72
+ else
73
+ %pmx_n = @str(!pmx_x, "g.17")
74
+ endif
75
+ endsub
76
+
77
+ ' ---------------------------------------------------------------------------------------------- the header
78
+ call pmx_json(@ver) ' (verify: @ver gives the EViews version as text)
79
+ %pmx_ver = %pmx_j
80
+ call pmx_json(@strnow("YYYY-MM-DD") + "T" + @strnow("HH:MI:SS")) ' (verify: @strnow and its format letters)
81
+ %pmx_now = %pmx_j
82
+ call pmx_json(%pmx_wf)
83
+ %pmx_wfj = %pmx_j
84
+ call pmx_json(%pmx_wfpath)
85
+ %pmx_wfpj = %pmx_j
86
+ call pmx_json(@lower(%pmx_start_page))
87
+ %pmx_apj = %pmx_j
88
+
89
+ _pmx_json.append {
90
+ _pmx_json.append "format": "pymetrix-eviews-bundle",
91
+ _pmx_json.append "format_version": 1,
92
+ _pmx_json.append "exporter": {"program_version": "1.0", "eviews_version": {%pmx_ver}, "exported": {%pmx_now}},
93
+ _pmx_json.append "workfile": {"name": {%pmx_wfj}, "path": {%pmx_wfpj}, "active_page": {%pmx_apj}},
94
+ _pmx_json.append "na": "NA",
95
+ _pmx_json.append "pages": [
96
+ ' (verify: .append writes the rest of the line as it is, braces and quotes included; if it does not, build each
97
+ ' line in a % variable and append that)
98
+
99
+ ' ---------------------------------------------------------------------------------------------- page by page
100
+ %pmx_pages = @pagelist ' (verify: @pagelist, the workfile's pages separated by spaces)
101
+ for !pmx_p = 1 to @wcount(%pmx_pages)
102
+ %pmx_pg = @word(%pmx_pages, !pmx_p)
103
+ %pmx_pgl = @lower(%pmx_pg)
104
+ pageselect {%pmx_pg}
105
+ %pmx_oldsmpl = @pagesmpl ' the page's current sample, put back below (verify: @pagesmpl)
106
+ smpl @all
107
+ shell(h) mkdir "{%pmx_out}\text\{%pmx_pgl}"
108
+ shell(h) mkdir "{%pmx_out}\objects\{%pmx_pgl}"
109
+ shell(h) mkdir "{%pmx_out}\valmaps\{%pmx_pgl}"
110
+
111
+ ' the structure and frequency: "U" undated; otherwise A, Q, M, W, D5, D7, ... as EViews names them
112
+ %pmx_freq = @pagefreq ' (verify: @pagefreq, and the codes it gives for weekly and the daily frequencies)
113
+ if %pmx_freq = "U" then
114
+ %pmx_struct = "undated"
115
+ else
116
+ %pmx_struct = "dated"
117
+ endif
118
+ if @ispanel then ' (verify: @ispanel)
119
+ %pmx_struct = "panel"
120
+ endif
121
+
122
+ ' the date and id columns, made here and deleted at the end of the page
123
+ %pmx_datecol = ""
124
+ %pmx_ids = ""
125
+ if %pmx_struct <> "undated" then
126
+ %pmx_datecol = "pmx_date"
127
+ if @isobject(%pmx_datecol) then
128
+ %pmx_datecol = "pmx_date_" ' the user's own object of that name is left alone
129
+ endif
130
+ alpha {%pmx_datecol} = @datestr(@date, "YYYY-MM-DD") ' the first day of each period (verify: @date, @datestr's format)
131
+ endif
132
+ if %pmx_struct = "panel" then
133
+ %pmx_ids = "pmx_crossid"
134
+ series {%pmx_ids} = @crossid ' the cross-section number (verify: @crossid)
135
+ endif
136
+ if %pmx_struct = "undated" then
137
+ %pmx_ids = "pmx_obs"
138
+ series {%pmx_ids} = @obsnum ' (verify: @obsnum)
139
+ endif
140
+
141
+ ' the series and alpha series, page CSV first
142
+ %pmx_ser = @wlookup("*", "series") ' (verify: @wlookup's type names)
143
+ %pmx_alp = @wlookup("*", "alpha")
144
+ %pmx_cols = %pmx_datecol + " " + %pmx_ids
145
+ for !pmx_i = 1 to @wcount(%pmx_ser)
146
+ %pmx_o = @word(%pmx_ser, !pmx_i)
147
+ if @lower(%pmx_o) <> @lower(%pmx_ids) then
148
+ %pmx_cols = %pmx_cols + " " + %pmx_o
149
+ endif
150
+ next
151
+ for !pmx_i = 1 to @wcount(%pmx_alp)
152
+ %pmx_o = @word(%pmx_alp, !pmx_i)
153
+ if @lower(%pmx_o) <> @lower(%pmx_datecol) then
154
+ %pmx_cols = %pmx_cols + " " + %pmx_o
155
+ endif
156
+ next
157
+ ' (verify: pagesave's text options: the delimiter, the NA string, numbers at full precision, alpha values in
158
+ ' quotes, one header row of names, no extra date column of EViews's own, and @keep of series and alpha series only;
159
+ ' and that link and frml series are written with their values)
160
+ pagesave(type=text, delim=",", na="NA") "{%pmx_out}\pages\{%pmx_pgl}.csv" @keep {%pmx_cols} @smpl @all
161
+ _pmx_log.append {%pmx_pg}: page written to pages\{%pmx_pgl}.csv
162
+
163
+ call pmx_json(%pmx_pgl)
164
+ %pmx_pgj = %pmx_j
165
+ call pmx_json(%pmx_oldsmpl)
166
+ %pmx_smj = %pmx_j
167
+ call pmx_json(@otod(1)) ' (verify: @otod gives the date of an observation, as EViews writes dates)
168
+ %pmx_r1 = %pmx_j
169
+ call pmx_json(@otod(@obsrange)) ' (verify: @obsrange)
170
+ %pmx_r2 = %pmx_j
171
+ if !pmx_p > 1 then
172
+ _pmx_json.append ,
173
+ endif
174
+ _pmx_json.append {
175
+ _pmx_json.append "name": {%pmx_pgj}, "structure": "{%pmx_struct}", "frequency": "{%pmx_freq}",
176
+ _pmx_json.append "range": [{%pmx_r1}, {%pmx_r2}], "sample": {%pmx_smj}, "file": "pages/{%pmx_pgl}.csv",
177
+ if %pmx_datecol = "" then
178
+ _pmx_json.append "date_column": null,
179
+ else
180
+ _pmx_json.append "date_column": "{%pmx_datecol}",
181
+ endif
182
+ if %pmx_ids = "" then
183
+ _pmx_json.append "id_columns": [],
184
+ else
185
+ _pmx_json.append "id_columns": ["{%pmx_ids}"],
186
+ endif
187
+
188
+ ' each series: its kind and descriptive members
189
+ _pmx_json.append "series": [
190
+ !pmx_first = 1
191
+ for !pmx_k = 1 to 2
192
+ if !pmx_k = 1 then
193
+ %pmx_list = %pmx_ser
194
+ %pmx_kind = "numeric"
195
+ else
196
+ %pmx_list = %pmx_alp
197
+ %pmx_kind = "alpha"
198
+ endif
199
+ for !pmx_i = 1 to @wcount(%pmx_list)
200
+ %pmx_o = @word(%pmx_list, !pmx_i)
201
+ if @lower(%pmx_o) = @lower(%pmx_datecol) or @lower(%pmx_o) = @lower(%pmx_ids) then
202
+ next ' (verify: "next" inside an if skips to the next pass; if not, wrap the rest in an else)
203
+ endif
204
+ call pmx_json(@lower(%pmx_o))
205
+ %pmx_line = "{""name"": " + %pmx_j + ", ""kind"": ""{%pmx_kind}"""
206
+ ' (verify: "" inside a string literal is a double quote; if not, build these with %pmx_q)
207
+ call pmx_json({%pmx_o}.@displayname) ' (verify: the data members @displayname, @description, @units,
208
+ %pmx_line = %pmx_line + ", ""display_name"": " + %pmx_j ' @source and @remarks, and in which versions)
209
+ call pmx_json({%pmx_o}.@description)
210
+ %pmx_line = %pmx_line + ", ""description"": " + %pmx_j
211
+ call pmx_json({%pmx_o}.@units)
212
+ %pmx_line = %pmx_line + ", ""units"": " + %pmx_j
213
+ call pmx_json({%pmx_o}.@source)
214
+ %pmx_line = %pmx_line + ", ""source"": " + %pmx_j
215
+ call pmx_json({%pmx_o}.@remarks)
216
+ %pmx_line = %pmx_line + ", ""remarks"": " + %pmx_j
217
+ %pmx_line = %pmx_line + ", ""attributes"": {"
218
+ for !pmx_a = 1 to @wcount(%pmx_attrs)
219
+ %pmx_an = @word(%pmx_attrs, !pmx_a)
220
+ call pmx_json({%pmx_o}.@attr(%pmx_an)) ' (verify: .@attr("name"))
221
+ %pmx_aj = %pmx_j
222
+ call pmx_json(%pmx_an)
223
+ if !pmx_a > 1 then
224
+ %pmx_line = %pmx_line + ", "
225
+ endif
226
+ %pmx_line = %pmx_line + %pmx_j + ": " + %pmx_aj
227
+ next
228
+ %pmx_line = %pmx_line + "}"
229
+ %pmx_vm = {%pmx_o}.@map ' the value map attached to the series, if any (verify: how to read it)
230
+ if %pmx_vm = "" then
231
+ %pmx_line = %pmx_line + ", ""value_map"": null}"
232
+ else
233
+ call pmx_json(@lower(%pmx_vm))
234
+ %pmx_line = %pmx_line + ", ""value_map"": " + %pmx_j + "}"
235
+ endif
236
+ if !pmx_first = 0 then
237
+ %pmx_line = ", " + %pmx_line
238
+ endif
239
+ !pmx_first = 0
240
+ _pmx_json.append {%pmx_line}
241
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: {%pmx_kind} series exported
242
+ next
243
+ next
244
+ _pmx_json.append ],
245
+
246
+ ' groups: their members (verify: @members)
247
+ _pmx_json.append "groups": [
248
+ %pmx_list = @wlookup("*", "group")
249
+ for !pmx_i = 1 to @wcount(%pmx_list)
250
+ %pmx_o = @word(%pmx_list, !pmx_i)
251
+ call pmx_json(@lower(%pmx_o))
252
+ %pmx_line = "{""name"": " + %pmx_j + ", ""members"": ["
253
+ %pmx_mem = {%pmx_o}.@members
254
+ for !pmx_m = 1 to @wcount(%pmx_mem)
255
+ call pmx_json(@lower(@word(%pmx_mem, !pmx_m)))
256
+ if !pmx_m > 1 then
257
+ %pmx_line = %pmx_line + ", "
258
+ endif
259
+ %pmx_line = %pmx_line + %pmx_j
260
+ next
261
+ %pmx_line = %pmx_line + "]}"
262
+ if !pmx_i > 1 then
263
+ %pmx_line = ", " + %pmx_line
264
+ endif
265
+ _pmx_json.append {%pmx_line}
266
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: group exported
267
+ next
268
+ _pmx_json.append ],
269
+
270
+ ' samples: their text (verify: how a sample object gives its text; @smpl is assumed)
271
+ _pmx_json.append "samples": [
272
+ %pmx_list = @wlookup("*", "sample")
273
+ for !pmx_i = 1 to @wcount(%pmx_list)
274
+ %pmx_o = @word(%pmx_list, !pmx_i)
275
+ call pmx_json(@lower(%pmx_o))
276
+ %pmx_line = "{""name"": " + %pmx_j
277
+ call pmx_json({%pmx_o}.@smpl)
278
+ %pmx_line = %pmx_line + ", ""text"": " + %pmx_j + "}"
279
+ if !pmx_i > 1 then
280
+ %pmx_line = ", " + %pmx_line
281
+ endif
282
+ _pmx_json.append {%pmx_line}
283
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: sample exported
284
+ next
285
+ _pmx_json.append ],
286
+
287
+ ' scalars and strings, in the manifest
288
+ _pmx_json.append "scalars": [
289
+ %pmx_list = @wlookup("*", "scalar")
290
+ for !pmx_i = 1 to @wcount(%pmx_list)
291
+ %pmx_o = @word(%pmx_list, !pmx_i)
292
+ call pmx_json(@lower(%pmx_o))
293
+ call pmx_num({%pmx_o})
294
+ %pmx_line = "{""name"": " + %pmx_j + ", ""value"": " + %pmx_n + "}"
295
+ if !pmx_i > 1 then
296
+ %pmx_line = ", " + %pmx_line
297
+ endif
298
+ _pmx_json.append {%pmx_line}
299
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: scalar exported
300
+ next
301
+ _pmx_json.append ],
302
+ _pmx_json.append "strings": [
303
+ %pmx_list = @wlookup("*", "string")
304
+ for !pmx_i = 1 to @wcount(%pmx_list)
305
+ %pmx_o = @word(%pmx_list, !pmx_i)
306
+ call pmx_json(@lower(%pmx_o))
307
+ %pmx_line = "{""name"": " + %pmx_j
308
+ call pmx_json({%pmx_o})
309
+ %pmx_line = %pmx_line + ", ""value"": " + %pmx_j + "}"
310
+ if !pmx_i > 1 then
311
+ %pmx_line = ", " + %pmx_line
312
+ endif
313
+ _pmx_json.append {%pmx_line}
314
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: string exported
315
+ next
316
+ _pmx_json.append ],
317
+
318
+ ' vectors, matrices, sym and coef: a CSV each, one line per row, NA for missing (written cell by cell, so the
319
+ ' format is the program's own and not EViews's display)
320
+ _pmx_json.append "arrays": [
321
+ !pmx_first = 1
322
+ %pmx_types = "vector matrix sym coef"
323
+ for !pmx_k = 1 to 4
324
+ %pmx_ty = @word(%pmx_types, !pmx_k)
325
+ %pmx_list = @wlookup("*", %pmx_ty)
326
+ for !pmx_i = 1 to @wcount(%pmx_list)
327
+ %pmx_o = @word(%pmx_list, !pmx_i)
328
+ %pmx_ol = @lower(%pmx_o)
329
+ !pmx_r = @rows({%pmx_o}) ' (verify: @rows and @columns of each of the four types)
330
+ !pmx_c = @columns({%pmx_o})
331
+ text _pmx_arr
332
+ for !pmx_y = 1 to !pmx_r
333
+ %pmx_row = ""
334
+ for !pmx_x = 1 to !pmx_c
335
+ call pmx_num({%pmx_o}(!pmx_y, !pmx_x)) ' (verify: (i, j) indexing of a vector and a coef)
336
+ if %pmx_n = "null" then
337
+ %pmx_n = "NA"
338
+ endif
339
+ if !pmx_x > 1 then
340
+ %pmx_row = %pmx_row + ","
341
+ endif
342
+ %pmx_row = %pmx_row + %pmx_n
343
+ next
344
+ _pmx_arr.append {%pmx_row}
345
+ next
346
+ _pmx_arr.save "{%pmx_out}\objects\{%pmx_pgl}\{%pmx_ol}.csv" ' (verify: text.save writes the lines as they are)
347
+ delete _pmx_arr
348
+ call pmx_json(%pmx_ol)
349
+ %pmx_line = "{""name"": " + %pmx_j + ", ""type"": ""{%pmx_ty}"", ""rows"": " + @str(!pmx_r) + ", ""cols"": " + @str(!pmx_c)
350
+ %pmx_line = %pmx_line + ", ""file"": ""objects/{%pmx_pgl}/{%pmx_ol}.csv""}"
351
+ if !pmx_first = 0 then
352
+ %pmx_line = ", " + %pmx_line
353
+ endif
354
+ !pmx_first = 0
355
+ _pmx_json.append {%pmx_line}
356
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: {%pmx_ty} exported
357
+ next
358
+ next
359
+ _pmx_json.append ],
360
+
361
+ ' value maps: value,label (verify: freezing a valmap's sheet into a table and saving it as CSV gives these two
362
+ ' columns with that header; if not, write them cell by cell as the arrays are)
363
+ _pmx_json.append "value_maps": [
364
+ %pmx_list = @wlookup("*", "valmap")
365
+ for !pmx_i = 1 to @wcount(%pmx_list)
366
+ %pmx_o = @word(%pmx_list, !pmx_i)
367
+ %pmx_ol = @lower(%pmx_o)
368
+ freeze(_pmx_vt) {%pmx_o}.sheet
369
+ _pmx_vt.save(t=csv) "{%pmx_out}\valmaps\{%pmx_pgl}\{%pmx_ol}.csv"
370
+ delete _pmx_vt
371
+ call pmx_json(%pmx_ol)
372
+ %pmx_line = "{""name"": " + %pmx_j + ", ""file"": ""valmaps/{%pmx_pgl}/{%pmx_ol}.csv""}"
373
+ if !pmx_i > 1 then
374
+ %pmx_line = ", " + %pmx_line
375
+ endif
376
+ _pmx_json.append {%pmx_line}
377
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: value map exported
378
+ next
379
+ _pmx_json.append ],
380
+
381
+ ' equations: the command, method, sample and EViews's estimates (kept to compare, not imported as results)
382
+ _pmx_json.append "equations": [
383
+ %pmx_list = @wlookup("*", "equation")
384
+ for !pmx_i = 1 to @wcount(%pmx_list)
385
+ %pmx_o = @word(%pmx_list, !pmx_i)
386
+ %pmx_ol = @lower(%pmx_o)
387
+ !pmx_nc = {%pmx_o}.@ncoef
388
+ text _pmx_est
389
+ _pmx_est.append coefficient,estimate,std_error
390
+ for !pmx_y = 1 to !pmx_nc
391
+ call pmx_num({%pmx_o}.@coefs(!pmx_y))
392
+ %pmx_b = %pmx_n
393
+ call pmx_num({%pmx_o}.@stderrs(!pmx_y))
394
+ _pmx_est.append c({!pmx_y}),{%pmx_b},{%pmx_n}
395
+ next
396
+ _pmx_est.save "{%pmx_out}\objects\{%pmx_pgl}\{%pmx_ol}_est.csv"
397
+ delete _pmx_est
398
+ call pmx_json(%pmx_ol)
399
+ %pmx_line = "{""name"": " + %pmx_j
400
+ call pmx_json({%pmx_o}.@command) ' (verify: @command; a command over several lines would go to text\)
401
+ %pmx_line = %pmx_line + ", ""command"": " + %pmx_j
402
+ call pmx_json({%pmx_o}.@method) ' (verify: @method)
403
+ %pmx_line = %pmx_line + ", ""method"": " + %pmx_j
404
+ call pmx_json({%pmx_o}.@smpl) ' (verify: an equation's @smpl is its estimation sample)
405
+ %pmx_line = %pmx_line + ", ""sample"": " + %pmx_j + ", ""ncoef"": " + @str(!pmx_nc)
406
+ %pmx_line = %pmx_line + ", ""estimates"": ""objects/{%pmx_pgl}/{%pmx_ol}_est.csv""}"
407
+ if !pmx_i > 1 then
408
+ %pmx_line = ", " + %pmx_line
409
+ endif
410
+ _pmx_json.append {%pmx_line}
411
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: equation exported
412
+ next
413
+ _pmx_json.append ],
414
+
415
+ ' models: the text, as the Text view shows it (verify: freezing the text view and saving the frozen text)
416
+ _pmx_json.append "models": [
417
+ %pmx_list = @wlookup("*", "model")
418
+ for !pmx_i = 1 to @wcount(%pmx_list)
419
+ %pmx_o = @word(%pmx_list, !pmx_i)
420
+ %pmx_ol = @lower(%pmx_o)
421
+ freeze(_pmx_mt) {%pmx_o}.text
422
+ _pmx_mt.save "{%pmx_out}\text\{%pmx_pgl}\{%pmx_ol}.txt"
423
+ delete _pmx_mt
424
+ call pmx_json(%pmx_ol)
425
+ %pmx_line = "{""name"": " + %pmx_j + ", ""text"": ""text/{%pmx_pgl}/{%pmx_ol}.txt""}"
426
+ if !pmx_i > 1 then
427
+ %pmx_line = ", " + %pmx_line
428
+ endif
429
+ _pmx_json.append {%pmx_line}
430
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: model exported
431
+ next
432
+ _pmx_json.append ],
433
+
434
+ ' everything else: listed with its type (verify: @wlookup("*") lists every object, and .@type gives its type)
435
+ _pmx_json.append "skipped": [
436
+ %pmx_done = "series alpha group sample scalar string vector matrix sym coef valmap equation model"
437
+ %pmx_list = @wlookup("*")
438
+ !pmx_first = 1
439
+ for !pmx_i = 1 to @wcount(%pmx_list)
440
+ %pmx_o = @word(%pmx_list, !pmx_i)
441
+ %pmx_ty = @lower({%pmx_o}.@type)
442
+ if @wfind(%pmx_done, %pmx_ty) = 0 and @left(@lower(%pmx_o), 5) <> "_pmx_" then ' (verify: @wfind)
443
+ call pmx_json(@lower(%pmx_o))
444
+ %pmx_line = "{""name"": " + %pmx_j + ", ""type"": ""{%pmx_ty}"", ""reason"": ""objects of this type are not exported""}"
445
+ if !pmx_first = 0 then
446
+ %pmx_line = ", " + %pmx_line
447
+ endif
448
+ !pmx_first = 0
449
+ _pmx_json.append {%pmx_line}
450
+ _pmx_log.append {%pmx_pg}\{%pmx_o}: skipped ({%pmx_ty} objects are not exported)
451
+ endif
452
+ next
453
+ _pmx_json.append ]
454
+ _pmx_json.append }
455
+
456
+ ' the page as it was
457
+ if %pmx_datecol <> "" then
458
+ delete {%pmx_datecol}
459
+ endif
460
+ if %pmx_ids <> "" then
461
+ delete {%pmx_ids}
462
+ endif
463
+ smpl {%pmx_oldsmpl}
464
+ next
465
+
466
+ _pmx_json.append ]
467
+ _pmx_json.append }
468
+
469
+ ' ---------------------------------------------------------------------------------------------- the end
470
+ pageselect {%pmx_start_page}
471
+ _pmx_log.save "{%pmx_out}\export.log"
472
+ ' the manifest last: a folder without it is an incomplete export, and pymetrix refuses it
473
+ ' (verify: the encoding text.save writes; pymetrix reads UTF-8 and falls back to Windows-1252 with a note)
474
+ _pmx_json.save "{%pmx_out}\{%pmx_wf}.evbundle"
475
+ delete _pmx_json _pmx_log
476
+ statusline pymetrix bundle written to {%pmx_out}\{%pmx_wf}.evbundle