opensced 0.1.0__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,911 @@
1
+ """ERCOT: public reports -> opensced input tables.
2
+
3
+ Everything here reads files anyone can download from ERCOT (ercot.com or the public API; docs/ercot.md says how). Nothing else is
4
+ needed, except the two inputs ERCOT does not publish, which you bring yourself:
5
+
6
+ shift_factors constraint x settlement point
7
+ resource_nodes resource -> settlement point
8
+
9
+ The reports, by the file name read_day() looks for (the name of the report's API endpoint):
10
+
11
+ 60_sced_gen_res_data 60-Day SCED Disclosure, generation resources NP3-965-ER required
12
+ 60d_sced_esr_data 60-Day SCED Disclosure, storage resources NP3-965-ER required
13
+ 60d_sced_resource_as_offers 60-Day SCED Disclosure, reserve offers NP3-965-ER
14
+ 60_load_res_data_in_sced 60-Day SCED Disclosure, Load Resources NP3-965-ER
15
+ dam_sced_as_demand_curves Ancillary Service Demand Curves NP4-212-CD every point, as posted
16
+ dam_as_plan DAM Ancillary Service Plan NP4-33-CD the hourly requirements
17
+ shdw_prices_bnd_trns_const SCED Shadow Prices and Binding Constraints NP6-86-CD
18
+ lmp_node_zone_hub LMPs by Resource Node, Load Zone and Hub NP6-788-CD for scoring
19
+ sced_system_lambda SCED System Lambda NP6-322-CD for scoring
20
+ rt_clear_price_cap_sced Real-Time Clearing Prices for Capacity NP6-332-CD for scoring
21
+ as_deployments when ERCOT had Non-Spin deployed: product, start, end (from its operations messages)
22
+ 2day_agg_sced_as_offers 2-Day Aggregate SCED Ancillary Service Offers NP3-906-EX days before Feb 3, 2026
23
+ reference_sced_resource_as_offers the same disclosure for a day on or after Feb 3, 2026 (optional, with the line above)
24
+ (the nine product files in one table, with a `product` column)
25
+
26
+ Each may be a .parquet or .csv file (optionally .csv.gz) holding one operating day, with ERCOT's own column names.
27
+ The four files of the 60-day disclosure are understood in both of ERCOT's naming styles ("Base Point" in the website's
28
+ files, "basePoint" from the API). The other reports are read in the API's column names.
29
+
30
+ How a SCED run becomes the tables
31
+ status a resource SCED can move (telemetered status in DISPATCHABLE, which includes units on an Output Schedule
32
+ and off-line quick-start units) is dispatchable. Anything else is held at its base point.
33
+ limits low / high are LSL / HSL; ramp_low / ramp_high are LDL / HDL; output is the base point.
34
+ offers the SCED2 curve: the curve SCED dispatched on, after mitigation, including the proxy curves ERCOT
35
+ builds for resources without a full curve (6.5.7.3(4) and (6)). If a file has no curve for a
36
+ dispatchable resource it gets the wind and solar proxy: free to 1 MW below its ceiling, then $1,500.
37
+ reserves limits are the disclosed capabilities times the rulebook's minutes of ramp. RRS is three products
38
+ (RRS-PFR, RRS-FFR, RRS-UFR), each with its own capability and offer price, serving one RRS demand curve.
39
+ Offers come from the reserve offer disclosure, including ERCOT's proxy offer for unoffered capacity.
40
+ On-line resources offer through ONRES and REGDN blocks, off-line ones through OFFNS; an off-line
41
+ unit may carry Non-Spin only, a quick-start unit ECRS and Non-Spin, a synchronous condenser RRS and ECRS.
42
+ loads a non-controllable Load Resource is a resource of kind 'load' that carries reserves up to the
43
+ consumption it can drop. A controllable one is dispatched as negative output on its bid-to-buy curve.
44
+ What either self-arranged is offered at $0, so it is taken first.
45
+ demand the sum of the run's base points (what SCED dispatched), less what controllable loads consume.
46
+ constraints every constraint ERCOT reported in the run, with its reported flow, limit and maximum shadow price.
47
+ """
48
+ import os
49
+ import re
50
+ import warnings
51
+
52
+ import numpy as np
53
+ import pandas as pd
54
+
55
+ from opensced.core.tables import Inputs
56
+ from opensced.markets.ercot.rulebooks import ALL
57
+
58
+ TS, RES, REP = 'SCED Time Stamp', 'Resource Name', 'Repeated Hour Flag'
59
+ NPT = 35 # points on an offer curve
60
+ STORAGE_TYPES = ('ESR', 'PWRSTR')
61
+ # ERCOT's resource type -> the category its mitigated offer floor is set by (Protocols 4.4.9.4.2). Whether a unit is a
62
+ # Qualifying Facility is not in the disclosure: pass categories={resource: 'qf'} for those.
63
+ CATEGORY = {'NUC': 'nuclear', 'HYDRO': 'hydro', 'CLLIG': 'coal', 'CCGT90': 'combined_cycle', 'CCLE90': 'combined_cycle',
64
+ 'SCGT90': 'gas_steam_ct', 'SCLE90': 'gas_steam_ct', 'GSREH': 'gas_steam_ct', 'GSNONR': 'gas_steam_ct',
65
+ 'GSSUP': 'gas_steam_ct', 'DSL': 'gas_steam_ct', 'WIND': 'wind', 'PVGR': 'pv', 'ESR': 'esr', 'PWRSTR': 'esr'}
66
+ ZERO_FILL_END = pd.Timestamp('2026-02-03') # before this, ERCOT wrote unpriced cells as 0
67
+ PRODUCT = {'REGUP': 'RegUp', 'REGDN': 'RegDown', 'RRS': 'RRS', 'ECRS': 'ECRS', 'NSPIN': 'NonSpin'} # demand curve names
68
+ # ERCOT's aggregate reserve offer curves (NP3-906-EX): aggregate product -> (rulebook product, price column, who offers it)
69
+ AGGREGATE = {'REGUP': ('RegUp', 'REGUP', 'resource'), 'REGDN': ('RegDown', 'REGDN', 'resource'), 'RRSPFR': ('RRS-PFR', 'RRSPFR', 'resource'),
70
+ 'RRSFFR': ('RRS-FFR', 'RRSFFR', 'any'), 'RRSUFR': ('RRS-UFR', 'RRSUFR', 'load'), 'ECRSS': ('ECRS', 'ECRS', 'resource'),
71
+ 'ECRSM': ('ECRS', 'ECRS', 'load'), 'NSPIN': ('NonSpin', 'NSPIN', 'resource'), 'NSPNM': ('NonSpin', 'NSPIN', 'load')}
72
+ GEN_CAPABILITY = ('ASCapREGUP', 'ASCapREGDN', 'ASCapRRSPFR', 'ASCapRRSFFR', 'ASCapECRS', 'ASCapNSPIN') # in the generation and storage files
73
+ MCPC = {'REGUP': 'RegUp', 'REGDN': 'RegDown', 'RRS': 'RRS', 'ECRS': 'ECRS', 'NSPIN': 'NonSpin'}
74
+
75
+ CANON = {
76
+ 'SCEDTimestamp': TS, 'SCED Timestamp': TS, 'repeatHourFlag': REP, 'repeatedHourFlag': REP,
77
+ 'resourceName': RES, 'resourceType': 'Resource Type',
78
+ 'telemeteredResourceStatus': 'Telemetered Resource Status', 'telemeteredNetOutput': 'Telemetered Net Output',
79
+ 'basePoint': 'Base Point', 'Ramp Rate Up': 'rampRateUp', 'Ramp Rate Down': 'rampRateDown', 'Normal Ramp Rate Up': 'rampRateUp',
80
+ 'Normal Ramp Rate Down': 'rampRateDown',
81
+ **{f'SCED{n} Curve-{k}{i}': f'SCED{n}Curve{k}{i}' for n in (1, 2) for k in ('MW', 'Price') for i in range(1, NPT + 1)},
82
+ **{f'AS Awards {a}': f'ASAwards{a}' for a in ('ECRS', 'NSPIN', 'REGDN', 'REGUP', 'RRSFFR', 'RRSPFR', 'RRSUFR')},
83
+ **{f'AS Capability {a}': f'ASCap{a}' for a in ('ECRS', 'NSPIN', 'REGDN', 'REGUP', 'RRSFFR', 'RRSPFR', 'RRSUFR')},
84
+ 'State of Charge': 'SOC', 'Minimum SOC': 'minSOC', 'Maximum SOC': 'maxSOC',
85
+ }
86
+ # the Load Resource file: the website's column names -> the API's
87
+ LOAD_CANON = {
88
+ 'SCED Time Stamp': 'SCEDTimestamp', 'SCED Timestamp': 'SCEDTimestamp', 'Repeated Hour Flag': 'repeatHourFlag', 'QSE': 'qseName',
89
+ 'DME': 'dmeName', 'Resource Name': 'resourceName', 'Telemetered Resource Status': 'telResStatus',
90
+ 'Max Power Consumption': 'maxPowerConsumption', 'Low Power Consumption': 'lowPowerConsumption',
91
+ 'Real Power Consumption': 'realPowerConsumption', 'Ramp Rate Up': 'rampRateUp', 'Ramp Rate Down': 'rampRateDown',
92
+ 'Base Point': 'basePoint',
93
+ **{f'SCED Bid to Buy Curve-{k}{i}': f'SCEDBidCurve{k}{i}' for k in ('MW', 'Price') for i in range(1, 11)},
94
+ **{f'{a} {p}': f'{b}{p}' for a, b in (('AS Awards', 'ASAwards'), ('AS Capability', 'ASCap'), ('Self Provided', 'self'))
95
+ for p in ('ECRS', 'NSPIN', 'REGDN', 'REGUP', 'RRSFFR', 'RRSPFR', 'RRSUFR')},
96
+ }
97
+ # report -> what to call it in a message
98
+ REPORTS = {'gen': '60-Day SCED Disclosure, generation resources (NP3-965-ER)', 'esr': '60-Day SCED Disclosure, storage resources (NP3-965-ER)',
99
+ 'reserve_offers': '60-Day SCED Disclosure, reserve offers (NP3-965-ER)', 'load_resources': '60-Day SCED Disclosure, Load Resources (NP3-965-ER)',
100
+ 'reserve_demand': 'Ancillary Service Demand Curves (NP4-212-CD)', 'reserve_plan': 'DAM Ancillary Service Plan (NP4-33-CD)',
101
+ 'constraints': 'SCED Shadow Prices and Binding Transmission Constraints (NP6-86-CD)',
102
+ 'lmp': 'LMPs by Resource Node, Load Zone and Hub (NP6-788-CD)', 'system_lambda': 'SCED System Lambda (NP6-322-CD)',
103
+ 'reserve_prices': 'Real-Time Clearing Prices for Capacity by SCED Interval (NP6-332-CD)'}
104
+ FILES = {'gen': '60_sced_gen_res_data', 'esr': '60d_sced_esr_data', 'reserve_offers': '60d_sced_resource_as_offers',
105
+ 'load_resources': '60_load_res_data_in_sced', 'reserve_demand': 'dam_sced_as_demand_curves', 'reserve_plan': 'dam_as_plan',
106
+ 'constraints': 'shdw_prices_bnd_trns_const', 'lmp': 'lmp_node_zone_hub', 'system_lambda': 'sced_system_lambda',
107
+ 'reserve_prices': 'rt_clear_price_cap_sced', 'aggregate_offers': '2day_agg_sced_as_offers',
108
+ 'reference_offers': 'reference_sced_resource_as_offers', 'reserve_deployments': 'as_deployments'}
109
+
110
+
111
+ # ---------------------------------------------------------------- the SCED disclosure
112
+ def _merge_collisions(df):
113
+ """Columns that share a name after renaming: keep the first non-null value per row."""
114
+ if not df.columns.duplicated().any():
115
+ return df
116
+ out = {}
117
+ for name in dict.fromkeys(df.columns):
118
+ block = df.loc[:, df.columns == name]
119
+ out[name] = block.iloc[:, 0] if block.shape[1] == 1 else block.bfill(axis=1).iloc[:, 0]
120
+ return pd.DataFrame(out, index=df.index)
121
+
122
+
123
+ def normalize(df):
124
+ """The SCED disclosure with one set of column names; one row per resource and SCED run."""
125
+ df = df.copy()
126
+ df.columns = df.columns.str.strip()
127
+ df = _merge_collisions(df)
128
+ df = _merge_collisions(df.rename(columns={k: v for k, v in CANON.items() if k in df.columns}))
129
+ if RES not in df or TS not in df:
130
+ raise ValueError(f'this does not look like the 60-Day SCED Disclosure: no resource name or SCED timestamp column. '
131
+ f'Columns start: {list(df.columns[:6])}')
132
+ df[TS] = pd.to_datetime(df[TS], errors='coerce')
133
+ df[RES] = df[RES].astype(str).str.strip()
134
+ return df.drop_duplicates(subset=[c for c in (RES, TS, REP) if c in df.columns])
135
+
136
+
137
+ def load_columns(L):
138
+ """The Load Resource file with the API's column names. The website's CSV names them "Resource Name",
139
+ "AS Awards NSPIN", "SCED Bid to Buy Curve-MW1", ..."""
140
+ if L is None:
141
+ return L
142
+ L = L.rename(columns=lambda c: str(c).strip())
143
+ L = L.rename(columns={k: v for k, v in LOAD_CANON.items() if k in L.columns and v not in L.columns})
144
+ if 'resourceName' not in L or 'SCEDTimestamp' not in L:
145
+ raise ValueError(f'this does not look like the 60-Day SCED Load Resource file: no resource name or SCED timestamp column. '
146
+ f'Columns start: {list(L.columns[:6])}')
147
+ return L
148
+
149
+
150
+ def _num(x, c):
151
+ return pd.to_numeric(x[c], errors='coerce').to_numpy(float) if c in x else np.full(len(x), np.nan)
152
+
153
+
154
+ def _flag(s):
155
+ return s.astype(str).str.strip().str.upper().isin(['TRUE', 'Y', '1']).to_numpy()
156
+
157
+
158
+ def _run_rows(df, when, ts_col):
159
+ """rows of a per-run report at the run `when`: the same SCED timestamp, else the same 5-minute interval."""
160
+ t, w = pd.to_datetime(df[ts_col], errors='coerce'), pd.Timestamp(when)
161
+ exact = (t == w).to_numpy()
162
+ return df[exact] if exact.any() else df[(t.dt.floor('5min') == w.floor('5min')).to_numpy()]
163
+
164
+
165
+ def _sced_tables(x, rules, storage_types=STORAGE_TYPES, curve_points=NPT, curve='SCED2'):
166
+ """generation and storage rows of one run -> resources, energy_offers, storage, reserve_limits, flags."""
167
+ x = x.reset_index(drop=True)
168
+ names = x[RES].to_numpy()
169
+ status = x['Telemetered Resource Status'].astype(str).str.strip().str.upper().to_numpy()
170
+ typ = x['Resource Type'].astype(str).str.strip().to_numpy() if 'Resource Type' in x else np.full(len(x), '')
171
+ ldl, hdl, lsl, hsl = (_num(x, c) for c in ('LDL', 'HDL', 'LSL', 'HSL'))
172
+ bp = np.nan_to_num(_num(x, 'Base Point'))
173
+ if rules.dispatch_limits == 'ramp': # SCED moves a resource between LDL and HDL
174
+ lo, hi = np.where(np.isfinite(ldl), ldl, lsl), np.where(np.isfinite(hdl), hdl, hsl)
175
+ else:
176
+ lo, hi = np.fmax(ldl, lsl), np.fmin(hdl, hsl)
177
+ can = {st.name for st in rules.statuses if st.dispatchable}
178
+ held = {st.name for st in rules.statuses if not st.dispatchable and st.reserves}
179
+ disp = np.isin(status, list(can)) & np.isfinite(lo) & np.isfinite(hi) & (hi >= lo)
180
+ off = np.isin(status, list(held)) & np.isfinite(hsl)
181
+ fill = lambda a, b: np.where(np.isfinite(a), a, np.where(np.isfinite(b), b, bp))
182
+ low, high = fill(lsl, ldl), fill(hsl, hdl)
183
+ high = np.maximum(high, low)
184
+ storage_kind = np.isin(typ, storage_types)
185
+ resources = pd.DataFrame({'name': names, 'low': low, 'high': high, 'ramp_low': fill(ldl, lsl), 'ramp_high': fill(hdl, hsl),
186
+ 'output': bp, 'dispatchable': disp, 'kind': np.where(storage_kind, 'storage', 'generator'),
187
+ 'type': typ, 'status': status, 'category': [CATEGORY.get(t, 'other') for t in typ],
188
+ 'ramp_up': _num(x, 'rampRateUp'), 'ramp_down': _num(x, 'rampRateDown'),
189
+ 'telemetered': _num(x, 'Telemetered Net Output')})
190
+ if f'{curve}CurveMW1' not in x:
191
+ raise ValueError(f'the SCED table has no {curve} offer curve columns ({curve}CurveMW1, {curve}CurvePrice1, ...)')
192
+ M = np.column_stack([_num(x, f'{curve}CurveMW{j}') for j in range(1, curve_points + 1)])
193
+ Pr = np.column_stack([_num(x, f'{curve}CurvePrice{j}') for j in range(1, curve_points + 1)])
194
+ tol = rules.tolerance_mw
195
+ ok = np.isfinite(M) & np.isfinite(Pr) & (disp & (hi - lo > tol))[:, None]
196
+ ri, _ = np.where(ok)
197
+ offers = pd.DataFrame({'resource': names[ri], 'mw': M[ok], 'price': Pr[ok]})
198
+ bare = np.where(disp & (hi - lo > tol) & ~ok.any(axis=1))[0] # no curve: the wind and solar proxy, 6.5.7.3(4)(c)
199
+ if len(bare):
200
+ a, b = np.fmax(ldl, lsl)[bare], np.fmin(hdl, hsl)[bare] # the proxy is anchored on LSL and HSL, inside the range
201
+ proxy = pd.DataFrame({'resource': np.repeat(names[bare], 3),
202
+ 'mw': np.c_[a, np.maximum(b - rules.proxy_mw_step, a), b].ravel(),
203
+ 'price': np.tile((rules.offer_floor, rules.offer_floor + rules.proxy_price_step, rules.irr_proxy_price), len(bare))})
204
+ offers = pd.concat([offers, proxy], ignore_index=True)
205
+ soc, smin, smax = _num(x, 'SOC'), _num(x, 'minSOC'), _num(x, 'maxSOC')
206
+ s = storage_kind & np.isfinite(soc)
207
+ storage = pd.DataFrame({'resource': names[s], 'soc': soc[s], 'soc_min': np.nan_to_num(smin[s]), 'soc_max': np.where(np.isfinite(smax[s]), smax[s], soc[s])})
208
+ lim = []
209
+ for p in rules.products:
210
+ cap = sum(np.nan_to_num(_num(x, c)) for c in p.capability_columns) * (p.ramp_minutes or 1.0)
211
+ cap = cap + np.zeros(len(x))
212
+ keep = (cap > 0) & (disp | off)
213
+ lim.append(pd.DataFrame({'resource': names[keep], 'product': p.name, 'mw': cap[keep]}))
214
+ return resources, offers, storage, pd.concat(lim, ignore_index=True), dict(zip(names, status)), dict(zip(names, disp))
215
+
216
+
217
+ # product codes in the website's CSV: the short ones (files posted to April 2026) and the API's own (later files)
218
+ _OFFER_PRODUCT = {'URS': 'REGUP', 'DRS': 'REGDN', 'RRSPF': 'RRSPFR', 'RRSUF': 'RRSUFR', 'RRSFF': 'RRSFFR', 'NS': 'NSPIN', 'ECRS': 'ECRS',
219
+ 'REGUP': 'REGUP', 'REGDN': 'REGDN', 'RRSPFR': 'RRSPFR', 'RRSUFR': 'RRSUFR', 'RRSFFR': 'RRSFFR', 'NSPIN': 'NSPIN'}
220
+
221
+
222
+ def offer_columns(o):
223
+ """The reserve offer disclosure with the API's column names. The website's CSV (the only form ERCOT's corrected
224
+ files for December 5, 2025 to February 2, 2026 come in) names them PRICE1_URS, QUANTITY_MW1, "SCED Timestamp", ...
225
+ and writes the repeated-hour flag as Y / N."""
226
+ if o is None or 'SCEDTimestamp' in o.columns:
227
+ return o
228
+ names = {'SCED Timestamp': 'SCEDTimestamp', 'Repeated Hour Flag': 'repeatHourFlag', 'Resource Name': 'resourceName',
229
+ 'Offer Type': 'offerType'}
230
+ for c in o.columns:
231
+ m = re.fullmatch(r'PRICE(\d)_([A-Z]+)', str(c).strip())
232
+ if m and m.group(2) in _OFFER_PRODUCT:
233
+ names[c] = f'price{m.group(1)}{_OFFER_PRODUCT[m.group(2)]}'
234
+ elif m:
235
+ raise ValueError(f'the reserve offer table has a price column for a product code this adapter does not know: {c}')
236
+ m = re.fullmatch(r'QUANTITY_MW(\d)', str(c).strip())
237
+ if m:
238
+ names[c] = f'quantityMW{m.group(1)}'
239
+ o = o.rename(columns=names)
240
+ if 'SCEDTimestamp' not in o.columns:
241
+ raise ValueError(f'the reserve offer table has no SCED timestamp column; its columns are {list(o.columns)[:8]}...')
242
+ if 'repeatHourFlag' in o and o['repeatHourFlag'].dtype == object:
243
+ o['repeatHourFlag'] = o['repeatHourFlag'].astype(str).str.strip().str.upper().isin(('Y', 'TRUE'))
244
+ return o
245
+
246
+
247
+ def _offer_types(o):
248
+ """the offer type of each row of the reserve offer disclosure: ONRES, REGDN or OFFNS.
249
+
250
+ ERCOT left the offerType column empty in the first weeks of RTC+B (seen on December 14, 2025). Block 6, ERCOT's
251
+ proxy offer, still tells the rows apart: it is priced for Reg-Down alone on a REGDN row, for Non-Spin alone on an
252
+ OFFNS row, and for the other products on an ONRES row. On three days that have the column (January 25, January 28,
253
+ February 24, 2026; 4.6 million rows) this recovers it with no row wrong."""
254
+ given = o['offer_type'].astype(str).str.strip()
255
+ missing = o['offer_type'].isna().to_numpy() | given.isin(['', 'None', 'nan', 'NaN']).to_numpy()
256
+ if not missing.any():
257
+ return given
258
+ on = {}
259
+ for c in o.columns:
260
+ if c.startswith('price6'):
261
+ v = pd.to_numeric(o[c], errors='coerce').to_numpy(float)
262
+ on[c[6:]] = np.isfinite(v) & (v != 0)
263
+ other = np.zeros(len(o), bool)
264
+ for q, m in on.items():
265
+ if q not in ('REGDN', 'NSPIN'):
266
+ other |= m
267
+ dn, ns = on.get('REGDN', np.zeros(len(o), bool)), on.get('NSPIN', np.zeros(len(o), bool))
268
+ found = np.where(other, 'ONRES', np.where(dn & ~ns, 'REGDN', np.where(ns & ~dn, 'OFFNS', '')))
269
+ out = np.where(missing, found, given.to_numpy())
270
+ lost = missing & (out == '')
271
+ if lost.any():
272
+ offered = np.zeros(len(o), bool)
273
+ for k in range(1, 6):
274
+ if f'quantityMW{k}' in o:
275
+ offered |= pd.to_numeric(o[f'quantityMW{k}'], errors='coerce').fillna(0).to_numpy() > 0
276
+ if (lost & offered).any():
277
+ raise ValueError(f'reserve_offers: {int((lost & offered).sum()):,} rows have no offerType and no proxy block to tell it '
278
+ f'from, e.g. {o["resource"].to_numpy()[lost & offered][0]!r}')
279
+ return pd.Series(out, index=o.index)
280
+
281
+
282
+ def zero_offer_habits(reference):
283
+ """A day of the reserve offer disclosure on which blanks are real (February 3, 2026 or later) -> the cells that
284
+ held a genuine $0 offer: resource, offer_type, product (ERCOT's column name), block, hour. Used as evidence of
285
+ which zero-filled cells of an earlier day were real offers (see _reserve_offers)."""
286
+ r = reference.rename(columns={'resourceName': 'resource', 'offerType': 'offer_type'})
287
+ cols = [c for c in r.columns if c.startswith('price') and c[5:6] in '12345']
288
+ if not len(cols) or not r[cols].isna().to_numpy().any():
289
+ raise ValueError('reference_offers: this file has no blank prices, so its zeros cannot be told from blanks. Use a day on '
290
+ 'or after 2026-02-03')
291
+ hour = pd.to_datetime(r['SCEDTimestamp']).dt.hour.to_numpy()
292
+ name, kind = r['resource'].astype(str).str.strip().to_numpy(), _offer_types(r).to_numpy()
293
+ out = []
294
+ for c in cols:
295
+ k = int(c[5])
296
+ m = (pd.to_numeric(r[c], errors='coerce') == 0).to_numpy() & (pd.to_numeric(r[f'quantityMW{k}'], errors='coerce') > 0).to_numpy()
297
+ if m.any():
298
+ out.append(pd.DataFrame({'resource': name[m], 'offer_type': kind[m], 'product': c[6:], 'block': k, 'hour': hour[m]}).drop_duplicates())
299
+ return pd.concat(out, ignore_index=True).drop_duplicates() if out else pd.DataFrame(columns=['resource', 'offer_type', 'product', 'block', 'hour'])
300
+
301
+
302
+ def _reserve_offers(o, status, when, rules, zero_price_is_blank=None, aggregate=None, loads=None, habits=None):
303
+ """the run's rows of the reserve offer disclosure -> the reserve_offers table.
304
+
305
+ Each row holds up to six blocks. Blocks 1-5 are what the QSE submitted. Block 6 is ERCOT's proxy offer
306
+ (6.5.7.3(5)): the rest of the resource's capacity, linked across every product it is qualified for, priced at the
307
+ higher of a floor taken from the demand curve and the resource's own highest offer. A status may carry only the
308
+ products the rulebook's `statuses` list for it.
309
+
310
+ Before February 3, 2026 ERCOT wrote every unpriced cell as 0, so a 0 may be "not offered" or a real $0 offer. A 0 is
311
+ read as not offered. When `aggregate` (ERCOT's aggregate offer curves for the run, NP3-906-EX) is given, the real
312
+ $0 offers are put back. The aggregate curve is the exact sum of every resource's offers, whatever its status
313
+ (checked on February 24, 2026, to 0.1 MW at every price), so its MW at $0 is the total to restore for each product.
314
+ Which cells held them is not in the file. The total is given out in this order, each cell whole until it runs out:
315
+ 1. cells that must be real: a block with MW needs one price, and this is the only product the row could price
316
+ 2. cells that were a $0 offer on the reference day (`habits`): same resource, offer type, product, block, hour
317
+ 3. cells whose resource offered that product at $0 at any time on the reference day
318
+ 4. what is left, over the remaining zero cells in proportion to their MW
319
+ Without a reference day everything but step 1 falls to step 4, which gets the total right and the resources wrong."""
320
+ o = o.rename(columns={'resourceName': 'resource', 'offerType': 'offer_type'}).reset_index(drop=True)
321
+ o = o.assign(resource=o['resource'].astype(str).str.strip())
322
+ o['offer_type'] = _offer_types(o)
323
+ may_carry = {x.name: x.reserves for x in rules.statuses}
324
+ no_proxy = {x.name for x in rules.statuses if not x.proxy_reserves}
325
+ group = o['resource'].map(status).to_numpy()
326
+ allowed = np.array([bool(may_carry.get(g)) for g in group], dtype=bool) # the resource's status may carry reserves at all
327
+ carries = lambda ot, p: np.array([bool(may_carry.get(g)) and ot in may_carry[g] and (may_carry[g][ot] is None or p in may_carry[g][ot]) for g in group], dtype=bool)
328
+ if zero_price_is_blank is None: # a file with blank prices is ERCOT's corrected one
329
+ prices = [c for c in o.columns if c.startswith('price')]
330
+ blanks = bool(len(o)) and bool(o[prices].isna().to_numpy().any())
331
+ zero_blank = pd.Timestamp(when) < ZERO_FILL_END and not blanks
332
+ else:
333
+ zero_blank = zero_price_is_blank
334
+ kinds = sorted({k for p in rules.products for k in p.offer_kinds})
335
+ name, kind = o['resource'].to_numpy(), o['offer_type'].to_numpy()
336
+ out = []
337
+ for k in range(1, 7):
338
+ if f'quantityMW{k}' not in o:
339
+ continue
340
+ w = pd.to_numeric(o[f'quantityMW{k}'], errors='coerce').to_numpy(float)
341
+ if k == 6 and no_proxy: # block 6 is ERCOT's proxy offer
342
+ w = np.where(np.isin(group.astype(str), list(no_proxy)), np.nan, w)
343
+ for ot in kinds:
344
+ m = (kind == ot) & np.isfinite(w) & (w > 0) & allowed
345
+ if not m.any():
346
+ continue
347
+ for prod in rules.products:
348
+ if ot not in prod.offer_kinds:
349
+ continue
350
+ p = prod.name
351
+ may = carries(ot, p)
352
+ cols = [f'price{k}{q}' for q in prod.offer_price_columns if f'price{k}{q}' in o]
353
+ if not cols or not (m & may).any():
354
+ continue
355
+ v = o.loc[m & may, cols].apply(pd.to_numeric, errors='coerce')
356
+ if zero_blank:
357
+ v = v.mask(v == 0)
358
+ price = v.min(axis=1).to_numpy(float)
359
+ has = np.isfinite(price)
360
+ idx = np.where(m & may)[0][has]
361
+ out.append(pd.DataFrame({'resource': name[idx], 'block': [f'{ot}-{i}-{k}' for i in idx],
362
+ 'mw': w[idx], 'product': p, 'price': price[has], '_o': idx * 10 + k}))
363
+ restored, report = [], []
364
+ if zero_blank and aggregate is not None and len(aggregate) and len(o):
365
+ a = aggregate.copy()
366
+ pc = [c for c in a.columns if c.endswith('OfferPrice')]
367
+ a['_p'] = a[pc].apply(pd.to_numeric, errors='coerce').bfill(axis=1).iloc[:, 0] if pc else pd.to_numeric(a['price'], errors='coerce')
368
+ a['_mw'] = pd.to_numeric(a['MWOffered'] if 'MWOffered' in a else a['mw'], errors='coerce')
369
+ is_load = np.isin(name, list(loads)) if loads is not None else (group == 'ONL')
370
+ can_price = {ot: sum(ot in p.offer_kinds for p in rules.products) for ot in kinds} # products a row of this type could price
371
+ hour = pd.Timestamp(when).hour
372
+ exact, ever = set(), set()
373
+ if habits is not None and len(habits):
374
+ h = habits[habits['hour'] == hour]
375
+ exact = set(zip(h['resource'], h['offer_type'], h['product'], h['block']))
376
+ ever = set(zip(habits['resource'], habits['offer_type'], habits['product']))
377
+ priced = {} # block k -> rows with a price above 0 for any product
378
+ for k in range(1, 6):
379
+ any_price = np.zeros(len(o), bool)
380
+ for c in o.columns:
381
+ if c.startswith(f'price{k}'):
382
+ any_price |= (pd.to_numeric(o[c], errors='coerce') > 0).to_numpy()
383
+ priced[k] = any_price
384
+ for agg, (prod, col, who) in AGGREGATE.items():
385
+ if prod not in rules.product_names:
386
+ continue
387
+ g = a[a['product'].astype(str).str.upper() == agg]
388
+ at_zero = g['_mw'][g['_p'] <= 1e-9]
389
+ left = float(at_zero.max()) if len(at_zero) else 0.0 # MW ERCOT counts at exactly $0, all resources
390
+ report.append({'product': prod, 'aggregate': agg, 'mw_at_zero': left, 'certain': 0.0, 'same_cell': 0.0, 'same_resource': 0.0, 'spread': 0.0, 'unplaced': 0.0})
391
+ if left <= 0:
392
+ continue
393
+ side = is_load if who == 'load' else ~is_load if who == 'resource' else np.ones(len(o), bool)
394
+ types = np.isin(kind, list(rules.product(prod).offer_kinds))
395
+ cells = [] # (row, block, MW, tier)
396
+ for k in range(1, 6):
397
+ c, q = f'price{k}{col}', f'quantityMW{k}'
398
+ if c not in o or q not in o:
399
+ continue
400
+ mw = pd.to_numeric(o[q], errors='coerce').to_numpy(float)
401
+ z = (pd.to_numeric(o[c], errors='coerce') == 0).to_numpy() & (mw > 0) & side & types
402
+ for i in np.where(z)[0]:
403
+ tier = (0 if not priced[k][i] and can_price[kind[i]] == 1 else 1 if (name[i], kind[i], col, k) in exact
404
+ else 2 if (name[i], kind[i], col) in ever else 3)
405
+ cells.append((i, k, mw[i], tier))
406
+ for tier, label in enumerate(('certain', 'same_cell', 'same_resource', 'spread')):
407
+ mine = [c for c in cells if c[3] == tier]
408
+ pool = sum(c[2] for c in mine)
409
+ share = min(left / pool, 1.0) if pool > 0 else 0.0
410
+ if share <= 0:
411
+ continue
412
+ report[-1][label] = share * pool
413
+ left -= share * pool
414
+ may = carries
415
+ for i, k, mw, _ in mine: # only resources whose status may carry it enter the run
416
+ ot = kind[i]
417
+ g_ = group[i]
418
+ if not (bool(may_carry.get(g_)) and ot in may_carry[g_] and (may_carry[g_][ot] is None or prod in may_carry[g_][ot])):
419
+ continue
420
+ whole = share > 0.999 # a whole cell joins its block, linked with the block's other products
421
+ restored.append((name[i], f'{ot}-{i}-{k}' if whole else f'zero-{prod}-{i}-{k}', mw if whole else share * mw, prod, 0.0))
422
+ report[-1]['unplaced'] = max(left, 0.0)
423
+ cols = ['resource', 'block', 'mw', 'product', 'price']
424
+ r = pd.concat(out, ignore_index=True).sort_values('_o', kind='stable').drop(columns='_o') if out else pd.DataFrame(columns=cols)
425
+ if restored:
426
+ r = pd.concat([r, pd.DataFrame(restored, columns=cols)], ignore_index=True)
427
+ r.attrs['zero_offers'] = pd.DataFrame(report) if report else None
428
+ return r
429
+
430
+
431
+ def _load_tables(L, rules, controllable=True, load_room='consumption-lpc'):
432
+ """the run's Load Resource rows -> resources of kind 'load', their energy bids, reserve limits, self-arranged MW
433
+ as $0 offer blocks, and which of them the clearing may move.
434
+
435
+ A non-controllable Load Resource carries reserves only: up to the consumption it can drop (its consumption less
436
+ its low power consumption). It has no output of its own in the clearing.
437
+
438
+ A controllable Load Resource (one with a base point or a bid curve) is dispatched like a generator with negative
439
+ output: it consumes between its LDL and HDL, and its bid-to-buy curve says what each MW of consumption is worth
440
+ to it. Online with a bid curve and room to move, it is dispatchable; otherwise it is held at its base point.
441
+ controllable=False leaves these out, as if their consumption were fixed demand."""
442
+ L = L.assign(_n=L['resourceName'].astype(str).str.strip()).drop_duplicates('_n').reset_index(drop=True)
443
+ raw = lambda c: pd.to_numeric(L[c], errors='coerce').to_numpy(float) if c in L else np.full(len(L), np.nan)
444
+ num = lambda c: np.nan_to_num(raw(c))
445
+ names = L['_n'].to_numpy()
446
+ bp, has_bid = raw('basePoint'), np.isfinite(raw('SCEDBidCurveMW1'))
447
+ ctrl = np.isin(names, list(controllable)) if isinstance(controllable, (list, tuple, set)) else (np.abs(np.nan_to_num(bp)) > 0) | has_bid
448
+ controllable = bool(controllable) if not isinstance(controllable, bool) else controllable
449
+ tel = L['telResStatus'].astype(str).str.strip().str.upper().to_numpy() if 'telResStatus' in L else np.full(len(L), 'ONL')
450
+ online = np.isin(tel, [x.name for x in rules.statuses if x.dispatchable])
451
+ room = np.clip(num('maxPowerConsumption' if load_room == 'mpc-lpc' else 'realPowerConsumption') - num('lowPowerConsumption'), 0, None)
452
+ n = ~ctrl
453
+ res = [pd.DataFrame({'name': names[n], 'low': 0.0, 'high': room[n], 'ramp_low': 0.0, 'ramp_high': 0.0, 'output': 0.0,
454
+ 'dispatchable': False, 'kind': 'load', 'type': 'NCLR', 'status': tel[n],
455
+ 'max_consumption': num('maxPowerConsumption')[n], 'low_consumption': num('lowPowerConsumption')[n]})]
456
+ offers = pd.DataFrame(columns=['resource', 'mw', 'price'])
457
+ moves = {}
458
+ if controllable and ctrl.any():
459
+ c = ctrl
460
+ use = np.where(np.isfinite(bp), bp, num('realPowerConsumption')) # consumption going in, MW
461
+ hdl, ldl = raw('HDL'), raw('LDL')
462
+ hdl, ldl = np.where(np.isfinite(hdl), hdl, use), np.where(np.isfinite(ldl), ldl, use)
463
+ most, least = np.maximum(num('maxPowerConsumption'), hdl), np.minimum(num('lowPowerConsumption'), ldl)
464
+ disp = c & online & (hdl - ldl > rules.tolerance_mw) # with no bid it gets ERCOT's proxy bid (below)
465
+ res.append(pd.DataFrame({'name': names[c], 'low': -most[c], 'high': -least[c], 'ramp_low': -hdl[c], 'ramp_high': -ldl[c],
466
+ 'output': -use[c], 'dispatchable': disp[c], 'kind': 'load', 'type': 'CLR',
467
+ 'status': tel[c], 'max_consumption': num('maxPowerConsumption')[c], 'low_consumption': num('lowPowerConsumption')[c]}))
468
+ moves = dict(zip(names[c], disp[c]))
469
+ pts = [pd.DataFrame({'resource': names[disp], 'mw': -raw(f'SCEDBidCurveMW{k}')[disp], 'price': raw(f'SCEDBidCurvePrice{k}')[disp]})
470
+ for k in range(10, 0, -1) if f'SCEDBidCurveMW{k}' in L] # last point first: as output (minus consumption) the
471
+ # curve runs the other way, and where two points share a MW the one for more consumption must come first
472
+ bare = disp & ~has_bid # 6.5.7.3(9): a proxy bid from LPC to MPC at the
473
+ if bare.any(): # value of lost load
474
+ pts.append(pd.DataFrame({'resource': np.tile(names[bare], 2), 'mw': np.r_[-most[bare], -least[bare]], 'price': float(rules.voll)}))
475
+ if pts:
476
+ offers = pd.concat(pts, ignore_index=True).dropna()
477
+ keep = n | (ctrl if controllable else False)
478
+ cap = {p.name: sum(num(c) for c in p.capability_columns) * (p.ramp_minutes or 1.0) + np.zeros(len(L)) for p in rules.products}
479
+ lim = pd.concat([pd.DataFrame({'resource': names[(v > 0) & keep], 'product': p, 'mw': v[(v > 0) & keep]}) for p, v in cap.items()], ignore_index=True)
480
+ # Self-provided reserves (6.4.2(3): RRS and ECRS from loads on under-frequency relays) are awarded before anything
481
+ # is bought from the load, RRS first, as far as the consumption it can drop allows. Offered at a price low enough
482
+ # that the clearing always takes them, twice as low for RRS. A load that is not on line provides nothing.
483
+ carries = np.isin(tel, [x.name for x in rules.statuses if x.reserves])
484
+ own, left = [], room.copy()
485
+ for p, v, rank in (('RRS-UFR', num('selfRRSUFR'), 2.0), ('RRS-FFR', num('selfRRSFFR'), 2.0), ('ECRS', num('selfECRS'), 1.0)):
486
+ take = np.minimum(v, left)
487
+ left = left - take
488
+ m = (take > 0) & keep & carries
489
+ own.append(pd.DataFrame({'resource': names[m], 'block': f'self-{p}', 'mw': take[m], 'product': p, 'price': rank * rules.self_arranged_price}))
490
+ return pd.concat(res, ignore_index=True), offers, lim, pd.concat(own, ignore_index=True), moves
491
+
492
+
493
+ def _reserve_demand(curves, when):
494
+ """Ancillary Service Demand Curves -> the reserve_demand table for the run's hour. When the report holds several
495
+ postings, each product's curve comes from the latest posting made before the run that contains it (a posting can be
496
+ incomplete: the one made on September 7, 2026 for September 8 holds five hours only)."""
497
+ c = curves.copy()
498
+ c.columns = c.columns.str.strip()
499
+ t = pd.Timestamp(when)
500
+ if 'hourEnding' in c:
501
+ he = c['hourEnding'].astype(str).str.slice(0, 2).astype(int)
502
+ c = c[(he == t.hour + 1).to_numpy()]
503
+ if 'deliveryDate' in c:
504
+ c = c[(pd.to_datetime(c['deliveryDate']).dt.date == t.date()).to_numpy()]
505
+ if 'repeatHourFlag' in c:
506
+ c = c[~_flag(c['repeatHourFlag'])]
507
+ if 'postedDatetime' in c and len(c): # ERCOT re-posts when the reserve plan changes (6.4.9.1.2).
508
+ posted = pd.to_datetime(c['postedDatetime']) # For each product: the latest posting made before the
509
+ pick = [] # run that holds it; if none does, the first that does
510
+ for _, g in c.assign(_posted=posted).groupby('ASType'):
511
+ before = g['_posted'][g['_posted'] <= t]
512
+ pick.append(g[g['_posted'] == (before.max() if len(before) else g['_posted'].min())])
513
+ c = pd.concat(pick).drop(columns='_posted')
514
+ c = c.rename(columns={'ASType': 'product', 'quantity': 'mw'})
515
+ elif 'he' in c:
516
+ c = c[(c['he'] == t.hour + 1).to_numpy()]
517
+ c = c.assign(product=c['product'].map(lambda p: PRODUCT.get(str(p).strip(), p)))
518
+ return c[['product', 'mw', 'price']].apply(lambda s: pd.to_numeric(s) if s.name != 'product' else s).reset_index(drop=True)
519
+
520
+
521
+ def reserve_requirements(plan, when):
522
+ """DAM Ancillary Service Plan -> the reserve_requirements table (product, mw) for the run's hour: each product's
523
+ requirement from the latest posting made before the run, else the first posting. None if the hour is not in the plan.
524
+ The Non-Spin demand curve runs far past the requirement, so limits written against the Non-Spin requirement need this."""
525
+ c = plan.copy()
526
+ c.columns = c.columns.str.strip()
527
+ t = pd.Timestamp(when)
528
+ c = c[(c['hourEnding'].astype(str).str.slice(0, 2).astype(int) == t.hour + 1).to_numpy()]
529
+ c = c[(pd.to_datetime(c['deliveryDate']).dt.date == t.date()).to_numpy()]
530
+ if 'DSTFlag' in c:
531
+ c = c[~_flag(c['DSTFlag'])]
532
+ if not len(c):
533
+ return None
534
+ posted = pd.to_datetime(c['postedDatetime']) if 'postedDatetime' in c else pd.Series(t, index=c.index)
535
+ out = []
536
+ for p, g in c.assign(_posted=posted).groupby('ancillaryType'):
537
+ before = g['_posted'][g['_posted'] <= t]
538
+ g = g[g['_posted'] == (before.max() if len(before) else g['_posted'].min())]
539
+ out.append({'product': PRODUCT.get(str(p).strip(), p), 'mw': float(pd.to_numeric(g['quantity']).iloc[0])})
540
+ return pd.DataFrame(out)
541
+
542
+
543
+ def constraint_name(df):
544
+ """The id this adapter gives a constraint: '<constraint name>|<from station>|<to station>|<contingency>'.
545
+ Your shift_factors index must use the same ids."""
546
+ return (df['constraintName'].astype(str).str.strip() + '|' + df['fromStation'].fillna('').astype(str).str.strip() + '|'
547
+ + df['toStation'].fillna('').astype(str).str.strip() + '|' + df['contingencyName'].fillna('').astype(str).str.strip())
548
+
549
+
550
+ def _constraints(c, rules):
551
+ """the run's rows of SCED Shadow Prices and Binding Transmission Constraints -> the constraints table."""
552
+ c = c.copy()
553
+ c['name'] = constraint_name(c)
554
+ c['shadowPrice'] = pd.to_numeric(c['shadowPrice'], errors='coerce')
555
+ c = c.sort_values('shadowPrice').drop_duplicates('name', keep='last')
556
+ return pd.DataFrame({'name': c['name'].to_numpy(), 'limit': pd.to_numeric(c['limit'], errors='coerce').to_numpy(float),
557
+ 'flow': pd.to_numeric(c['value'], errors='coerce').to_numpy(float),
558
+ 'max_shadow_price': pd.to_numeric(c['maxShadowPrice'], errors='coerce').fillna(rules.default_max_shadow_price).to_numpy(float),
559
+ 'published_shadow_price': c['shadowPrice'].to_numpy(float),
560
+ 'competitive': (c['CCTStatus'].astype(str).str.strip().str.upper() != 'NONCOMP').to_numpy() if 'CCTStatus' in c else True}).dropna(subset=['limit', 'flow']).reset_index(drop=True)
561
+
562
+
563
+ def inputs(sced, when=None, reserve_offers=None, load_resources=None, reserve_demand=None, constraints=None, aggregate_offers=None,
564
+ shift_factors=None, resource_nodes=None, rules=None, controllable_loads=True, demand=None,
565
+ reserve_requirements=None, limit_values=None, storage_types=STORAGE_TYPES, zero_price_is_blank=None,
566
+ load_room='consumption-lpc', missing_shift_factors='drop', curve_points=NPT, curve='SCED2', mitigated=None,
567
+ mitigated_offer_caps=None, categories=None, reference_offers=None, battery_efficiency=None, quick_start=None,
568
+ startup_non_spin=None, status_overrides=None, offline_proxy=None,
569
+ qualified_mw=None):
570
+ """One SCED run's Inputs from ERCOT's published tables (pandas DataFrames, ERCOT's column names).
571
+
572
+ sced 60-Day SCED Disclosure rows, generation and storage together. One run, or a whole day with `when`
573
+ when the run's SCED timestamp. Needed when the tables hold more than one run
574
+ reserve_offers 60-Day SCED reserve offers -> reserve_offers
575
+ aggregate_offers 2-Day Aggregate SCED reserve offers, for days before February 3, 2026: restores real $0 offers
576
+ reference_offers the reserve offers of a day on or after February 3, 2026 (or zero_offer_habits() of it): says which
577
+ resources the restored $0 offers belong to. Without it only their total is right
578
+ load_resources 60-Day SCED Load Resource data -> resources of kind 'load'
579
+ reserve_demand Ancillary Service Demand Curves -> reserve_demand (switches reserves on)
580
+ constraints SCED Shadow Prices and Binding Constraints -> constraints
581
+ shift_factors, resource_nodes yours; passed straight through
582
+ rules the rulebook. Default: the one in force at `when`
583
+ controllable_loads False treats controllable Load Resources as fixed demand instead of dispatching them. A list
584
+ of names says which Load Resources are controllable (default: those with a base point or a bid curve)
585
+ demand MW to serve, if you have ERCOT's demand target (GTBD) or a forecast. Default: the sum of base
586
+ points. Controllable loads' consumption is taken off it either way
587
+ reserve_requirements, limit_values passed through (see opensced.schema())
588
+ storage_types resource types treated as storage
589
+ zero_price_is_blank read a reserve offer price of 0 as "not offered". Default: true before February 3, 2026, unless
590
+ the file has blank prices: then it is ERCOT's corrected file (posted April 10, 2026) and a 0 is a real offer
591
+ load_room 'consumption-lpc' (what a load can drop from where it is now) or 'mpc-lpc' (from its maximum)
592
+ missing_shift_factors 'drop' a constraint with no shift factors (listed in notes) or raise an 'error'
593
+ curve_points points on an offer curve in the files
594
+ curve 'SCED2': the curves SCED dispatched on, already mitigated (the clearing then runs once).
595
+ 'SCED1': the curves before mitigation; the clearing runs both steps and mitigates them itself
596
+ mitigated names of the resources whose offers are capped in step 2 (only used with curve='SCED1')
597
+ mitigated_offer_caps table resource, mw, price: their cost-based caps (see opensced.schema())
598
+ qualified_mw table resource, product, mw: the most of a reserve product a resource is qualified to carry. Awards
599
+ follow "a Resource's qualifications and telemetered Ancillary Service capabilities" (6.5.7.3(12));
600
+ the qualified amounts are registration data ERCOT does not publish. helpers.qualified_mw() reads
601
+ them off ERCOT's awards, and Day uses that on the day's own files. Here the default is no cap
602
+ beyond the telemetered capability
603
+ quick_start names of quick-start units. One that telemeters OFF is still offered ERCOT's proxy Non-Spin offer.
604
+ Day uses every unit seen in OFFQS during the day
605
+ offline_proxy names of units that are awarded Non-Spin through ERCOT's proxy offer while OFF, though they are not
606
+ quick-start. Which units is not published (it follows their Non-Spin qualification);
607
+ helpers.offline_proxy_units() reads them off ERCOT's awards, and Day uses that on the day's own files
608
+ status_overrides {resource: status} to use in place of the telemetered status of a generator or battery, e.g. the
609
+ status a unit had just before ERCOT's file printed it blank (Day's `blank_status='previous'`)
610
+ startup_non_spin names of units in STARTUP that keep Non-Spin (6.4.9.1.1(4)-(5)): quick-start units, and units
611
+ that carried off-line Non-Spin before starting while ERCOT has Non-Spin deployed. Every other unit
612
+ in STARTUP carries no reserve. Day works the names out (see Day.startup_non_spin)
613
+ battery_efficiency {resource: share of charging energy stored}, e.g. helpers.battery_efficiency(sced). ERCOT does not
614
+ publish it; a battery not named gets rules.storage_charge_efficiency
615
+ categories {resource: category} to override the category taken from the resource type, e.g. 'qf'
616
+
617
+ Reserves are only cleared when reserve_demand is given. Constraints are only enforced when shift_factors is given."""
618
+ x = normalize(sced)
619
+ if when is None:
620
+ if x[TS].nunique() != 1:
621
+ raise ValueError(f'the SCED table holds {x[TS].nunique():,} runs: say which with when="YYYY-MM-DD HH:MM"')
622
+ when = x[TS].iloc[0]
623
+ else:
624
+ x = _run_rows(x, when, TS)
625
+ if x.empty:
626
+ raise ValueError(f'no SCED run at {when} in the SCED table')
627
+ when = x[TS].iloc[0]
628
+ rules = rules or ALL.on(when)
629
+ if reserve_demand is not None: # never clear with a product nobody can carry by accident
630
+ caps = [c for p in rules.products for c in p.capability_columns if c in GEN_CAPABILITY]
631
+ empty = [c for c in caps if c not in x or not pd.to_numeric(x[c], errors='coerce').notna().any()]
632
+ if empty and len(empty) < len(caps):
633
+ raise ValueError(f'the SCED table has no values in {", ".join(empty)} at {when}, so no generator or battery could carry '
634
+ f'that product. Files of December 2025 downloaded early lack these columns; ERCOT\'s API has them')
635
+ if status_overrides:
636
+ given = x[RES].astype(str).str.strip().map(status_overrides)
637
+ if given.notna().any():
638
+ x = x.copy()
639
+ x.loc[given.notna(), 'Telemetered Resource Status'] = given[given.notna()]
640
+ if startup_non_spin is not None and len(startup_non_spin): # a starting unit that keeps its Non-Spin
641
+ st = x['Telemetered Resource Status'].astype(str).str.strip().str.upper()
642
+ ns = x[RES].astype(str).str.strip().isin(set(startup_non_spin)) & (st == 'STARTUP')
643
+ if ns.any():
644
+ x = x.copy()
645
+ x.loc[ns, 'Telemetered Resource Status'] = 'STARTUP-NS'
646
+ res, eo, sto, lim, status, disp = _sced_tables(x, rules, storage_types, curve_points, curve)
647
+ proxied = set(quick_start if quick_start is not None else ()) | set(offline_proxy if offline_proxy is not None else ())
648
+ if proxied: # a quick-start (or so-qualified) unit that telemeters OFF
649
+ qs = res['name'].isin(proxied) & (res['status'] == 'OFF')
650
+ res.loc[qs, 'status'] = 'OFF-QS'
651
+ status.update({n: 'OFF-QS' for n in res.loc[qs, 'name']})
652
+ if len(sto):
653
+ known = sto['resource'].map(dict(battery_efficiency)) if battery_efficiency is not None else pd.Series(np.nan, index=sto.index)
654
+ sto['efficiency'] = pd.to_numeric(known, errors='coerce').fillna(rules.storage_charge_efficiency).to_numpy(float)
655
+ if categories:
656
+ res['category'] = res['name'].map(categories).fillna(res['category'])
657
+ res['mitigated'] = res['name'].isin(set(mitigated)) if mitigated is not None else False
658
+ own = None
659
+ if load_resources is not None:
660
+ load_resources = load_columns(load_resources)
661
+ L = _run_rows(load_resources, when, 'SCEDTimestamp')
662
+ lres, leo, llim, own, moves = _load_tables(L, rules, controllable_loads, load_room)
663
+ if reserve_offers is None: # no offers: loads that only carry reserves add nothing
664
+ lres = lres[lres['type'] == 'CLR']
665
+ lres = lres[~lres['name'].isin(res['name'])]
666
+ mine = lambda t: t[t['resource'].isin(lres['name'])]
667
+ status.update(zip(lres['name'], lres['status']))
668
+ disp.update({k: v for k, v in moves.items() if k in set(lres['name'])})
669
+ res = pd.concat([res, lres], ignore_index=True)
670
+ eo = pd.concat([eo, mine(leo)], ignore_index=True)
671
+ lim, own = pd.concat([lim, mine(llim)], ignore_index=True), mine(own)
672
+ if qualified_mw is not None and len(qualified_mw) and len(lim):
673
+ q = qualified_mw.assign(resource=qualified_mw['resource'].astype(str).str.strip()).set_index(['resource', 'product'])['mw']
674
+ cap = q[~q.index.duplicated()].reindex(pd.MultiIndex.from_frame(lim[['resource', 'product']])).to_numpy(float)
675
+ lim = lim.assign(mw=np.where(np.isfinite(cap), np.minimum(lim['mw'].to_numpy(float), cap), lim['mw'].to_numpy(float)))
676
+ ro = None
677
+ if reserve_offers is not None:
678
+ reserve_offers = offer_columns(reserve_offers)
679
+ habits = reference_offers
680
+ if habits is not None and 'hour' not in habits: # a raw day of offers: reduce it to its $0 cells
681
+ habits = zero_offer_habits(habits)
682
+ load_names = None if load_resources is None else set(L['resourceName'].astype(str).str.strip())
683
+ ro = _reserve_offers(_run_rows(reserve_offers, when, 'SCEDTimestamp'), status, when, rules, zero_price_is_blank,
684
+ None if aggregate_offers is None else _run_rows(aggregate_offers, when, 'SCEDTimestamp'), load_names, habits)
685
+ zero_report = ro.attrs.get('zero_offers')
686
+ if own is not None:
687
+ ro = pd.concat([ro, own[own['product'].isin(rules.product_names)]], ignore_index=True)
688
+ cons = None
689
+ if constraints is not None:
690
+ cons = _constraints(_run_rows(constraints, when, 'SCEDTimestamp'), rules)
691
+ notes = {'published_shadow_prices': cons.set_index('name')['published_shadow_price'] if cons is not None else None}
692
+ if reserve_offers is not None and zero_report is not None:
693
+ notes['zero_offers_restored'] = zero_report
694
+ if cons is not None: # enforce the constraints that have shift factors
695
+ have = cons['name'].isin(shift_factors.index) if shift_factors is not None else pd.Series(False, index=cons.index)
696
+ notes['constraints_published'] = len(cons)
697
+ notes['constraints_without_shift_factors'] = list(cons['name'][~have])
698
+ if missing_shift_factors == 'error' and shift_factors is not None and (~have).any():
699
+ raise ValueError(f'shift_factors: no row for {int((~have).sum()):,} of {len(cons):,} constraints, e.g. {cons["name"][~have].iloc[0]!r}')
700
+ cons = cons[have].reset_index(drop=True) if have.any() else None
701
+ curves = None
702
+ if reserve_demand is not None:
703
+ curves = _reserve_demand(reserve_demand, when)
704
+ lacking = [d for d in rules.demand_names if d not in set(curves['product'])]
705
+ if lacking: # never clear without reserves by accident
706
+ raise ValueError(f'reserve_demand: no demand curve for {", ".join(lacking)} in hour ending {pd.Timestamp(when).hour + 1} of '
707
+ f'{pd.Timestamp(when).date()}. The demand curve file is incomplete for this run. Pass reserve_demand=None '
708
+ f'to clear energy only on purpose')
709
+ served = float(res['output'].sum()) if demand is None else float(demand) + float(res.loc[res['type'] == 'CLR', 'output'].sum())
710
+ return Inputs(resources=res, demand=served, mitigated=(curve == 'SCED2'), mitigated_offer_caps=mitigated_offer_caps, reserve_requirements=reserve_requirements, limit_values=limit_values, energy_offers=eo, storage=sto, reserve_limits=lim,
711
+ reserve_offers=ro, reserve_demand=curves,
712
+ constraints=None if cons is None else cons.drop(columns='published_shadow_price'),
713
+ shift_factors=shift_factors, resource_nodes=resource_nodes, time=pd.Timestamp(when), notes=notes)
714
+
715
+
716
+ # ---------------------------------------------------------------- a folder of downloaded files
717
+ def _read(folder, stem):
718
+ for ext in ('.parquet', '.csv', '.csv.gz'):
719
+ f = os.path.join(folder, stem + ext)
720
+ if os.path.exists(f):
721
+ return pd.read_parquet(f) if ext == '.parquet' else pd.read_csv(f, low_memory=False)
722
+ return None
723
+
724
+
725
+ class Day:
726
+ """One operating day of ERCOT files, loaded by read_day().
727
+
728
+ times the SCED runs in the folder
729
+ inputs(time) that run's Inputs
730
+ published_lambda() Series time -> ERCOT's system lambda
731
+ published_node_prices() DataFrame time x settlement point
732
+ published_reserve_prices() DataFrame time x product
733
+ published_shadow_prices() DataFrame time x constraint"""
734
+
735
+ def __init__(self, folder):
736
+ self.folder = folder
737
+ t = {k: _read(folder, stem) for k, stem in FILES.items()}
738
+ t['reserve_offers'], t['reference_offers'] = offer_columns(t['reserve_offers']), offer_columns(t['reference_offers'])
739
+ t['load_resources'] = load_columns(t['load_resources'])
740
+ if t['gen'] is None:
741
+ have = ', '.join(sorted(os.listdir(folder))) if os.path.isdir(folder) else 'the folder does not exist'
742
+ raise FileNotFoundError(f'{folder}: no {FILES["gen"]}.parquet or .csv (the 60-Day SCED Disclosure for generation '
743
+ f'resources). Found: {have}. See help(opensced.market("ercot").adapter) for the file names')
744
+ parts = [normalize(t['gen'])] + ([normalize(t['esr'])] if t['esr'] is not None else [])
745
+ self.sced = pd.concat(parts, ignore_index=True)
746
+ self.tables = t
747
+ self.times = sorted(self.sced[TS].dropna().unique())
748
+ self.missing = [FILES[k] for k in ('esr', 'reserve_offers', 'load_resources', 'reserve_demand', 'reserve_plan', 'constraints') if t[k] is None]
749
+ if t['reserve_plan'] is None and t['reserve_demand'] is not None:
750
+ warnings.warn(f'{folder}: no {FILES["reserve_plan"]} file (DAM Ancillary Service Plan, NP4-33-CD). Limits written against a '
751
+ f'reserve requirement then use the demand curve\'s total MW; for Non-Spin that is far above the requirement, '
752
+ f'so the limit on Non-Spin from non-controllable loads cannot bind', stacklevel=2)
753
+ kinds = self.sced['Resource Type'].astype(str).str.strip() if 'Resource Type' in self.sced else pd.Series('', index=self.sced.index)
754
+ if kinds.isin(STORAGE_TYPES).any() and 'SOC' not in self.sced:
755
+ warnings.warn(f'{folder}: the day has storage resources but no state of charge column (SOC, or "State of Charge" in the '
756
+ f'website\'s file), so batteries are cleared without an energy limit', stacklevel=2)
757
+ if not any(c in self.sced for c in GEN_CAPABILITY):
758
+ warnings.warn(f'{folder}: no reserve capability columns (ASCapREGUP, or "AS Capability REGUP" in the website\'s file, ...), '
759
+ f'so no generator or battery can carry reserves', stacklevel=2)
760
+ self._by_run = dict(tuple(self.sced.groupby(TS)))
761
+ self._curves = None # demand curves, cut by hour once (the full report is large)
762
+ rd = t['reserve_demand']
763
+ if rd is not None and ('hourEnding' in rd or 'he' in rd):
764
+ he = rd['hourEnding'].astype(str).str.slice(0, 2).astype(int) if 'hourEnding' in rd else rd['he'].astype(int)
765
+ self._curves = {h: g for h, g in rd.groupby(he.to_numpy())}
766
+ self._habits = None if t['reference_offers'] is None else zero_offer_habits(t['reference_offers'])
767
+ from opensced.markets.ercot import helpers
768
+ self.battery_efficiency = helpers.battery_efficiency(self.sced) # read off the day's own Reg-Down awards
769
+ self.quick_start = sorted(set(self.sced.loc[self.sced['Telemetered Resource Status'].astype(str).str.strip() == 'OFFQS', RES]))
770
+ self.offline_proxy = helpers.offline_proxy_units(self.sced, t['reserve_offers']) if t['reserve_offers'] is not None else []
771
+ self.qualified_mw = helpers.qualified_mw(t['load_resources']) if t['load_resources'] is not None else None
772
+ self._startup = self._startups(t['reserve_deployments'])
773
+ self.blank_status = 'previous' # or 'none': see inputs()
774
+ self._before_blank = self._previous_status()
775
+ if t['reserve_deployments'] is None and self._startup['carried']:
776
+ warnings.warn(f'{folder}: no {FILES["reserve_deployments"]} file (when ERCOT had Non-Spin deployed: columns product, '
777
+ f'start, end). {len(self._startup["carried"])} unit(s) that carried off-line Non-Spin start up on this day; '
778
+ f'without the file they are given no Non-Spin while starting', stacklevel=2)
779
+ self._split = {} # per-run reports, cut by run once
780
+ for k in ('reserve_offers', 'load_resources', 'constraints', 'aggregate_offers'):
781
+ if t[k] is not None:
782
+ when = pd.Series(self._snap(t[k]['SCEDTimestamp']), index=t[k].index)
783
+ self._split[k] = {u: g for u, g in t[k].groupby(when)}
784
+
785
+ def _startups(self, deployments):
786
+ """What decides which starting units keep Non-Spin: the stretches of STARTUP of every unit that carried an
787
+ off-line Non-Spin award in the stretch just before it, and the times ERCOT had Non-Spin deployed."""
788
+ s = self.sced[[TS, RES, 'Telemetered Resource Status']].copy()
789
+ s.columns = ['t', 'n', 'st']
790
+ s['st'] = s['st'].astype(str).str.strip()
791
+ s['ns'] = pd.to_numeric(self.sced['ASAwardsNSPIN'], errors='coerce').fillna(0.0).to_numpy() if 'ASAwardsNSPIN' in self.sced else 0.0
792
+ names = s.loc[s['st'] == 'STARTUP', 'n'].unique()
793
+ carried = {} # unit -> the runs of its startups that follow a Non-Spin award
794
+ for n, g in s[s['n'].isin(names)].sort_values('t').groupby('n'):
795
+ g = g[g['st'] != 'NA'] # a status ERCOT prints while a unit changes state
796
+ block = (g['st'] != g['st'].shift()).cumsum()
797
+ had = g.groupby(block)['ns'].max().shift(1).fillna(0.0) > 0
798
+ runs = g.loc[(g['st'] == 'STARTUP') & block.map(had).to_numpy(), 't']
799
+ if len(runs):
800
+ carried[n] = set(runs)
801
+ spans = []
802
+ if deployments is not None and len(deployments):
803
+ d = deployments.rename(columns=str.lower)
804
+ if 'product' in d:
805
+ d = d[d['product'].astype(str).str.replace('-', '').str.lower().isin(('nonspin', 'nspin'))]
806
+ spans = list(zip(pd.to_datetime(d['start']), pd.to_datetime(d['end'])))
807
+ return {'carried': carried, 'deployed': spans}
808
+
809
+ def _previous_status(self):
810
+ """For every unit-run whose status ERCOT's file leaves blank (printed NA): the last status the unit had before it.
811
+ -> {run: {resource: status}}. A unit blank from the first run of the day has none."""
812
+ s = self.sced[[TS, RES, 'Telemetered Resource Status']].copy()
813
+ s.columns = ['t', 'n', 'st']
814
+ st = s['st'].astype(str).str.strip().str.upper()
815
+ blank = s['st'].isna() | st.isin(('', 'NA', 'NAN', 'NONE'))
816
+ if not blank.any():
817
+ return {}
818
+ s['st'] = st.where(~blank)
819
+ s = s.sort_values(['n', 't'])
820
+ s['prev'] = s.groupby('n')['st'].ffill()
821
+ b = s[s['st'].isna() & s['prev'].notna()]
822
+ return {t: dict(zip(g['n'], g['prev'])) for t, g in b.groupby('t')}
823
+
824
+ def startup_non_spin(self, time):
825
+ """Units in STARTUP at this run that keep Non-Spin (Protocols 6.4.9.1.1(4)-(5)): the day's quick-start units,
826
+ and, while ERCOT has Non-Spin deployed, units that carried an off-line Non-Spin award just before starting.
827
+ Measured on 13 days with deployment times (7,353 unit-runs in STARTUP, 37 awarded): 36 of the 39 unit-runs this
828
+ awards or ERCOT awarded agree to 0.5 MW; the rule it replaces (every starting unit, off-line offer) got 33 of 122."""
829
+ t = pd.Timestamp(time)
830
+ out = set(self.quick_start)
831
+ if any(a <= t <= b for a, b in self._startup['deployed']):
832
+ out |= {n for n, runs in self._startup['carried'].items() if t in runs}
833
+ return sorted(out)
834
+
835
+ def inputs(self, time, shift_factors=None, resource_nodes=None, rules=None, blank_status=None, **options):
836
+ """The run's Inputs. blank_status says what to do with a unit whose status ERCOT's file leaves blank (printed NA,
837
+ usually for one run while it changes state): 'previous' (the default, `self.blank_status`) gives it the last
838
+ status it had; 'none' holds it at its base point with no reserves. Measured on 33 days, on the 6,166 runs that
839
+ have such a unit: 'previous' changes the system price by more than $0.05 in 15 runs, every one closer to
840
+ ERCOT's (January 28, 2026 07:00: four quick-start hydro units keep their ECRS in the run they come on, error
841
+ $6.18 -> $0.00), and none further away."""
842
+ t = pd.Timestamp(time)
843
+ if t not in self._by_run:
844
+ near = min(self.times, key=lambda u: abs(u - t))
845
+ raise KeyError(f'no SCED run at {t}. The nearest is {near}. See .times for all {len(self.times):,}')
846
+ cut = lambda k: None if self.tables[k] is None else self._split[k].get(t, self.tables[k].iloc[:0])
847
+ curves = self.tables['reserve_demand'] if self._curves is None else self._curves.get(t.hour + 1, self.tables['reserve_demand'].iloc[:0])
848
+ options.setdefault('reference_offers', self._habits)
849
+ options.setdefault('battery_efficiency', self.battery_efficiency)
850
+ options.setdefault('quick_start', self.quick_start)
851
+ options.setdefault('offline_proxy', self.offline_proxy)
852
+ if self.qualified_mw is not None and len(self.qualified_mw):
853
+ options.setdefault('qualified_mw', self.qualified_mw)
854
+ options.setdefault('startup_non_spin', self.startup_non_spin(t))
855
+ if (blank_status or self.blank_status) == 'previous':
856
+ options.setdefault('status_overrides', self._before_blank.get(t, {}))
857
+ elif (blank_status or self.blank_status) != 'none':
858
+ raise ValueError(f"blank_status is 'none' or 'previous', not {blank_status or self.blank_status!r}")
859
+ if self.tables['reserve_plan'] is not None:
860
+ options.setdefault('reserve_requirements', reserve_requirements(self.tables['reserve_plan'], t))
861
+ return inputs(self._by_run[t], None, cut('reserve_offers'), cut('load_resources'), curves,
862
+ cut('constraints'), cut('aggregate_offers'), shift_factors, resource_nodes, rules, **options)
863
+
864
+ def published_lambda(self):
865
+ x = self._need('system_lambda')
866
+ col = next(c for c in ('systemLambda', 'cappedSystemLambda', 'SystemLambda') if c in x)
867
+ return pd.Series(pd.to_numeric(x[col]).to_numpy(), index=self._snap(x['SCEDTimestamp']), name='system_lambda').rename_axis('time')
868
+
869
+ def published_node_prices(self):
870
+ x = self._need('lmp')
871
+ x = x.rename(columns=lambda c: c.strip())
872
+ node = next(c for c in ('SettlementPoint', 'settlementPoint') if c in x)
873
+ price = next(c for c in ('LMP', 'cappedLMP', 'CappedLMP') if c in x)
874
+ f = pd.DataFrame({'time': self._snap(x['SCEDTimestamp']), 'node': x[node].astype(str).str.strip(), 'price': pd.to_numeric(x[price]).to_numpy()})
875
+ return f.drop_duplicates(['time', 'node']).pivot(index='time', columns='node', values='price')
876
+
877
+ def published_reserve_prices(self):
878
+ x = self._need('reserve_prices')
879
+ col = next(c for c in ('cappedMCPC', 'MCPC') if c in x)
880
+ f = pd.DataFrame({'time': self._snap(x['SCEDTimestamp']), 'product': x['ASType'].map(lambda p: MCPC.get(str(p).strip(), p)), 'price': pd.to_numeric(x[col]).to_numpy()})
881
+ return f.drop_duplicates(['time', 'product']).pivot(index='time', columns='product', values='price')
882
+
883
+ def published_shadow_prices(self):
884
+ x = self._need('constraints')
885
+ f = pd.DataFrame({'time': self._snap(x['SCEDTimestamp']), 'constraint': constraint_name(x), 'price': pd.to_numeric(x['shadowPrice'], errors='coerce').to_numpy()})
886
+ return f.sort_values('price').drop_duplicates(['time', 'constraint'], keep='last').pivot(index='time', columns='constraint', values='price')
887
+
888
+ def _need(self, key):
889
+ if self.tables[key] is None:
890
+ raise FileNotFoundError(f'{self.folder}: no {FILES[key]}.parquet, .csv or .csv.gz. That is ERCOT\'s {REPORTS.get(key, key)}; '
891
+ f'docs/ercot.md says where to download it')
892
+ return self.tables[key]
893
+
894
+ def _snap(self, ts):
895
+ """a report's SCED timestamps -> the run times of the SCED disclosure (same timestamp, else same 5 minutes)."""
896
+ ts = pd.to_datetime(ts)
897
+ known = set(pd.DatetimeIndex(self.times))
898
+ by5 = {pd.Timestamp(t).floor('5min'): pd.Timestamp(t) for t in self.times}
899
+ return ts.where(ts.isin(known), ts.dt.floor('5min').map(by5)).to_numpy()
900
+
901
+ def __repr__(self):
902
+ day = pd.Timestamp(self.times[0]).date() if self.times else '?'
903
+ out = [f'ERCOT day {day}: {len(self.times):,} SCED runs, {self.sced[RES].nunique():,} resources']
904
+ for k, stem in FILES.items():
905
+ out.append(f' {stem:<28} ' + ('missing' if self.tables[k] is None else f'{len(self.tables[k]):,} rows'))
906
+ return '\n'.join(out)
907
+
908
+
909
+ def read_day(folder):
910
+ """Load a folder holding one operating day of ERCOT files (names in this module's docstring). -> Day"""
911
+ return Day(folder)