Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions docs/market-data.md
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,11 @@ uv run python -m examples.price_history rt --point LZ_HOUSTON --output rt-histor
The export uses unbounded `backfill()`, so it includes bundle-only publications
and archives older than the bundles. Optional `--date-from` and `--date-to`
filter **delivery dates after download**; they do not reduce source downloads.
To limit downloads explicitly, add `--posted-from` and/or `--posted-to` with
inclusive ERCOT-local publication timestamps without offsets. These bounds use
original archive metadata, excluding bundle-only publications without that
metadata and corrections posted outside the chosen period. See the
[bounded export example](../examples/README.md#retained-settlement-price-history).
Unbounded backfills return bundle rows before fetching archive listings;
they then stream the uncovered archives. Large histories still take time.
For bounded recent data use the
Expand Down
21 changes: 16 additions & 5 deletions examples/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,24 @@ and DST flags. Overlapping copies of a publication are retrieved once; distinct
corrections remain separate, and rows are not sorted.

Optional `--date-from YYYY-MM-DD` and `--date-to YYYY-MM-DD` filter inclusive
**delivery dates**, after download. They do not supply publication bounds or
reduce the amount downloaded. These are maximum-history workflows and can take
considerable time; use `market_day` for bounded recent queries. The output file
is overwritten, and an interrupted run can leave a partial file.
**delivery dates**, after download. They do not reduce the amount downloaded.
To limit downloads, explicitly select inclusive **publication times** with
`--posted-from` and/or `--posted-to`, using ERCOT-local timestamps without offsets:

```sh
uv run python -m examples.price_history dam --point HB_HOUSTON --posted-from 2014-05-01T00:00 --posted-to 2014-05-02T00:00 --date-from 2014-05-02 --date-to 2014-05-02 --output dam-2014-05-02.jsonl
```

Publication bounds use original archive metadata; bundle-only publications without
that metadata are excluded. They can also exclude later corrections for the same
delivery day. Omit both publication bounds for maximum retained history. Large
exports can take considerable time; use `market_day` for bounded recent queries.
The output file is overwritten, and an interrupted run can leave a partial file.

The price-history exporter is checked with saved original DAM/RT CSV samples and
mocked archive/bundle listings, including a bundle-only publication and an
archive-only publication. This verifies its use of the existing backfill reader;
archive-only publication. Bounded checks verify that an unrelated month's bundle
is skipped while the selected archive and delivery-date filter are retained.
This verifies its use of the existing backfill reader;
it is not a new live comparison of every retained RT price row. See the
[market-data guide](../docs/market-data.md) for verified ranges and remaining gaps.
30 changes: 27 additions & 3 deletions examples/price_history.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Export retained DAM or RT settlement-price history as typed JSON Lines."""

import argparse
from datetime import date
from datetime import date, datetime
from pathlib import Path
from typing import Literal

Expand All @@ -17,15 +17,23 @@ def export_price_history(
*,
date_from: date | None = None,
date_to: date | None = None,
posted_from: datetime | None = None,
posted_to: datetime | None = None,
) -> int:
"""Combine bundles and archives, filtering delivery dates after decoding.

Unbounded publication selection includes bundle-only reports and older
individual archives. Distinct corrections remain separate. Output is not
sorted, and a date filter does not reduce the source downloads.
sorted. Delivery-date filters apply after download; optional inclusive
ERCOT-local publication bounds limit downloads using archive metadata.
"""
if date_from and date_to and date_from > date_to:
raise ValueError("date_from must not exceed date_to")
for bound in (posted_from, posted_to):
if bound is not None and bound.utcoffset() is not None:
raise ValueError("Publication bounds must be ERCOT-local without an offset")
if posted_from and posted_to and posted_from > posted_to:
raise ValueError("posted_from must not exceed posted_to")

def selected(
row: np4_190_cd.DamStlmntPntPricesRow | np6_905_cd.SppNodeZoneHubRow,
Expand All @@ -48,7 +56,15 @@ def selected(
else client.np6_905_cd.spp_node_zone_hub_history
)
path.parent.mkdir(parents=True, exist_ok=True)
return write_rows(path, history.backfill(where=selected, batch_size=25))
return write_rows(
path,
history.backfill(
posted_from=posted_from,
posted_to=posted_to,
where=selected,
batch_size=25,
),
)


if __name__ == "__main__":
Expand All @@ -58,6 +74,12 @@ def selected(
parser.add_argument("--output", type=Path, required=True, help="Output JSONL file")
parser.add_argument("--date-from", type=date.fromisoformat, help="Delivery date")
parser.add_argument("--date-to", type=date.fromisoformat, help="Delivery date")
for flag in ("--posted-from", "--posted-to"):
parser.add_argument(
flag,
type=datetime.fromisoformat,
help="Inclusive publication time, ERCOT-local ISO timestamp without offset",
)
args = parser.parse_args()
with Client() as ercot:
count = export_price_history(
Expand All @@ -67,5 +89,7 @@ def selected(
args.output,
date_from=args.date_from,
date_to=args.date_to,
posted_from=args.posted_from,
posted_to=args.posted_to,
)
print(f"{args.market}_prices: {count} rows")
45 changes: 39 additions & 6 deletions tests/test_backfill.py
Original file line number Diff line number Diff line change
Expand Up @@ -353,6 +353,7 @@ def test_generic_uppercase_csv_reader_does_not_treat_missing_report_as_sparse_ta
run(source, "np7_535_sg", "path_adders_history")


@pytest.mark.parametrize("bounded", [False, True])
@pytest.mark.parametrize(
("market", "product", "delivery_day", "price"),
[
Expand All @@ -361,11 +362,11 @@ def test_generic_uppercase_csv_reader_does_not_treat_missing_report_as_sparse_ta
],
)
def test_price_history_export_uses_delivery_dates_and_both_sources(
tmp_path, market, product, delivery_day, price
tmp_path, market, product, delivery_day, price, bounded
):
report = zipped({"report.csv": (INPUTS / f"{product}.csv").read_bytes()})
source = Source(
[document(1), document(2)],
[document(1, "2014-05-01T12:00:00"), document(2)],
[document(-1)],
{
("bundle", (-1,)): zipped({"2.report.zip": report, "3.report.zip": report}),
Expand All @@ -376,8 +377,12 @@ def test_price_history_export_uses_delivery_dates_and_both_sources(
def handle(request):
if "b2clogin" not in request.url.host:
assert product in request.url.path
assert "postDatetimeFrom" not in request.url.params
assert "postDatetimeTo" not in request.url.params
if "postDatetimeFrom" in request.url.params:
assert bounded
assert request.url.params["postDatetimeFrom"] == "2014-05-01T00:00:00"
assert request.url.params["postDatetimeTo"] == "2014-05-02T00:00:00"
else:
assert "postDatetimeTo" not in request.url.params
return source(request)

path = tmp_path / "history" / "prices.jsonl"
Expand All @@ -392,14 +397,18 @@ def handle(request):
path,
date_from=delivery_day,
date_to=delivery_day,
posted_from=datetime(2014, 5, 1) if bounded else None,
posted_to=datetime(2014, 5, 2) if bounded else None,
)
rows = [json.loads(line) for line in path.read_text().splitlines()]
assert count == len(rows) == 3
assert count == len(rows) == (1 if bounded else 3)
assert all(r["deliveryDate"] == delivery_day.isoformat() for r in rows)
assert all(r["settlementPoint"] == "AMISTAD_ALL" for r in rows)
assert all(r["settlementPointPrice"] == price for r in rows)
assert all(r["DSTFlag"] is False for r in rows)
assert source.downloads == [("bundle", [-1]), ("archive", [1])]
assert source.downloads == (
[("archive", [1])] if bounded else [("bundle", [-1]), ("archive", [1])]
)
assert (
export_price_history(
client, market, "AMISTAD_ALL", path, date_from=date(2020, 1, 1)
Expand All @@ -409,6 +418,30 @@ def handle(request):
assert path.read_text() == ""


@pytest.mark.parametrize(
("start", "end", "message"),
[
("2014-05-02", "2014-05-01", "posted_from must not exceed posted_to"),
("2014-05-01T00:00:00Z", "2014-05-02", "without an offset"),
],
)
def test_price_history_invalid_publication_bounds_preserve_output(
tmp_path, start, end, message
):
path = tmp_path / "prices.jsonl"
path.write_text("existing export\n")
with Client() as client, pytest.raises(ValueError, match=message):
export_price_history(
client,
"dam",
"HB_HOUSTON",
path,
posted_from=datetime.fromisoformat(start),
posted_to=datetime.fromisoformat(end),
)
assert path.read_text() == "existing export\n"


@pytest.mark.parametrize("bundled", [False, True])
def test_unbounded_first_rows_do_not_wait_for_later_archive_pages(bundled):
report = price_report()
Expand Down