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
28 changes: 24 additions & 4 deletions pytr/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -398,13 +398,27 @@ def formatter(prog):
default=0,
type=int,
)
parser_export_transactions.add_argument(
"--from_timestamp",
help="Include data from this exact timestamp onwards; overrides --last_days. Local time if no offset given (e.g. 2026-10-01T07:30:00), or with UTC offset (e.g. 2026-10-01T05:30:00+00:00)",
metavar="TIMESTAMP",
default=None,
type=str,
)
parser_export_transactions.add_argument(
"--days_until",
help="Include data up to N days ago (0 = include all days)",
metavar="DAYS",
default=0,
type=int,
)
parser_export_transactions.add_argument(
"--until_timestamp",
help="Include data up to this exact timestamp; overrides --days_until. Local time if no offset given (e.g. 2026-10-01T07:30:00), or with UTC offset (e.g. 2026-10-01T05:30:00+00:00)",
metavar="TIMESTAMP",
default=None,
type=str,
)
parser_export_transactions.add_argument(
"--store-event-database",
default=True,
Expand Down Expand Up @@ -559,17 +573,23 @@ def main():

# Compute the timestamp range to get data for
not_before = 0
if hasattr(args, "last_days"):
if hasattr(args, "from_timestamp") and args.from_timestamp is not None:
not_before = datetime.fromisoformat(args.from_timestamp).astimezone().timestamp()
elif hasattr(args, "last_days"):
if args.last_days < 0:
not_before = float(-1)
elif args.last_days == 0:
not_before = float(0)
else:
not_before = (datetime.now().astimezone() - timedelta(days=args.last_days)).timestamp()
not_after = (
(datetime.now().astimezone() - timedelta(days=args.days_until)).timestamp()
if hasattr(args, "days_until") and args.days_until > 0
else float("inf")
datetime.fromisoformat(args.until_timestamp).astimezone().timestamp()
if hasattr(args, "until_timestamp") and args.until_timestamp is not None
else (
(datetime.now().astimezone() - timedelta(days=args.days_until)).timestamp()
if hasattr(args, "days_until") and args.days_until > 0
else float("inf")
)
)

if args.command == "login":
Expand Down
11 changes: 6 additions & 5 deletions pytr/timeline.py
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ async def get_next_timeline_transactions(self, response):
self.num_timelines += 1
added_last_event = False
for event in response["items"]:
event_timestamp = datetime.fromisoformat(event["timestamp"][:19]).timestamp()
event_timestamp = datetime.fromisoformat(event["timestamp"][:19] + "+00:00").timestamp()
if event_timestamp > self.not_before:
if event_timestamp < self.not_after:
event["source"] = "timelineTransaction"
Expand Down Expand Up @@ -161,7 +161,7 @@ async def get_next_timeline_activity_log(self, response):
self.num_timelines += 1
added_last_event = False
for event in response["items"]:
event_timestamp = datetime.fromisoformat(event["timestamp"][:19]).timestamp()
event_timestamp = datetime.fromisoformat(event["timestamp"][:19] + "+00:00").timestamp()
if event_timestamp > self.not_before:
if event_timestamp < self.not_after:
event["source"] = "timelineActivity"
Expand Down Expand Up @@ -308,7 +308,7 @@ def finish_timeline_details(self):
if self.fetch_from_tr and (self.not_before != 0 or self.not_after != float("inf")):
self.log.info("Throwing away outdated events...")
for i in range(len(old_events) - 1, -1, -1):
ts = datetime.fromisoformat(old_events[i]["timestamp"][:19]).timestamp()
ts = datetime.fromisoformat(old_events[i]["timestamp"][:19] + "+00:00").timestamp()
if ts > self.not_before and ts < self.not_after:
del old_events[i]

Expand Down Expand Up @@ -376,12 +376,13 @@ def finish_timeline_details(self):
e
for e in self.events
if "details" in e
and datetime.fromisoformat(e["timestamp"][:19]).timestamp() >= self.not_before
and datetime.fromisoformat(e["timestamp"][:19]).timestamp() <= self.not_after
and datetime.fromisoformat(e["timestamp"][:19] + "+00:00").timestamp() >= self.not_before
and datetime.fromisoformat(e["timestamp"][:19] + "+00:00").timestamp() <= self.not_after
]
self.log.info(f"Replaying {len(filtered)} events from database (out of {len(self.events)} total)...")
self.all_detail = len(filtered)
for event in filtered:
self.event_callback(event)
self.events = filtered

self.dl_done = True
120 changes: 119 additions & 1 deletion tests/test_export_transactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
import io
import subprocess
import sys
from datetime import datetime
from datetime import datetime, timedelta, timezone
from pathlib import Path

from pytr.event import Event
Expand Down Expand Up @@ -164,3 +164,121 @@ def test_cli_golden(tmp_path):
actual = out_file.read_text(encoding="utf-8")
expected = GOLDEN_CSV.read_text(encoding="utf-8")
assert actual == expected


# ---------------------------------------------------------------------------
# Timestamp / cutoff filtering tests
#
# Event timestamps in all_events_test.json (all UTC):
# buy 2024-02-20T16:32:07
# deposit 2024-06-03T17:07:26
# split 2024-06-26T08:06:40
# sell 2025-03-14T07:03:14
# dividend 2025-10-23T14:19:56
# ---------------------------------------------------------------------------

UTC = timezone.utc


def _ts(iso_utc: str) -> float:
"""Parse an ISO string with explicit UTC offset to a POSIX timestamp."""
return datetime.fromisoformat(iso_utc).timestamp()


def load_events_filtered(output_dir, not_before=0.0, not_after=float("inf")):
tl = Timeline(
tr=None,
output_path=output_dir,
store_event_database=False,
load_event_database=ALL_EVENTS_FILE,
not_before=not_before,
not_after=not_after,
)
asyncio.run(tl.tl_loop())
return tl.events


def event_ids(events):
return {e["id"] for e in events}


def test_not_before_utc_excludes_early_events(tmp_path):
"""not_before after deposit cuts buy and deposit, keeps split/sell/dividend."""
# 2024-06-03T18:00:00Z is after deposit (17:07 UTC) and buy (Feb)
not_before = _ts("2024-06-03T18:00:00+00:00")
events = load_events_filtered(tmp_path, not_before=not_before)
ids = event_ids(events)
assert "12345678" not in ids # buy (2024-02-20)
assert "deposit-001" not in ids # deposit (2024-06-03 17:07)
assert "e230be28-286a-31b6-879f-5c97f8a9d85a" in ids # split
assert "5b0f491f-7bad-40b1-8cd1-56d83729afd4" in ids # sell
assert "88008da6-da94-3e0e-8ea5-e3878643f5ab" in ids # dividend


def test_not_after_utc_excludes_late_events(tmp_path):
"""not_after before 2025 cuts sell and dividend, keeps buy/deposit/split."""
not_after = _ts("2025-01-01T00:00:00+00:00")
events = load_events_filtered(tmp_path, not_after=not_after)
ids = event_ids(events)
assert "12345678" in ids # buy
assert "deposit-001" in ids # deposit
assert "e230be28-286a-31b6-879f-5c97f8a9d85a" in ids # split
assert "5b0f491f-7bad-40b1-8cd1-56d83729afd4" not in ids # sell (2025)
assert "88008da6-da94-3e0e-8ea5-e3878643f5ab" not in ids # dividend (2025)


def test_not_before_and_not_after_bracket(tmp_path):
"""Bracket to 2024 only: buy, deposit, split in; sell, dividend out."""
not_before = _ts("2024-01-01T00:00:00+00:00")
not_after = _ts("2024-12-31T23:59:59+00:00")
events = load_events_filtered(tmp_path, not_before=not_before, not_after=not_after)
ids = event_ids(events)
assert "12345678" in ids # buy
assert "deposit-001" in ids # deposit
assert "e230be28-286a-31b6-879f-5c97f8a9d85a" in ids # split
assert "5b0f491f-7bad-40b1-8cd1-56d83729afd4" not in ids # sell
assert "88008da6-da94-3e0e-8ea5-e3878643f5ab" not in ids # dividend


def test_last_days_cutoff(tmp_path):
"""last_days computed the same way main.py does: cuts old events, keeps recent ones.

The newest event is dividend at 2025-10-23. We pick last_days so that the
cutoff falls between the sell (2025-03-14) and dividend (2025-10-23), i.e.
relative to 'now' we keep only the dividend. We calculate not_before the
same way main.py does to stay timezone-independent.
"""
# Anchor: dividend is at 2025-10-23T14:19:56 UTC.
# We want not_before to land between sell (2025-03-14) and dividend (2025-10-23).
# Use a fixed reference: 2026-10-12 (today) minus 400 days → 2025-09-07, which is
# after sell but before dividend.
reference_now = datetime(2026, 10, 12, tzinfo=UTC)
not_before = (reference_now - timedelta(days=400)).timestamp()

events = load_events_filtered(tmp_path, not_before=not_before)
ids = event_ids(events)
assert "88008da6-da94-3e0e-8ea5-e3878643f5ab" in ids # dividend (2025-10-23, after cutoff)
assert "5b0f491f-7bad-40b1-8cd1-56d83729afd4" not in ids # sell (2025-03-14, before cutoff)
assert "12345678" not in ids # buy (2024, before cutoff)


def test_from_timestamp_naive_vs_utc_offset(tmp_path):
"""A naive ISO string (local time) and the same instant as +HH:MM produce the same POSIX value.

This mirrors the main.py conversion: datetime.fromisoformat(s).astimezone().timestamp()
We pick a UTC instant, convert to local time for the naive string, and assert both paths
give the same POSIX timestamp.
"""
utc_instant = datetime(2025, 3, 14, 7, 3, 14, tzinfo=UTC)
posix_utc = utc_instant.timestamp()

# Path 1: explicit UTC offset string (as a user would pass --from_timestamp 2025-03-14T07:03:14+00:00)
from_utc_str = "2025-03-14T07:03:14+00:00"
posix_from_utc = datetime.fromisoformat(from_utc_str).astimezone().timestamp()
assert posix_from_utc == posix_utc

# Path 2: naive local-time string (user passes local clock reading of the same instant)
local_dt = utc_instant.astimezone() # convert to local TZ
naive_local_str = local_dt.strftime("%Y-%m-%dT%H:%M:%S") # drop tzinfo, as a user would type
posix_from_naive = datetime.fromisoformat(naive_local_str).astimezone().timestamp()
assert posix_from_naive == posix_utc
Loading