Computational Lab: EIA State Residential Electricity Panel¶
Course: Y1-04 Applied Quantitative Methods for Energy Research
Public dataset: U.S. Energy Information Administration (EIA), Open Data API v2, route electricity/retail-sales (annual state totals built from Forms EIA-861 and EIA-861M)
Fallback dataset: a deterministic synthetic panel with a known data-generating process, used by the tests, CI and any run without a downloaded extract
Purpose: an end-to-end empirical workflow (acquire, audit, describe, model, diagnose, predict, report) that keeps association, prediction and causal claims apart.
No real EIA data is committed to this repository. Everything under outputs/ is regenerated on each run, and any output built from the synthetic panel carries the banner SYNTHETIC TEACHING DATA: NOT EVIDENCE ABOUT ANY REAL STATE.
Research question¶
Across U.S. states and years, how does average residential electricity use per customer co-move with the average residential price, once nationwide year-to-year shocks (inflation, fuel prices, weather years, efficiency standards) are removed?
This is a descriptive and associational question. It is not "what is the price elasticity of residential electricity demand?" That causal question needs a source of price variation unrelated to demand, which this design does not have (see Association, prediction and causation).
Unit of observation and population¶
- Unit of observation: a state-year (50 states plus DC; 2001 to 2023 by default), residential sector only.
- Population: all residential retail electricity sales reported to EIA for those state-years. EIA's national (
US) and census-division rows (NEW,MAT,ENC, ...) are sums of states and are dropped so they cannot enter as extra units. - Not the unit: a utility, a household or a feeder. State averages mix utilities, rate designs and customer types; nothing here supports claims about any single utility or household.
Estimands and equations¶
Write y[s,t] = log(kWh per customer) and p[s,t] = log(average price, cents/kWh) for state s in year t.
M1 pooled: y[s,t] = a + b1 * p[s,t] + u[s,t]
M2 year FE: y[s,t] = b2 * p[s,t] + lambda[t] + u[s,t] (main)
M3 two-way FE: y[s,t] = b3 * p[s,t] + mu[s] + lambda[t] + u[s,t]
| Model | Coefficient describes |
|---|---|
| M1 pooled | raw log-log association, mixing cross-state and over-time variation and common inflation |
| M2 year FE (main) | association net of anything common to all states in a year |
| M3 two-way FE | within-state association: years when a state is pricier than its own average and the national year |
Primary estimand (b2): the slope of the linear projection of y on p after removing year means, in the population of state-years defined above. By Frisch-Waugh-Lovell,
b2 = sum over (s,t) of p~[s,t] * y~[s,t] / sum over (s,t) of p~[s,t]^2,
where x~[s,t] = x[s,t] - (mean of x over states in year t),
which the tests check against the regression. The default is unweighted (each state-year counts once); the customer-weighted version, which describes the average customer instead of the average state, is reported as a sensitivity case.
Inference. The sampling unit for dependence is the state: a state's residuals are strongly serially correlated. Standard errors are therefore clustered by state (51 clusters, statsmodels' CR1 small-sample correction), and 95% intervals use a t distribution with G - 1 = 50 degrees of freedom. Conventional and HC3 standard errors are printed beside them so the learner can see how much the choice matters. In M3 the state dummies are nested within clusters, so CR1's (N - 1)/(N - K) factor counts them and makes the M3 interval slightly conservative (the Stata areg versus xtreg issue).
Data dictionary¶
One row per state-year in outputs/<source>/panel.csv (the full panel, including rows dropped from models). Units are as listed; prices and revenues are nominal dollars.
| Column | Type | Units | Definition |
|---|---|---|---|
state |
string | Two-letter postal code (public) or S01..S51 (synthetic) |
|
year |
integer | calendar year | EIA period |
customers |
float | count | Residential customer accounts, EIA customers (number of customers) |
sales_mwh |
float | MWh | Residential retail sales, EIA sales (million kilowatt hours) times 1000 |
revenue_million_usd |
float | million nominal USD | Residential retail revenue, EIA revenue (million dollars) |
price_cents_per_kwh |
float | nominal cents/kWh | Average revenue per kWh, EIA price (cents per kilowatt-hour); not a marginal tariff rate |
kwh_per_customer |
float | kWh per account per year | sales_mwh * 1000 / customers |
log_kwh_per_customer |
float | log kWh | Outcome y[s,t] |
log_price |
float | log cents/kWh | Regressor p[s,t] |
revenue_identity_gap |
float | fraction | (revenue - price * sales) / revenue; should be near zero because EIA price is revenue over sales |
source |
string | eia_api_v2 or synthetic |
Missing source values (null, blank, NA, NM, W, --) stay missing; they are never coded as zero. The parser refuses records whose declared units differ from the table above, duplicate state-year keys, and non-positive values.
Provenance¶
- Source: EIA Open Data API v2,
https://api.eia.gov/v2/electricity/retail-sales/data/, documentation at eia.gov/opendata. EIA data are public-domain U.S. government information; cite EIA as the source. - Request:
frequency=annual,data[]=customers,price,revenue,sales,facets[sectorid][]=RES,start=2001,end=2023, sorted by period then state, paged at the API maximum of 5000 rows. - Raw cache:
acquire.pystores each response page verbatim asdata/raw/page_NNN.jsonand writesdata/raw/manifest.jsonwith the request, retrieval time, each page's URL (API key replaced byREDACTED), row count and SHA-256. A rerun reuses the cache only when the request matches and every hash still verifies.data/raw/is git-ignored: the extract is reproducible from the script, not committed. - Test fixture:
fixtures/eia_api_v2_retail_sales_fixture.jsonis a hand-made fixture in the API v2 response shape. Its values are invented (its own_notefield says so) and it is not an EIA response. It holds edge cases on purpose: a thousands separator, a state-year with null and blank values, aUStotal, a census-division row and a commercial-sector row. - Synthetic panel:
data/synthetic_state_panel.csvis produced bypanel.generate_synthetic_panel()with a fixed seed; the tests regenerate it and require an exact match. Regenerate withpython run.py --write-synthetic.
Run¶
python -m pip install -r requirements.txt
python -m unittest discover -s . -p "test_*.py" -v
python run.py --source synthetic --output-dir outputs/synthetic
requirements.txt pins exact versions (the environment CI tests on Python 3.12), so tables and the report reproduce byte for byte (a test checks this) and figures are regenerated from the same numbers.
Fetching the real EIA data¶
- Register for a free key at eia.gov/opendata/register.php.
-
Put it in the environment for this shell only. Never write it into a file in the repository, a notebook or a commit:
export EIA_API_KEY=your-key-here -
Download and cache the extract, then run the lab on it:
python acquire.py # writes data/raw/ (git-ignored) python run.py --source public # or: python run.py --source public --acquire
--source auto (the default) uses the cached public extract when data/raw/manifest.json exists and the synthetic panel otherwise. Read results.json["audit"] before any model: it reports coverage, balance, missingness by column, duplicate keys, revenue-identity failures and how many state-years were dropped for missing values. Every model, table and figure uses the same complete-case sample.
Tests and CI never touch the network: parsing is tested on the fixture, acquisition on a fake HTTP opener, and the public code path end to end on synthetic values relabelled as API-shaped records.
Outputs¶
| File | Contents |
|---|---|
report.md |
Audit line, model table, M2 diagnostics, sensitivity, prediction, and (synthetic only) the causal check |
results.json |
Everything in the report in machine-readable form, plus the full audit |
table_descriptive.csv, table_yearly.csv |
Summary statistics; customer-weighted national use and price, and cross-state dispersion, by year |
table_models.csv |
M1 to M3 coefficients with conventional, HC3 and state-clustered SEs and clustered 95% CIs |
table_sensitivity.csv, table_leave_one_state_out.csv |
Weighted, split-period and leave-one-state-out estimates of b2 |
fig1 to fig6 |
Latest-year cross-section, national trends, residuals vs fitted, residual Q-Q, within-state variation behind M3, leave-one-state-out histogram |
Diagnostics on M2: Breusch-Pagan (heteroskedasticity), RESET with squared and cubed fitted values (functional form), Jarque-Bera (residual normality), within-state residual AR(1) (the reason to cluster), Cook's distance against 4/n, and the condition number of the regressors.
Association, prediction and causation¶
- Association. The estimate of
b2summarizes how use and price co-move across state-years after year effects. It is a fact about this population of state-years, with uncertainty from treating the 51 states as draws from a superpopulation of similar units. - Prediction. Five-fold cross-validation with folds that never split a state asks how well year effects plus log price predict use for a state the model has not seen, compared with year means alone. Good out-of-sample fit says nothing about why use and price move together.
- Causation. The own-price elasticity of demand is a different estimand: the change in use if price alone were changed. It is not identified here, for at least three reasons. Fixed state traits (electric heating share, climate, housing stock) shift both price and use; prices respond to demand because fixed utility costs are spread over sales; and the regressor is an average price, not the marginal price customers respond to. A credible design needs price variation unrelated to demand (for example a well-justified instrument or a rate change with a valid comparison group), which belongs to the Year 2 econometrics sequence.
The synthetic panel makes this concrete because its true causal elasticity is known. Its data-generating process builds in a fixed confounder and price feedback from demand shocks.
Results on the synthetic panel¶
These numbers describe a simulated world and are not evidence about any real state. They come from python run.py --source synthetic with the pinned environment.
| Model | Estimate | SE conventional | SE clustered by state | 95% CI (clustered) |
|---|---|---|---|---|
| M1 pooled | -0.388 | 0.015 | 0.058 | [-0.504, -0.272] |
| M2 year FE | -0.401 | 0.017 | 0.078 | [-0.558, -0.244] |
| M3 two-way FE | -0.221 | 0.017 | 0.025 | [-0.271, -0.171] |
- True causal elasticity in the generator: -0.150. M2 is off by -0.251, mostly from the fixed heating-share confounder; M3 removes that and is still off by -0.071 because prices respond to demand shocks. Both intervals exclude the truth: precise and wrong.
- Clustered SEs are 4.0 and 4.6 times the conventional ones for M1 and M2 (1.5 for M3); within-state residual AR(1) in M2 is 0.97. Conventional or HC3 intervals would be badly overconfident.
- Breusch-Pagan, RESET and Jarque-Bera all reject at 5% for M2; leave-one-state-out estimates of
b2range from -0.451 to -0.379; customer weighting moves it to -0.456. - Out-of-sample R squared rises from 0.041 (year means) to 0.306 (year FE plus log price) for held-out states, while the coefficient remains a biased estimate of the elasticity.
Tests¶
test_panel.py covers parsing (sector and aggregate filtering, unit conversion, thousands separators, missing values kept missing, unit-change, duplicate and non-positive rejection), the audit, the synthetic generator (determinism, exact match to the committed CSV, labels that cannot be mistaken for real states), and acquisition (URL contents, key redaction, pagination, cache reuse, hash invalidation, retry, refusal without a key). test_analysis.py covers exact slope recovery on noise-free data, the Frisch-Waugh-Lovell identity, two-way demeaning on an unbalanced panel, the complete-case sample, clustered versus conventional SEs, diagnostics, grouped cross-validation, sensitivity, and full runs on both the synthetic and the public code path, including byte-identical tables across reruns.
Limitations¶
- No real results are reported here. The public path has been tested on the fixture and on API-shaped synthetic records only. The first run against the live API should be checked against the audit, and the request shape should be confirmed against EIA's current API documentation.
- Average, nominal price. EIA price is revenue over sales: an average across tariffs and fixed charges, not a marginal rate, and in nominal dollars. Year effects absorb common inflation in M2 and M3; M1 does not.
- Aggregation. State totals hide utility, rate-class and household heterogeneity; customer counts are accounts, not people or dwellings. Changes in how EIA collects or imputes small respondents (Form EIA-861 versus 861S, and the monthly 861M sample) can shift a state's series without any change in behaviour.
- Coverage. Some columns can be missing or withheld for some state-years. Complete-case analysis assumes those rows are missing for reasons unrelated to the outcome; the audit reports how many are dropped so this can be judged.
- Omitted variables. Weather (heating and cooling degree days), income, housing stock and electric heating share are not in the model. Adding them would change the associational estimand and still would not identify the elasticity.
- Few clusters, serial dependence. 51 clusters is enough for CR1 with t(G - 1) critical values in most settings, but inference can still be optimistic with unbalanced cluster sizes or very persistent errors; a wild cluster bootstrap is a natural extension.
- Synthetic answers do not transfer. The size of the synthetic biases is a property of the chosen generator, not a prediction of the bias in real data.
Submission¶
- State the research question, unit of observation and estimand in your own words, and explain why
b2is not an elasticity. - Run the lab on the synthetic panel and explain each gap between M1, M2, M3 and the true elasticity.
- If you have an EIA key, fetch the public extract, report the audit, and rerun. Otherwise explain what you would check first in the audit.
- Compare conventional, HC3 and clustered intervals and explain which one matches the dependence in the data.
- Write a limitations paragraph and a one-paragraph proposal for a design that could identify the price elasticity.