cgemod 1.2.0__tar.gz

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.
Files changed (48) hide show
  1. cgemod-1.2.0/CHANGELOG.md +40 -0
  2. cgemod-1.2.0/LICENSE +21 -0
  3. cgemod-1.2.0/MANIFEST.in +5 -0
  4. cgemod-1.2.0/PKG-INFO +304 -0
  5. cgemod-1.2.0/README.md +276 -0
  6. cgemod-1.2.0/cgemod/__init__.py +35 -0
  7. cgemod-1.2.0/cgemod/__main__.py +45 -0
  8. cgemod-1.2.0/cgemod/_util.py +151 -0
  9. cgemod-1.2.0/cgemod/app.py +121 -0
  10. cgemod-1.2.0/cgemod/appcore.py +54 -0
  11. cgemod-1.2.0/cgemod/config.py +185 -0
  12. cgemod-1.2.0/cgemod/data/cgemod_ext_reference.csv +35 -0
  13. cgemod-1.2.0/cgemod/data/cgemod_nigeria_reference.csv +149 -0
  14. cgemod-1.2.0/cgemod/data/cgemod_paneldata.csv +361 -0
  15. cgemod-1.2.0/cgemod/data/cgemod_sam3.csv +19 -0
  16. cgemod-1.2.0/cgemod/data/cgemod_sam_ext.csv +23 -0
  17. cgemod-1.2.0/cgemod/data/cgemod_survey.csv +3001 -0
  18. cgemod-1.2.0/cgemod/data/cgemod_tier2_reference.csv +28 -0
  19. cgemod-1.2.0/cgemod/data/cgemod_tsdata.csv +61 -0
  20. cgemod-1.2.0/cgemod/dynamic.py +269 -0
  21. cgemod-1.2.0/cgemod/estimate.py +553 -0
  22. cgemod-1.2.0/cgemod/latexdoc.py +288 -0
  23. cgemod-1.2.0/cgemod/model.py +1545 -0
  24. cgemod-1.2.0/cgemod/nexus.py +111 -0
  25. cgemod-1.2.0/cgemod/poverty.py +194 -0
  26. cgemod-1.2.0/cgemod/sam.py +770 -0
  27. cgemod-1.2.0/cgemod/scenario.py +244 -0
  28. cgemod-1.2.0/cgemod/ssa.py +159 -0
  29. cgemod-1.2.0/cgemod/structure.py +499 -0
  30. cgemod-1.2.0/cgemod/validate.py +258 -0
  31. cgemod-1.2.0/cgemod.egg-info/PKG-INFO +304 -0
  32. cgemod-1.2.0/cgemod.egg-info/SOURCES.txt +46 -0
  33. cgemod-1.2.0/cgemod.egg-info/dependency_links.txt +1 -0
  34. cgemod-1.2.0/cgemod.egg-info/entry_points.txt +2 -0
  35. cgemod-1.2.0/cgemod.egg-info/requires.txt +15 -0
  36. cgemod-1.2.0/cgemod.egg-info/top_level.txt +1 -0
  37. cgemod-1.2.0/examples/analysis.yaml +27 -0
  38. cgemod-1.2.0/examples/custom_equations.py +55 -0
  39. cgemod-1.2.0/examples/model_structure.py +68 -0
  40. cgemod-1.2.0/examples/new_in_1_2.py +44 -0
  41. cgemod-1.2.0/examples/nigeria.py +60 -0
  42. cgemod-1.2.0/examples/quickstart.py +31 -0
  43. cgemod-1.2.0/pyproject.toml +41 -0
  44. cgemod-1.2.0/setup.cfg +4 -0
  45. cgemod-1.2.0/tests/test_features.py +115 -0
  46. cgemod-1.2.0/tests/test_replication.py +128 -0
  47. cgemod-1.2.0/tests/test_structure.py +155 -0
  48. cgemod-1.2.0/tests/test_v12.py +263 -0
@@ -0,0 +1,40 @@
1
+ # Changes
2
+
3
+ ## 1.2.0 (24 November 2026)
4
+ - Vectorised evaluation of the model equations: 50 sectors about 8 times and 150 sectors about 9 times
5
+ faster, with identical results.
6
+ - Continuation (homotopy) for large shocks: `simulate(steps="auto" | n | None)`, `Results.path`.
7
+ - Complementarity constraints solved with the Fischer–Burmeister function: `add_complementarity`,
8
+ `minimum_wage`, `price_floor`, `capacity_limit`.
9
+ - AIDS household demand with the translog price index and exact equivalent variation (`demand="aids"`,
10
+ `ownprice=`).
11
+ - `Model.to_latex`: LaTeX documentation of the model as specified, including user extensions.
12
+ - `estimate_elasticity`: elasticity estimation with residual diagnostics and remedies for time series,
13
+ cross sections and panels; reproduces the Stata `elast` results. Example data `cgemod_tsdata.csv`,
14
+ `cgemod_paneldata.csv`.
15
+ - Household-level poverty microsimulation: `poverty(method="micro", budget=, sources=, transfers=)`.
16
+ - IFPRI Nexus SAM templates: `nexus_read`, `nexus_mapping` (8 sectors, 3 sectors, agri-food).
17
+ - Analyses described in YAML files and a command line: `cgemod run file.yaml`, `cgemod version`.
18
+ - Interactive policy app: `cgemod app` (optional dependency `cgemod[app]`).
19
+ - Sensitivity analysis and scenarios accept user parameters (`params=`).
20
+ - RAS balancing warns when it does not converge.
21
+ - `validate` reports the symmetry test as not applicable when the model has inequality constraints.
22
+ - Dashboard: readable names for the poverty rows, a note on the colours, and no "-0.00" bar labels.
23
+ - New dependencies: PyYAML and SciPy.
24
+
25
+ ## 1.1.0 (24 November 2026)
26
+ - Production trees: any nested CES/Leontief structure per activity, with factors and intermediate
27
+ commodities as inputs (`cg.nest`, `production=`, `Model.production_table`). Elasticities may be numbers,
28
+ specifications by activity, or model parameters. The default tree reproduces the standard model.
29
+ - Household demand systems: LES (default), CES (`demand="ces"`, `sigmac=`), or a user-supplied demand
30
+ function with optional exact equivalent variation.
31
+ - Named equation blocks that can be listed (`Model.equations`), replaced (`replace_equation`), dropped
32
+ (`drop_equation`) and restored (`restore_equation`); the model is checked to stay square.
33
+ - Equations and hooks can be written as text formulas, with arrays indexed by account name.
34
+ - Sensitivity analysis accepts `sigmac` and parameters added with `add_parameter` (for example nest elasticities).
35
+ - Errors raised in user equations are reported directly instead of as a failed evaluation.
36
+
37
+ ## 1.0.0 (22 November 2026)
38
+ - First release: SAM workflow, calibration and simulation of the cgemod model, closures and policy modules,
39
+ recursive dynamics, poverty microsimulation, sensitivity analysis, validation suite, scenario manager and
40
+ dashboard; reproduces the Stata cgemod reference results; user variables, hooks and equations; CES top nest.
cgemod-1.2.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Yusuf Toyin Yusuf and A. A. Kilishi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,5 @@
1
+ include README.md LICENSE CHANGELOG.md
2
+ recursive-include cgemod/data *.csv
3
+ recursive-include tests *.py
4
+ recursive-include examples *.py
5
+ recursive-include examples *.yaml
cgemod-1.2.0/PKG-INFO ADDED
@@ -0,0 +1,304 @@
1
+ Metadata-Version: 2.4
2
+ Name: cgemod
3
+ Version: 1.2.0
4
+ Summary: Computable general equilibrium (CGE) modelling from a social accounting matrix: SAM workflow, calibration, simulation, dynamics, poverty microsimulation, sensitivity analysis, validation and scenarios
5
+ Author-email: Yusuf Toyin Yusuf <ytoyinyusuf@gmail.com>, "A. A. Kilishi" <meetkilishi@yahoo.com>
6
+ License-Expression: MIT
7
+ Keywords: computable general equilibrium,CGE,social accounting matrix,SAM,economics,policy analysis,microsimulation
8
+ Classifier: Programming Language :: Python :: 3
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Intended Audience :: Science/Research
11
+ Classifier: Topic :: Scientific/Engineering
12
+ Requires-Python: >=3.9
13
+ Description-Content-Type: text/markdown
14
+ License-File: LICENSE
15
+ Requires-Dist: numpy>=1.21
16
+ Requires-Dist: pandas>=1.3
17
+ Requires-Dist: openpyxl>=3.0
18
+ Requires-Dist: pyyaml>=5.4
19
+ Requires-Dist: scipy>=1.7
20
+ Provides-Extra: plot
21
+ Requires-Dist: matplotlib>=3.4; extra == "plot"
22
+ Provides-Extra: app
23
+ Requires-Dist: streamlit>=1.20; extra == "app"
24
+ Provides-Extra: test
25
+ Requires-Dist: pytest>=7; extra == "test"
26
+ Requires-Dist: matplotlib>=3.4; extra == "test"
27
+ Dynamic: license-file
28
+
29
+ # cgemod for Python
30
+
31
+ Computable general equilibrium (CGE) modelling from a social accounting matrix (SAM). This is the Python
32
+ counterpart of the Stata package `cgemod`. It covers SAM import, aggregation, audit and balancing;
33
+ calibration and simulation of a standard open-economy CGE model in the IFPRI standard-model family
34
+ (Lofgren, Harris and Robinson 2002); recursive dynamics; poverty microsimulation; systematic sensitivity
35
+ analysis; a validation suite; and a scenario manager with an HTML dashboard.
36
+
37
+ It needs only NumPy and pandas; the Newton and Broyden solvers are built in, so no GAMS licence or external
38
+ solver is required.
39
+
40
+ ## Same model, same results as the Stata package
41
+
42
+ The equations, calibration and closures are identical to the Stata package. The test suite reproduces
43
+ every Stata reference result to within 1e-4 percentage points (in practice about 1e-8):
44
+
45
+ | Reference file (Stata package) | Cases | Results compared |
46
+ |---|---|---|
47
+ | `cgemod_ext_reference.csv` | default, fixed exchange rate, investment-driven with fixed government savings, unemployment | 4 x 34 |
48
+ | `cgemod_tier2_reference.csv` | wage curve, carbon tax, carbon tax with transfer recycling, fiscal rule, import quota, export quota, price cap | 7 cases |
49
+ | `cgemod_nigeria_reference.csv` | IFPRI 2018 Nigeria SAM (109 accounts): default, fixed exchange rate, unemployment | 3 x 148 |
50
+ | `cgemod_cert.do` (tier 3) | 6-period dynamics with GDP-growth calibration, population, public and human capital, debt; poverty paths | all values |
51
+
52
+ Results can be moved between the two languages: names follow the same pattern (`RGDP`, `X_<activity>`,
53
+ `QM_<commodity>`, `EV_<household>`), and `Results.compare()` reads the same reference files as
54
+ `cgemod compare` in Stata.
55
+
56
+ ## What the Python version adds: a model you can restructure
57
+
58
+ The Stata package fits the standard model to new data, closures and shocks. The Python version also
59
+ lets you change the model itself — its production functions, its demand system and its equations —
60
+ from your own script, without editing the package, while the solver, calibration, diagnostics,
61
+ validation suite, sensitivity analysis and scenario manager keep working on the changed model.
62
+
63
+ ### 1. Production structure: any nested CES tree
64
+
65
+ Each activity's technology is a tree of CES nodes (Leontief when sigma = 0, Cobb-Douglas when
66
+ sigma = 1) whose leaves are factors **or** intermediate commodities, so energy–capital bundles,
67
+ skill nests and material bundles are all possible:
68
+
69
+ ```python
70
+ from cgemod import nest
71
+ kle = nest("top", 0, # Leontief between KLE and other inputs
72
+ nest("KLE", "sig_kle", # elasticity held in a parameter
73
+ nest("KE", 0.3, "fcap", "celec"), # capital and electricity
74
+ nest("L", 1.5, "flab_n", "flab_p", "flab_s"),
75
+ "*factors"), # any remaining factors
76
+ "*inputs") # all other intermediates
77
+ m = cg.Model(sam, production=kle, solve=False)
78
+ m.add_parameter("sig_kle", 0.5)
79
+ m.solve_benchmark()
80
+ m.production_table() # nodes, elasticities, benchmark shares
81
+ m.simulate(pwm="cmine*1.5", params={"sig_kle": 0.9}) # change an elasticity in a scenario
82
+ cg.ssa(m, elasticities="sig_kle sigmaq", pwm="cmine*1.5") # sensitivity to your own elasticities
83
+ ```
84
+
85
+ A tree can differ by activity (`production={"aagri": tree1, "_default": tree2}`); an elasticity can be
86
+ a number, a specification such as `"0.5 aagri=0.2"`, or the name of a parameter. The default tree,
87
+ `cg.default_tree()`, is the standard model and reproduces the Stata results to 1e-8. The older options
88
+ `production="leontief"` (default) and `production="ces", sigmatop=` remain available.
89
+
90
+ ### 2. Household demand: LES, CES or your own function
91
+
92
+ `demand="les"` (default, with `frisch` and `incelas`), `demand="ces"` with `sigmac` (by household), or
93
+ any function `f(P, EH, p)` that returns consumption by good and household:
94
+
95
+ ```python
96
+ def my_demand(P, EH, p): # must reproduce benchmark consumption p["Cq0"] at P = p["Pg0"]
97
+ return p["dshare"] * EH[None, :] / P[:, None]
98
+ m = cg.Model(sam, demand=my_demand)
99
+ ```
100
+
101
+ The equivalent variation is exact for LES and CES. For a user function it is approximated with a
102
+ Laspeyres price index unless you attach an exact one (`my_demand.ev = f(Pb, Ps, EHb, EHs, p)`).
103
+
104
+ ### 3. Equations: add, replace or drop any of them
105
+
106
+ Every built-in equation block has a name (`m.equations()` lists them: zero profit, make matrix, margin
107
+ price, domestic markets, each factor market, balance of payments, savings–investment, government
108
+ savings, numeraire, quotas, price caps). You can replace a block, drop it, or add new variables and
109
+ equations, written as Python functions or as text formulas in which arrays are indexed by account name:
110
+
111
+ ```python
112
+ # the exchange rate instead of the CPI as numeraire
113
+ m.drop_equation("numeraire").add_equation("exr", "o.EXR - 1")
114
+
115
+ # a fiscal rule: government savings a fixed share of nominal GDP
116
+ m.replace_equation("government_savings", "(o.GSAV - p.GSAV0 * o.NGDP / p.NGDP0) / p.invscale")
117
+
118
+ # an output target met by an endogenous production subsidy
119
+ m.add_parameter("target", 1.0).add_variable("sub")
120
+ m.add_hook("ta['aagri'] = ta['aagri'] - v.sub")
121
+ m.add_equation("agri_target", "o.X['aagri'] / p.X0['aagri'] - p.target")
122
+ m.simulate(params={"target": 1.05})
123
+ ```
124
+
125
+ In formulas `o` holds results (X, PA, PQ, QM, QE, QINT, Fd, W, EH, Cq, YG, GSAV, CPI, EXR, NGDP, ...),
126
+ `p` parameters and `v` user variables. The model is checked to stay square. The test suite verifies
127
+ these features against cases with known answers: a closure rebuilt from text reproduces the built-in
128
+ one to 1e-8, a change of numeraire leaves all real results unchanged, a CES demand with unit elasticity
129
+ equals Cobb–Douglas, and a production tree with the default structure equals the standard model.
130
+
131
+ ### Also in the Python version
132
+
133
+ - **SAM aggregation with a mapping file**: `read_sam(..., mapping="map.csv")` or `SAM.aggregate()`
134
+ (Stata now has the same option as `samimport, map()`).
135
+ - **More SAM formats**: Excel, CSV, IFPRI `.tab`, GAMS include files (`.inc`/`.gms`) and long files with
136
+ `receiver,payer,value` columns; export to CSV, Excel (with prior, changes and an audit-log sheet),
137
+ GAMS and long format.
138
+ - **pandas results**: every table is a DataFrame; `Results.flat()` gives all results in one dictionary.
139
+ - **A self-contained HTML dashboard** for any number of scenarios, plus Excel/CSV export and graphs.
140
+
141
+ ## New in 1.2.0
142
+
143
+ ### Faster and more robust solving
144
+
145
+ - **Vectorised model evaluation.** The equations are evaluated as whole arrays instead of loops over
146
+ accounts. A 50-sector model now solves in about 0.2 seconds (1.4 before) and a 150-sector model in
147
+ about 1 second (9.8 before), with identical results. An exact sparse Jacobian was considered and not
148
+ adopted: with the evaluation vectorised, the finite-difference Jacobian is no longer the bottleneck
149
+ at the sizes used in practice, and it works automatically for user equations, hooks and production
150
+ trees, which an analytical Jacobian would not.
151
+ - **Continuation for large shocks.** `simulate(steps="auto")` (the default) solves directly and, only if
152
+ that fails, applies the shock in smaller steps from the previous solution. `steps=10` forces ten
153
+ steps; `Results.path` records them. Shocks such as a 50–60% productivity collapse in the Nigeria
154
+ model, which fail when solved directly, are solved this way.
155
+ - **Complementarity (inequality) constraints**, solved exactly with the Fischer–Burmeister function, so
156
+ regime switches need no manual closure changes:
157
+
158
+ ```python
159
+ m.minimum_wage("flab_n", 1.0) # real wage cannot fall; unemployment appears when the floor binds
160
+ m.price_floor("cagri", 1.0) # minimum support price defended by public procurement
161
+ m.capacity_limit("aelec", 1.0) # output cap; a capacity rent rations demand
162
+ m.add_complementarity("name", variable, slack) # any other constraint: variable >= 0, slack >= 0
163
+ ```
164
+
165
+ ### Model features
166
+
167
+ - **AIDS household demand** (`demand="aids"`, `ownprice=`, `incelas=`): the almost ideal demand system
168
+ with the translog price index, calibrated to budget shares, income elasticities and own-price
169
+ elasticities, with exact equivalent variation.
170
+ - **LaTeX documentation of the model** actually being solved: `m.to_latex("model.tex")` writes sets,
171
+ production trees, trade, demand, closures, every equation block (including replaced and user
172
+ equations and complementarity conditions) and the benchmark.
173
+ - **Elasticity estimation with diagnostics and remedies** (`cg.estimate_elasticity`), the Python
174
+ counterpart of Stata `cgemod elast`: Armington, CET, value-added or generic elasticities from time
175
+ series, cross sections or panels; normality, heteroskedasticity, autocorrelation, functional form,
176
+ collinearity, stability (CUSUM, sup-F with wild bootstrap), unit roots and cross-sectional
177
+ dependence; remedies (robust, Newey–West, bootstrap, structural break, cluster, Driscoll–Kraay, CCE);
178
+ and `result.spec()` to feed the estimate into `Model`. The results match the Stata `elast` log.
179
+ - **Household-level poverty microsimulation** (`poverty(..., method="micro", budget=..., sources=...)`):
180
+ each survey household's income changes with its own income sources and its cost of living with its own
181
+ budget shares, so households in the same SAM group can gain or lose differently.
182
+
183
+ ### Easier to use
184
+
185
+ - **IFPRI Nexus SAM templates**: `cg.nexus_read("..._SAM.tab", sectors="8", households="rural-urban")`
186
+ aggregates a Nexus SAM to 8 or 3 sectors or an agri-food split with built-in mappings
187
+ (`cg.nexus_mapping` to inspect or extend them).
188
+ - **Analyses written in YAML**, run without Python code: `cgemod run analysis.yaml` (see
189
+ `examples/analysis.yaml`). The file can set the SAM, options, production tree, user parameters,
190
+ variables, hooks and equations, constraints, scenarios, sensitivity analysis, poverty and outputs.
191
+ - **Interactive policy app**: `cgemod app` (or `cgemod app --sam file.tab`) opens a browser app with
192
+ sliders for tariffs, taxes, world prices, productivity, government spending and foreign savings,
193
+ closure switches, charts and Excel download. It needs `pip install "cgemod[app]"`.
194
+
195
+ ### Not yet included
196
+
197
+ Origin-differentiated Armington imports, destination-differentiated exports, the CDE demand system and
198
+ a multi-country (GTAP-type) model are planned for version 2; they need a multi-region data structure. The
199
+ instrumental-variable estimator of Stata `elast` is not ported.
200
+
201
+ ## Installation
202
+
203
+ ```bash
204
+ pip install cgemod # from PyPI
205
+ pip install "cgemod[plot]" # with matplotlib for Scenarios.graph()
206
+ pip install "cgemod[app]" # with streamlit for the policy app
207
+ pip install . # from this folder
208
+ ```
209
+
210
+ Requires Python 3.9 or later, NumPy, pandas, SciPy (for elasticity estimation), openpyxl (for Excel) and
211
+ PyYAML (for YAML analyses).
212
+ matplotlib is needed only for `Scenarios.graph()` and streamlit only for the app. Installing the package
213
+ also installs the `cgemod` command; `python -m cgemod` does the same.
214
+
215
+ ## Quick start
216
+
217
+ ```python
218
+ import cgemod as cg
219
+
220
+ sam = cg.read_sam("002_IFPRI_SAM_NGA_2018_SAM.tab", labelcol=2) # roles are detected; check them
221
+ sam.check() # identities and GDP from both sides
222
+ m = cg.Model(sam) # calibrate and replicate the benchmark
223
+ cg.check(m) # diagnostics
224
+ cg.validate(m) # Walras, homogeneity, path independence ...
225
+
226
+ r = m.simulate(tm="*0", title="Remove all tariffs")
227
+ print(r) # full report
228
+ r.macro, r.households # pandas DataFrames
229
+ r.to_excel("tariffs.xlsx")
230
+
231
+ sc = cg.Scenarios(m)
232
+ sc.define("free", tm="*0", description="All tariffs removed")
233
+ sc.define("free_fix", tm="*0", closure={"exchange": "fixed"})
234
+ sc.define("oil", pwm="coil*1.3")
235
+ sc.run()
236
+ sc.to_html("dashboard.html")
237
+
238
+ cg.ssa(m, tm="*0", elasticities="sigmava sigmaq omega sigmax", range_=0.5)
239
+ cg.dynamic(m, periods=10, labor="flab_n flab_p flab_s", capital="fcap", lgrowth=0.025, gdpgrowth=0.03, tm="*0")
240
+ ```
241
+
242
+ ## Reference
243
+
244
+ | Area | Python | Stata |
245
+ |---|---|---|
246
+ | SAM import | `read_sam`, `read_gams`, `from_long`, `SAM.from_data`, `SAM.from_frame` | `samimport`, `sam` |
247
+ | SAM restructuring | `SAM.merge`, `SAM.aggregate`, `SAM.set_roles` | `samimport, merge() map()` |
248
+ | SAM audit, balancing, monitoring | `SAM.check`, `SAM.balance` (GRAS/RAS, locked cells, weights, totals), `SAM.monitor` | `samcheck`, `sambalance`, `sammonitor` |
249
+ | SAM export | `SAM.to_csv`, `to_excel`, `to_gams`, `to_long` | `samexport` |
250
+ | Synthetic SAMs | `samgen` | `samgen` |
251
+ | Calibration | `Model(sam, **options)`, `Model.with_options` | `calibrate` |
252
+ | Simulation | `Model.simulate(**shocks)` | `sim` |
253
+ | Replication | `Results.compare` | `compare` |
254
+ | Diagnostics, validation | `check`, `validate` | `check`, `validate` |
255
+ | Sensitivity | `ssa` | `ssa` |
256
+ | Dynamics | `dynamic` | `dynamic` |
257
+ | Poverty | `poverty` (static and dynamic) | `poverty` |
258
+ | Scenarios | `Scenarios` | `scenario` |
259
+ | Production trees | `production=nest(...)`, `production_table()` | (not available) |
260
+ | Demand systems | `demand="les" \| "ces" \| "aids" \| function`, `sigmac=`, `ownprice=` | LES only |
261
+ | Inequality constraints | `minimum_wage`, `price_floor`, `capacity_limit`, `add_complementarity` | (not available) |
262
+ | Continuation | `simulate(steps=...)`, `Results.path` | (not available) |
263
+ | Model documentation | `Model.to_latex` | (not available) |
264
+ | IFPRI Nexus SAMs | `nexus_read`, `nexus_mapping` | (not available) |
265
+ | YAML analyses, app | `cgemod run file.yaml`, `cgemod app` | (not available) |
266
+ | Equations | `equations()`, `add_variable`, `add_parameter`, `add_hook`, `add_equation`, `replace_equation`, `drop_equation`, `restore_equation` | (not available) |
267
+ | CES top nest | `production="ces", sigmatop=` | (not available) |
268
+ | Elasticity estimation | `estimate_elasticity` (IV not included) | `elast` |
269
+
270
+ **Shocks** use the Stata syntax: `tm="*0"`, `tm="C_IND=0.05 C_AGR*0.5"`, `ty="+0.01"`,
271
+ `pwm="C_OIL*1.3"`, or a dict such as `{"C_IND": 0.05}`. The available shocks are `tm tq te ta ty pwm
272
+ pwe tfp fs wf gadj fsav tmsched qg gsavshare ctax mquota xquota pcap`.
273
+
274
+ **Calibration options** are the same as in Stata: `sigmava sigmaq omega sigmax frisch incelas specific
275
+ unemployed wagecurve urate elasw emissions pemissions exchange gsav fiscal siclosure solver tol
276
+ maxiter`, plus `production`, `sigmatop`, `demand`, `sigmac` and `ownprice`.
277
+
278
+ **Writing hooks.** A hook is a function or a text of assignments (`"tq = tq + v.dtq"`). A function hook receives a private copy of the parameter dictionary. Replace arrays rather than
279
+ changing them in place (`p["tq"] = p["tq"] + x`, not `p["tq"][0] += x`). Each user variable needs exactly
280
+ one equation.
281
+
282
+ ## Tests
283
+
284
+ ```bash
285
+ CGEMOD_STATA_DIR=/path/to/stata/cgemod pytest
286
+ ```
287
+
288
+ `tests/test_replication.py` checks the Python results against the Stata reference files.
289
+ `tests/test_features.py`, `tests/test_structure.py` and `tests/test_v12.py` cover the Python-only
290
+ features. Set `CGEMOD_NGA_SAM` to the IFPRI Nigeria 2018 `.tab` file to include the Nexus template tests.
291
+
292
+ ## Citation
293
+
294
+ Yusuf, Y. T., and A. A. Kilishi. 2026. cgemod: computable general equilibrium modelling in Python. Version 1.2.0.
295
+
296
+ ## Authors
297
+
298
+ Yusuf Toyin Yusuf, Department of Economics and Development Studies, Kwara State University, Malete, Nigeria. Email: ytoyinyusuf@gmail.com
299
+
300
+ A. A. Kilishi, Department of Economics, Faculty of Social Sciences, University of Ilorin, Ilorin, Nigeria. Email: meetkilishi@yahoo.com
301
+
302
+ ## Licence
303
+
304
+ MIT; see `LICENSE`.
cgemod-1.2.0/README.md ADDED
@@ -0,0 +1,276 @@
1
+ # cgemod for Python
2
+
3
+ Computable general equilibrium (CGE) modelling from a social accounting matrix (SAM). This is the Python
4
+ counterpart of the Stata package `cgemod`. It covers SAM import, aggregation, audit and balancing;
5
+ calibration and simulation of a standard open-economy CGE model in the IFPRI standard-model family
6
+ (Lofgren, Harris and Robinson 2002); recursive dynamics; poverty microsimulation; systematic sensitivity
7
+ analysis; a validation suite; and a scenario manager with an HTML dashboard.
8
+
9
+ It needs only NumPy and pandas; the Newton and Broyden solvers are built in, so no GAMS licence or external
10
+ solver is required.
11
+
12
+ ## Same model, same results as the Stata package
13
+
14
+ The equations, calibration and closures are identical to the Stata package. The test suite reproduces
15
+ every Stata reference result to within 1e-4 percentage points (in practice about 1e-8):
16
+
17
+ | Reference file (Stata package) | Cases | Results compared |
18
+ |---|---|---|
19
+ | `cgemod_ext_reference.csv` | default, fixed exchange rate, investment-driven with fixed government savings, unemployment | 4 x 34 |
20
+ | `cgemod_tier2_reference.csv` | wage curve, carbon tax, carbon tax with transfer recycling, fiscal rule, import quota, export quota, price cap | 7 cases |
21
+ | `cgemod_nigeria_reference.csv` | IFPRI 2018 Nigeria SAM (109 accounts): default, fixed exchange rate, unemployment | 3 x 148 |
22
+ | `cgemod_cert.do` (tier 3) | 6-period dynamics with GDP-growth calibration, population, public and human capital, debt; poverty paths | all values |
23
+
24
+ Results can be moved between the two languages: names follow the same pattern (`RGDP`, `X_<activity>`,
25
+ `QM_<commodity>`, `EV_<household>`), and `Results.compare()` reads the same reference files as
26
+ `cgemod compare` in Stata.
27
+
28
+ ## What the Python version adds: a model you can restructure
29
+
30
+ The Stata package fits the standard model to new data, closures and shocks. The Python version also
31
+ lets you change the model itself — its production functions, its demand system and its equations —
32
+ from your own script, without editing the package, while the solver, calibration, diagnostics,
33
+ validation suite, sensitivity analysis and scenario manager keep working on the changed model.
34
+
35
+ ### 1. Production structure: any nested CES tree
36
+
37
+ Each activity's technology is a tree of CES nodes (Leontief when sigma = 0, Cobb-Douglas when
38
+ sigma = 1) whose leaves are factors **or** intermediate commodities, so energy–capital bundles,
39
+ skill nests and material bundles are all possible:
40
+
41
+ ```python
42
+ from cgemod import nest
43
+ kle = nest("top", 0, # Leontief between KLE and other inputs
44
+ nest("KLE", "sig_kle", # elasticity held in a parameter
45
+ nest("KE", 0.3, "fcap", "celec"), # capital and electricity
46
+ nest("L", 1.5, "flab_n", "flab_p", "flab_s"),
47
+ "*factors"), # any remaining factors
48
+ "*inputs") # all other intermediates
49
+ m = cg.Model(sam, production=kle, solve=False)
50
+ m.add_parameter("sig_kle", 0.5)
51
+ m.solve_benchmark()
52
+ m.production_table() # nodes, elasticities, benchmark shares
53
+ m.simulate(pwm="cmine*1.5", params={"sig_kle": 0.9}) # change an elasticity in a scenario
54
+ cg.ssa(m, elasticities="sig_kle sigmaq", pwm="cmine*1.5") # sensitivity to your own elasticities
55
+ ```
56
+
57
+ A tree can differ by activity (`production={"aagri": tree1, "_default": tree2}`); an elasticity can be
58
+ a number, a specification such as `"0.5 aagri=0.2"`, or the name of a parameter. The default tree,
59
+ `cg.default_tree()`, is the standard model and reproduces the Stata results to 1e-8. The older options
60
+ `production="leontief"` (default) and `production="ces", sigmatop=` remain available.
61
+
62
+ ### 2. Household demand: LES, CES or your own function
63
+
64
+ `demand="les"` (default, with `frisch` and `incelas`), `demand="ces"` with `sigmac` (by household), or
65
+ any function `f(P, EH, p)` that returns consumption by good and household:
66
+
67
+ ```python
68
+ def my_demand(P, EH, p): # must reproduce benchmark consumption p["Cq0"] at P = p["Pg0"]
69
+ return p["dshare"] * EH[None, :] / P[:, None]
70
+ m = cg.Model(sam, demand=my_demand)
71
+ ```
72
+
73
+ The equivalent variation is exact for LES and CES. For a user function it is approximated with a
74
+ Laspeyres price index unless you attach an exact one (`my_demand.ev = f(Pb, Ps, EHb, EHs, p)`).
75
+
76
+ ### 3. Equations: add, replace or drop any of them
77
+
78
+ Every built-in equation block has a name (`m.equations()` lists them: zero profit, make matrix, margin
79
+ price, domestic markets, each factor market, balance of payments, savings–investment, government
80
+ savings, numeraire, quotas, price caps). You can replace a block, drop it, or add new variables and
81
+ equations, written as Python functions or as text formulas in which arrays are indexed by account name:
82
+
83
+ ```python
84
+ # the exchange rate instead of the CPI as numeraire
85
+ m.drop_equation("numeraire").add_equation("exr", "o.EXR - 1")
86
+
87
+ # a fiscal rule: government savings a fixed share of nominal GDP
88
+ m.replace_equation("government_savings", "(o.GSAV - p.GSAV0 * o.NGDP / p.NGDP0) / p.invscale")
89
+
90
+ # an output target met by an endogenous production subsidy
91
+ m.add_parameter("target", 1.0).add_variable("sub")
92
+ m.add_hook("ta['aagri'] = ta['aagri'] - v.sub")
93
+ m.add_equation("agri_target", "o.X['aagri'] / p.X0['aagri'] - p.target")
94
+ m.simulate(params={"target": 1.05})
95
+ ```
96
+
97
+ In formulas `o` holds results (X, PA, PQ, QM, QE, QINT, Fd, W, EH, Cq, YG, GSAV, CPI, EXR, NGDP, ...),
98
+ `p` parameters and `v` user variables. The model is checked to stay square. The test suite verifies
99
+ these features against cases with known answers: a closure rebuilt from text reproduces the built-in
100
+ one to 1e-8, a change of numeraire leaves all real results unchanged, a CES demand with unit elasticity
101
+ equals Cobb–Douglas, and a production tree with the default structure equals the standard model.
102
+
103
+ ### Also in the Python version
104
+
105
+ - **SAM aggregation with a mapping file**: `read_sam(..., mapping="map.csv")` or `SAM.aggregate()`
106
+ (Stata now has the same option as `samimport, map()`).
107
+ - **More SAM formats**: Excel, CSV, IFPRI `.tab`, GAMS include files (`.inc`/`.gms`) and long files with
108
+ `receiver,payer,value` columns; export to CSV, Excel (with prior, changes and an audit-log sheet),
109
+ GAMS and long format.
110
+ - **pandas results**: every table is a DataFrame; `Results.flat()` gives all results in one dictionary.
111
+ - **A self-contained HTML dashboard** for any number of scenarios, plus Excel/CSV export and graphs.
112
+
113
+ ## New in 1.2.0
114
+
115
+ ### Faster and more robust solving
116
+
117
+ - **Vectorised model evaluation.** The equations are evaluated as whole arrays instead of loops over
118
+ accounts. A 50-sector model now solves in about 0.2 seconds (1.4 before) and a 150-sector model in
119
+ about 1 second (9.8 before), with identical results. An exact sparse Jacobian was considered and not
120
+ adopted: with the evaluation vectorised, the finite-difference Jacobian is no longer the bottleneck
121
+ at the sizes used in practice, and it works automatically for user equations, hooks and production
122
+ trees, which an analytical Jacobian would not.
123
+ - **Continuation for large shocks.** `simulate(steps="auto")` (the default) solves directly and, only if
124
+ that fails, applies the shock in smaller steps from the previous solution. `steps=10` forces ten
125
+ steps; `Results.path` records them. Shocks such as a 50–60% productivity collapse in the Nigeria
126
+ model, which fail when solved directly, are solved this way.
127
+ - **Complementarity (inequality) constraints**, solved exactly with the Fischer–Burmeister function, so
128
+ regime switches need no manual closure changes:
129
+
130
+ ```python
131
+ m.minimum_wage("flab_n", 1.0) # real wage cannot fall; unemployment appears when the floor binds
132
+ m.price_floor("cagri", 1.0) # minimum support price defended by public procurement
133
+ m.capacity_limit("aelec", 1.0) # output cap; a capacity rent rations demand
134
+ m.add_complementarity("name", variable, slack) # any other constraint: variable >= 0, slack >= 0
135
+ ```
136
+
137
+ ### Model features
138
+
139
+ - **AIDS household demand** (`demand="aids"`, `ownprice=`, `incelas=`): the almost ideal demand system
140
+ with the translog price index, calibrated to budget shares, income elasticities and own-price
141
+ elasticities, with exact equivalent variation.
142
+ - **LaTeX documentation of the model** actually being solved: `m.to_latex("model.tex")` writes sets,
143
+ production trees, trade, demand, closures, every equation block (including replaced and user
144
+ equations and complementarity conditions) and the benchmark.
145
+ - **Elasticity estimation with diagnostics and remedies** (`cg.estimate_elasticity`), the Python
146
+ counterpart of Stata `cgemod elast`: Armington, CET, value-added or generic elasticities from time
147
+ series, cross sections or panels; normality, heteroskedasticity, autocorrelation, functional form,
148
+ collinearity, stability (CUSUM, sup-F with wild bootstrap), unit roots and cross-sectional
149
+ dependence; remedies (robust, Newey–West, bootstrap, structural break, cluster, Driscoll–Kraay, CCE);
150
+ and `result.spec()` to feed the estimate into `Model`. The results match the Stata `elast` log.
151
+ - **Household-level poverty microsimulation** (`poverty(..., method="micro", budget=..., sources=...)`):
152
+ each survey household's income changes with its own income sources and its cost of living with its own
153
+ budget shares, so households in the same SAM group can gain or lose differently.
154
+
155
+ ### Easier to use
156
+
157
+ - **IFPRI Nexus SAM templates**: `cg.nexus_read("..._SAM.tab", sectors="8", households="rural-urban")`
158
+ aggregates a Nexus SAM to 8 or 3 sectors or an agri-food split with built-in mappings
159
+ (`cg.nexus_mapping` to inspect or extend them).
160
+ - **Analyses written in YAML**, run without Python code: `cgemod run analysis.yaml` (see
161
+ `examples/analysis.yaml`). The file can set the SAM, options, production tree, user parameters,
162
+ variables, hooks and equations, constraints, scenarios, sensitivity analysis, poverty and outputs.
163
+ - **Interactive policy app**: `cgemod app` (or `cgemod app --sam file.tab`) opens a browser app with
164
+ sliders for tariffs, taxes, world prices, productivity, government spending and foreign savings,
165
+ closure switches, charts and Excel download. It needs `pip install "cgemod[app]"`.
166
+
167
+ ### Not yet included
168
+
169
+ Origin-differentiated Armington imports, destination-differentiated exports, the CDE demand system and
170
+ a multi-country (GTAP-type) model are planned for version 2; they need a multi-region data structure. The
171
+ instrumental-variable estimator of Stata `elast` is not ported.
172
+
173
+ ## Installation
174
+
175
+ ```bash
176
+ pip install cgemod # from PyPI
177
+ pip install "cgemod[plot]" # with matplotlib for Scenarios.graph()
178
+ pip install "cgemod[app]" # with streamlit for the policy app
179
+ pip install . # from this folder
180
+ ```
181
+
182
+ Requires Python 3.9 or later, NumPy, pandas, SciPy (for elasticity estimation), openpyxl (for Excel) and
183
+ PyYAML (for YAML analyses).
184
+ matplotlib is needed only for `Scenarios.graph()` and streamlit only for the app. Installing the package
185
+ also installs the `cgemod` command; `python -m cgemod` does the same.
186
+
187
+ ## Quick start
188
+
189
+ ```python
190
+ import cgemod as cg
191
+
192
+ sam = cg.read_sam("002_IFPRI_SAM_NGA_2018_SAM.tab", labelcol=2) # roles are detected; check them
193
+ sam.check() # identities and GDP from both sides
194
+ m = cg.Model(sam) # calibrate and replicate the benchmark
195
+ cg.check(m) # diagnostics
196
+ cg.validate(m) # Walras, homogeneity, path independence ...
197
+
198
+ r = m.simulate(tm="*0", title="Remove all tariffs")
199
+ print(r) # full report
200
+ r.macro, r.households # pandas DataFrames
201
+ r.to_excel("tariffs.xlsx")
202
+
203
+ sc = cg.Scenarios(m)
204
+ sc.define("free", tm="*0", description="All tariffs removed")
205
+ sc.define("free_fix", tm="*0", closure={"exchange": "fixed"})
206
+ sc.define("oil", pwm="coil*1.3")
207
+ sc.run()
208
+ sc.to_html("dashboard.html")
209
+
210
+ cg.ssa(m, tm="*0", elasticities="sigmava sigmaq omega sigmax", range_=0.5)
211
+ cg.dynamic(m, periods=10, labor="flab_n flab_p flab_s", capital="fcap", lgrowth=0.025, gdpgrowth=0.03, tm="*0")
212
+ ```
213
+
214
+ ## Reference
215
+
216
+ | Area | Python | Stata |
217
+ |---|---|---|
218
+ | SAM import | `read_sam`, `read_gams`, `from_long`, `SAM.from_data`, `SAM.from_frame` | `samimport`, `sam` |
219
+ | SAM restructuring | `SAM.merge`, `SAM.aggregate`, `SAM.set_roles` | `samimport, merge() map()` |
220
+ | SAM audit, balancing, monitoring | `SAM.check`, `SAM.balance` (GRAS/RAS, locked cells, weights, totals), `SAM.monitor` | `samcheck`, `sambalance`, `sammonitor` |
221
+ | SAM export | `SAM.to_csv`, `to_excel`, `to_gams`, `to_long` | `samexport` |
222
+ | Synthetic SAMs | `samgen` | `samgen` |
223
+ | Calibration | `Model(sam, **options)`, `Model.with_options` | `calibrate` |
224
+ | Simulation | `Model.simulate(**shocks)` | `sim` |
225
+ | Replication | `Results.compare` | `compare` |
226
+ | Diagnostics, validation | `check`, `validate` | `check`, `validate` |
227
+ | Sensitivity | `ssa` | `ssa` |
228
+ | Dynamics | `dynamic` | `dynamic` |
229
+ | Poverty | `poverty` (static and dynamic) | `poverty` |
230
+ | Scenarios | `Scenarios` | `scenario` |
231
+ | Production trees | `production=nest(...)`, `production_table()` | (not available) |
232
+ | Demand systems | `demand="les" \| "ces" \| "aids" \| function`, `sigmac=`, `ownprice=` | LES only |
233
+ | Inequality constraints | `minimum_wage`, `price_floor`, `capacity_limit`, `add_complementarity` | (not available) |
234
+ | Continuation | `simulate(steps=...)`, `Results.path` | (not available) |
235
+ | Model documentation | `Model.to_latex` | (not available) |
236
+ | IFPRI Nexus SAMs | `nexus_read`, `nexus_mapping` | (not available) |
237
+ | YAML analyses, app | `cgemod run file.yaml`, `cgemod app` | (not available) |
238
+ | Equations | `equations()`, `add_variable`, `add_parameter`, `add_hook`, `add_equation`, `replace_equation`, `drop_equation`, `restore_equation` | (not available) |
239
+ | CES top nest | `production="ces", sigmatop=` | (not available) |
240
+ | Elasticity estimation | `estimate_elasticity` (IV not included) | `elast` |
241
+
242
+ **Shocks** use the Stata syntax: `tm="*0"`, `tm="C_IND=0.05 C_AGR*0.5"`, `ty="+0.01"`,
243
+ `pwm="C_OIL*1.3"`, or a dict such as `{"C_IND": 0.05}`. The available shocks are `tm tq te ta ty pwm
244
+ pwe tfp fs wf gadj fsav tmsched qg gsavshare ctax mquota xquota pcap`.
245
+
246
+ **Calibration options** are the same as in Stata: `sigmava sigmaq omega sigmax frisch incelas specific
247
+ unemployed wagecurve urate elasw emissions pemissions exchange gsav fiscal siclosure solver tol
248
+ maxiter`, plus `production`, `sigmatop`, `demand`, `sigmac` and `ownprice`.
249
+
250
+ **Writing hooks.** A hook is a function or a text of assignments (`"tq = tq + v.dtq"`). A function hook receives a private copy of the parameter dictionary. Replace arrays rather than
251
+ changing them in place (`p["tq"] = p["tq"] + x`, not `p["tq"][0] += x`). Each user variable needs exactly
252
+ one equation.
253
+
254
+ ## Tests
255
+
256
+ ```bash
257
+ CGEMOD_STATA_DIR=/path/to/stata/cgemod pytest
258
+ ```
259
+
260
+ `tests/test_replication.py` checks the Python results against the Stata reference files.
261
+ `tests/test_features.py`, `tests/test_structure.py` and `tests/test_v12.py` cover the Python-only
262
+ features. Set `CGEMOD_NGA_SAM` to the IFPRI Nigeria 2018 `.tab` file to include the Nexus template tests.
263
+
264
+ ## Citation
265
+
266
+ Yusuf, Y. T., and A. A. Kilishi. 2026. cgemod: computable general equilibrium modelling in Python. Version 1.2.0.
267
+
268
+ ## Authors
269
+
270
+ Yusuf Toyin Yusuf, Department of Economics and Development Studies, Kwara State University, Malete, Nigeria. Email: ytoyinyusuf@gmail.com
271
+
272
+ A. A. Kilishi, Department of Economics, Faculty of Social Sciences, University of Ilorin, Ilorin, Nigeria. Email: meetkilishi@yahoo.com
273
+
274
+ ## Licence
275
+
276
+ MIT; see `LICENSE`.