mgplot 0.3.4__tar.gz → 0.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. {mgplot-0.3.4 → mgplot-0.3.5}/CHANGELOG.md +12 -0
  2. {mgplot-0.3.4 → mgplot-0.3.5}/PKG-INFO +10 -1
  3. {mgplot-0.3.4 → mgplot-0.3.5}/README.md +9 -0
  4. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot.html +1 -1
  5. {mgplot-0.3.4 → mgplot-0.3.5}/pyproject.toml +1 -1
  6. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/axis_utils.py +121 -2
  7. mgplot-0.3.5/test/test_intraday_ticks.py +97 -0
  8. mgplot-0.3.5/test/test_weekly_ticks.py +92 -0
  9. mgplot-0.3.5/uv.lock +2057 -0
  10. mgplot-0.3.4/uv.lock +0 -1983
  11. {mgplot-0.3.4 → mgplot-0.3.5}/.claude/settings.local.json +0 -0
  12. {mgplot-0.3.4 → mgplot-0.3.5}/.gitignore +0 -0
  13. {mgplot-0.3.4 → mgplot-0.3.5}/.pylintrc +0 -0
  14. {mgplot-0.3.4 → mgplot-0.3.5}/.python-version +0 -0
  15. {mgplot-0.3.4 → mgplot-0.3.5}/LICENSE +0 -0
  16. {mgplot-0.3.4 → mgplot-0.3.5}/build-all.sh +0 -0
  17. {mgplot-0.3.4 → mgplot-0.3.5}/build-docs.sh +0 -0
  18. {mgplot-0.3.4 → mgplot-0.3.5}/docs/index.html +0 -0
  19. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/bar_plot.html +0 -0
  20. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/fill_between_plot.html +0 -0
  21. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/finalise_plot.html +0 -0
  22. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/growth_plot.html +0 -0
  23. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/line_plot.html +0 -0
  24. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/postcovid_plot.html +0 -0
  25. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/revision_plot.html +0 -0
  26. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/run_plot.html +0 -0
  27. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/scatter_plot.html +0 -0
  28. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/seastrend_plot.html +0 -0
  29. {mgplot-0.3.4 → mgplot-0.3.5}/docs/mgplot/summary_plot.html +0 -0
  30. {mgplot-0.3.4 → mgplot-0.3.5}/docs/search.js +0 -0
  31. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/__init__.py +0 -0
  32. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/annotation_utils.py +0 -0
  33. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/bar_plot.py +0 -0
  34. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/colors.py +0 -0
  35. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/fill_between_plot.py +0 -0
  36. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/finalise_plot.py +0 -0
  37. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/finalisers.py +0 -0
  38. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/growth_plot.py +0 -0
  39. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/keyword_checking.py +0 -0
  40. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/line_plot.py +0 -0
  41. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/lint-all.sh +0 -0
  42. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/multi_plot.py +0 -0
  43. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/postcovid_plot.py +0 -0
  44. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/py.typed +0 -0
  45. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/revision_plot.py +0 -0
  46. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/run_plot.py +0 -0
  47. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/scatter_plot.py +0 -0
  48. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/seastrend_plot.py +0 -0
  49. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/settings.py +0 -0
  50. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/summary_plot.py +0 -0
  51. {mgplot-0.3.4 → mgplot-0.3.5}/src/mgplot/utilities.py +0 -0
  52. {mgplot-0.3.4 → mgplot-0.3.5}/test/test-executed.ipynb +0 -0
  53. {mgplot-0.3.4 → mgplot-0.3.5}/test/test.ipynb +0 -0
  54. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_annotate_text.py +0 -0
  55. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_annotation_collision.py +0 -0
  56. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_axvline_text.py +0 -0
  57. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_bar_annual_ticks.py +0 -0
  58. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_bar_horizontal.py +0 -0
  59. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_bar_string_index.py +0 -0
  60. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_chart_subdir.py +0 -0
  61. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_int_for_float.py +0 -0
  62. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_line_end_rounding.py +0 -0
  63. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_multi_series_ticks.py +0 -0
  64. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_scatter_plot.py +0 -0
  65. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_splat_sequences.py +0 -0
  66. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_tick_relabel.py +0 -0
  67. {mgplot-0.3.4 → mgplot-0.3.5}/test/test_zorder.py +0 -0
  68. {mgplot-0.3.4 → mgplot-0.3.5}/test/zz-test-data/ocr_rba.csv +0 -0
  69. {mgplot-0.3.4 → mgplot-0.3.5}/test/zz-test-data/revisions.csv +0 -0
  70. {mgplot-0.3.4 → mgplot-0.3.5}/test/zz-test-data/summary.csv +0 -0
  71. {mgplot-0.3.4 → mgplot-0.3.5}/uv-upgrade.sh +0 -0
@@ -1,3 +1,15 @@
1
+ Version 0.3.5 - released 21-Nov-2026 (Canberra, Australia)
2
+
3
+ * minor changes
4
+ - intraday PeriodIndex (minute, multi-minute and hourly frequencies) gets date-like
5
+ x-axis ticks and labels: times ("10:00") with the date at each new day, or days,
6
+ months or years for longer spans. Points sit at their ordinals, so closed hours take
7
+ their real time on the axis. Daily, monthly, quarterly and yearly labels are unchanged.
8
+ - weekly PeriodIndex gets date-like x-axis ticks and labels: weeks (labelled by each
9
+ week's start day, with the month at each new month), then months on the first week
10
+ starting in each month, then years.
11
+ - added test/test_intraday_ticks.py and test/test_weekly_ticks.py
12
+
1
13
  Version 0.3.4 - released 04-Oct-2026 (Canberra, Australia)
2
14
 
3
15
  * minor changes
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: mgplot
3
- Version: 0.3.4
3
+ Version: 0.3.5
4
4
  Summary: mgplot is a time-series/PeriodIndex frontend for matplotlib
5
5
  Project-URL: Repository, https://github.com/bpalmer4/mgplot
6
6
  Project-URL: Homepage, https://github.com/bpalmer4/mgplot
@@ -121,6 +121,15 @@ the tick density is chosen to fit within `max_ticks`, and labels show
121
121
  the period with years marked at transitions (e.g. a monthly axis shows
122
122
  `Feb Mar ... 2024 ... Feb`, a quarterly axis shows `Q2 Q3 2025 Q2`).
123
123
 
124
+ Contextual labels cover yearly, quarterly, monthly, weekly, daily and
125
+ intraday (minute, multi-minute such as `5min`, and hourly) frequencies.
126
+ Weekly ticks are labelled by each week's start day, or fall on the first
127
+ week of a month or year for longer spans. Intraday axes show times with
128
+ the date at each new day (`12:00` / `19 Nov 2026`, `15:00`, ... `00:00` /
129
+ `20 Nov`), or days, months or years for longer spans. Points sit at their
130
+ period ordinals, so gaps in the data (closed market hours, weekends) take
131
+ their real width on the axis.
132
+
124
133
  Three keyword arguments control the labels on the period-indexed plot
125
134
  functions (`line_plot`, `bar_plot`, `growth_plot`, `fill_between_plot`,
126
135
  `run_plot`, and their `*_finalise` variants):
@@ -105,6 +105,15 @@ the tick density is chosen to fit within `max_ticks`, and labels show
105
105
  the period with years marked at transitions (e.g. a monthly axis shows
106
106
  `Feb Mar ... 2024 ... Feb`, a quarterly axis shows `Q2 Q3 2025 Q2`).
107
107
 
108
+ Contextual labels cover yearly, quarterly, monthly, weekly, daily and
109
+ intraday (minute, multi-minute such as `5min`, and hourly) frequencies.
110
+ Weekly ticks are labelled by each week's start day, or fall on the first
111
+ week of a month or year for longer spans. Intraday axes show times with
112
+ the date at each new day (`12:00` / `19 Nov 2026`, `15:00`, ... `00:00` /
113
+ `20 Nov`), or days, months or years for longer spans. Points sit at their
114
+ period ordinals, so gaps in the data (closed market hours, weekends) take
115
+ their real width on the axis.
116
+
108
117
  Three keyword arguments control the labels on the period-indexed plot
109
118
  functions (`line_plot`, `bar_plot`, `growth_plot`, `fill_between_plot`,
110
119
  `run_plot`, and their `*_finalise` variants):
@@ -2738,7 +2738,7 @@ for color management and finalising plots with consistent styling.</p>
2738
2738
  <section id="__version__">
2739
2739
  <div class="attr variable">
2740
2740
  <span class="name">__version__</span> =
2741
- <span class="default_value">&#39;0.3.3&#39;</span>
2741
+ <span class="default_value">&#39;0.3.4&#39;</span>
2742
2742
 
2743
2743
 
2744
2744
  </div>
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "mgplot"
3
- version = "0.3.4"
3
+ version = "0.3.5"
4
4
  description = "mgplot is a time-series/PeriodIndex frontend for matplotlib"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12"
@@ -14,7 +14,7 @@ from enum import Enum
14
14
  from typing import Any, Final
15
15
 
16
16
  from matplotlib.axes import Axes
17
- from pandas import Index, Period, PeriodIndex, RangeIndex, period_range
17
+ from pandas import Index, Period, PeriodIndex, RangeIndex, Timedelta, Timestamp, date_range, period_range
18
18
  from pandas.api.types import is_string_dtype
19
19
 
20
20
  from mgplot.settings import DataT
@@ -126,11 +126,17 @@ class DateLike(Enum):
126
126
  MONTHS = 3
127
127
  DAYS = 4
128
128
  BAD = 5
129
+ HOURS = 6
130
+ MINUTES = 7
131
+ WEEKS = 8
129
132
 
130
133
 
131
134
  frequencies = {
132
135
  # freq: [Periods from smaller to larger]
136
+ "min": [DateLike.MINUTES, DateLike.HOURS, DateLike.DAYS, DateLike.MONTHS, DateLike.YEARS],
137
+ "h": [DateLike.HOURS, DateLike.DAYS, DateLike.MONTHS, DateLike.YEARS],
133
138
  "D": [DateLike.DAYS, DateLike.MONTHS, DateLike.YEARS],
139
+ "W": [DateLike.WEEKS, DateLike.MONTHS, DateLike.YEARS],
134
140
  "M": [DateLike.MONTHS, DateLike.YEARS],
135
141
  "Q": [DateLike.QUARTERS, DateLike.YEARS],
136
142
  "Y": [DateLike.YEARS],
@@ -143,8 +149,23 @@ intervals = {
143
149
  DateLike.QUARTERS: [1, 2],
144
150
  DateLike.MONTHS: [1, 2, 3, 4, 6],
145
151
  DateLike.DAYS: [1, 2, 3, 4, 7, 14],
152
+ DateLike.WEEKS: [1, 2, 4],
153
+ DateLike.HOURS: [1, 2, 3, 4, 6, 12], # each divides a day, so ticks repeat at the same times
154
+ DateLike.MINUTES: [1, 2, 5, 10, 15, 30], # each divides an hour
146
155
  }
147
156
 
157
+ INTRADAY: Final[tuple[str, ...]] = ("min", "h") # base codes of intraday PeriodIndex frequencies
158
+
159
+
160
+ def base_freq(p: PeriodIndex) -> str:
161
+ """Return the base code of a PeriodIndex frequency: "min", "h", or the first letter (D, M, Q, Y ...).
162
+
163
+ Intraday frequencies carry a multiple ("5min", "2h"), so they are read from the rule
164
+ code; the others keep the first letter of freqstr ("Q-DEC" is "Q").
165
+ """
166
+ code = p.freq.rule_code if p.freq is not None else ""
167
+ return code if code in INTRADAY else p.freqstr[0].upper()
168
+
148
169
 
149
170
  def get_count(p: PeriodIndex, max_ticks: int) -> tuple[int, DateLike, int]:
150
171
  """Work out the label frequency and interval for a date-like PeriodIndex.
@@ -163,7 +184,7 @@ def get_count(p: PeriodIndex, max_ticks: int) -> tuple[int, DateLike, int]:
163
184
  error = (0, DateLike.BAD, 0)
164
185
  if p.empty:
165
186
  return error
166
- freq: str = p.freqstr[0].upper()
187
+ freq: str = base_freq(p)
167
188
  if freq not in frequencies:
168
189
  print(f"Unrecognised date-like PeriodIndex frequency {freq}")
169
190
  return error
@@ -332,6 +353,98 @@ def year_labeller(labels: dict[Period, str]) -> dict[Period, str]:
332
353
  return labels
333
354
 
334
355
 
356
+ def intraday_locator(p: PeriodIndex, date_like: DateLike, interval: int) -> dict[Period, str]:
357
+ """Select the ticks for an intraday PeriodIndex: round times, as Periods of p's frequency.
358
+
359
+ Tick times are generated directly (every interval minutes or hours from midnight, each
360
+ interval-th day, the first of each interval-th month or year) rather than picked from p,
361
+ because a multi-minute range rebuilt from axis limits need not fall on round minutes.
362
+ """
363
+ first = Timestamp(p.min().start_time)
364
+ last = Timestamp(p.max().start_time)
365
+ match date_like:
366
+ case DateLike.MINUTES:
367
+ times = date_range(first.ceil(f"{interval}min"), last, freq=f"{interval}min")
368
+ case DateLike.HOURS:
369
+ times = date_range(first.ceil(f"{interval}h"), last, freq=f"{interval}h")
370
+ case DateLike.DAYS:
371
+ times = date_range(first.ceil("D"), last, freq="D")[::interval]
372
+ case DateLike.MONTHS:
373
+ times = date_range(first.ceil("D"), last, freq="MS")
374
+ times = times[(times.month - 1) % interval == 0]
375
+ case _:
376
+ times = date_range(first.ceil("D"), last, freq="YS")
377
+ times = times[times.year % interval == 0]
378
+ return {Period(t, freq=p.freqstr): "" for t in times}
379
+
380
+
381
+ def intraday_labeller(labels: dict[Period, str]) -> dict[Period, str]:
382
+ """Label hour or minute ticks with the time, adding the date at each new day.
383
+
384
+ The first tick, and the first of each new year, also carry the year.
385
+ """
386
+ previous: Period | None = None
387
+ for period in sorted(labels.keys()):
388
+ label = f"{period.hour:02d}:{period.minute:02d}"
389
+ if previous is None or (period.year, period.month, period.day) != (
390
+ previous.year,
391
+ previous.month,
392
+ previous.day,
393
+ ):
394
+ label = f"{label}\n{period.day} {calendar.month_abbr[period.month]}"
395
+ if previous is None or period.year != previous.year:
396
+ label = f"{label} {period.year}"
397
+ labels[period] = label
398
+ previous = period
399
+ return labels
400
+
401
+
402
+ def make_intraday_labels(p: PeriodIndex, date_like: DateLike, interval: int) -> dict[Period, str]:
403
+ """Select and label the ticks for an intraday PeriodIndex."""
404
+ labels = intraday_locator(p, date_like, interval)
405
+ match date_like:
406
+ case DateLike.MINUTES | DateLike.HOURS:
407
+ return intraday_labeller(labels)
408
+ case DateLike.DAYS:
409
+ return day_labeller(labels)
410
+ case DateLike.MONTHS:
411
+ return month_labeller(labels)
412
+ case _:
413
+ return year_labeller(labels)
414
+
415
+
416
+ def make_weekly_labels(p: PeriodIndex, date_like: DateLike, interval: int) -> dict[Period, str]:
417
+ """Select and label the ticks for a complete weekly PeriodIndex, by each week's start date.
418
+
419
+ Week ticks fall every interval weeks; month and year ticks on the first week starting in
420
+ each (interval-th) month or year. A weekly Period's day and month attributes describe its
421
+ last day, so ticks are chosen and labelled from start dates: each chosen week stands in
422
+ as a daily, monthly or yearly Period for the existing labellers.
423
+ """
424
+ starts = p.start_time
425
+ previous = starts - Timedelta(days=7)
426
+ match date_like:
427
+ case DateLike.WEEKS:
428
+ chosen = list(range(0, len(p), interval))
429
+ proxy_freq, labeller = "D", day_labeller
430
+ case DateLike.MONTHS:
431
+ chosen = [
432
+ i
433
+ for i in range(len(p))
434
+ if starts[i].month != previous[i].month and (starts[i].month - 1) % interval == 0
435
+ ]
436
+ proxy_freq, labeller = "M", month_labeller
437
+ case _:
438
+ chosen = [
439
+ i
440
+ for i in range(len(p))
441
+ if starts[i].year != previous[i].year and starts[i].year % interval == 0
442
+ ]
443
+ proxy_freq, labeller = "Y", year_labeller
444
+ weeks = {Period(starts[i], freq=proxy_freq): p[i] for i in chosen}
445
+ return {weeks[proxy]: label for proxy, label in labeller(dict.fromkeys(weeks, "")).items()}
446
+
447
+
335
448
  def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
336
449
  """Provide a dictionary of labels for the date-like PeriodIndex.
337
450
 
@@ -351,6 +464,9 @@ def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
351
464
  if date_like == DateLike.BAD:
352
465
  return labels
353
466
 
467
+ if base_freq(p) in INTRADAY:
468
+ return make_intraday_labels(p, date_like, interval)
469
+
354
470
  target_freq = r_freqs[date_like]
355
471
  try:
356
472
  complete = period_range(start=p.min(), end=p.max(), freq=p.freqstr)
@@ -358,6 +474,9 @@ def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
358
474
  print(f"Error creating period range: {e}")
359
475
  return labels
360
476
 
477
+ if base_freq(p) == "W":
478
+ return make_weekly_labels(complete, date_like, interval)
479
+
361
480
  match target_freq:
362
481
  case "D":
363
482
  second_interval: Final[int] = 2
@@ -0,0 +1,97 @@
1
+ """Test x-axis ticks and labels for intraday (minute and hour) PeriodIndex data.
2
+
3
+ Covers:
4
+ - 5-minute bars over two trading days: hour ticks at round times, after finalise's refresh
5
+ - a refreshed 5-minute range that starts off the hour still gets ticks on the hour
6
+ - hourly bars over six weeks: day ticks at midnight, labelled as days
7
+ - the first label carries the year; later hour labels carry the date only at a new day
8
+
9
+ Run with: uv run python test/test_intraday_ticks.py
10
+ """
11
+
12
+ import re
13
+
14
+ import matplotlib as mpl
15
+
16
+ mpl.use("Agg")
17
+ import matplotlib.pyplot as plt
18
+ import pandas as pd
19
+
20
+ import mgplot as mg
21
+ from mgplot.axis_utils import make_ilabels
22
+
23
+ TIME_RE = re.compile(r"^\d{2}:\d{2}")
24
+
25
+
26
+ def trading_days(freq: str, days: list[str]) -> pd.Series:
27
+ """Bars from 09:30 to 16:00 on each day: the overnight gaps are left out, as in market data."""
28
+ index = pd.PeriodIndex(
29
+ [p for day in days for p in pd.period_range(f"{day} 09:30", f"{day} 15:55", freq=freq)],
30
+ )
31
+ return pd.Series(range(len(index)), index=index, name="price", dtype=float)
32
+
33
+
34
+ def tick_periods(ax: plt.Axes, freq: str) -> list[pd.Period]:
35
+ """Read the axis ticks back as Periods of the plotted frequency."""
36
+ return [pd.Period(ordinal=int(t), freq=freq) for t in ax.get_xticks()]
37
+
38
+
39
+ def test_five_minute_two_days() -> None:
40
+ """Two days of 5-minute bars: ticks on round hours, labelled with times, after finalise."""
41
+ series = trading_days("5min", ["2026-11-19", "2026-11-20"])
42
+ ax = mg.line_plot(series)
43
+ mg.finalise_plot(ax, title="intraday 5min", dont_save=True, dont_close=True)
44
+ labels = [t.get_text() for t in ax.get_xticklabels()]
45
+ periods = tick_periods(ax, "5min")
46
+ assert labels, "no tick labels generated"
47
+ assert all(TIME_RE.match(label) for label in labels), f"labels are not times: {labels}"
48
+ assert all(p.minute == 0 for p in periods), f"ticks off the hour: {periods}"
49
+ assert "2026" in labels[0], f"first label lacks the year: {labels[0]!r}"
50
+ plt.close("all")
51
+ print("PASS: 5-minute bars over two days")
52
+
53
+
54
+ def test_unaligned_range_ticks_on_the_hour() -> None:
55
+ """A 5-minute range starting at 09:31 (as rebuilt from axis limits) still ticks on the hour."""
56
+ p = pd.period_range("2026-11-19 09:31", "2026-11-19 15:56", freq="5min")
57
+ ticks, labels = make_ilabels(p, 10)
58
+ periods = [pd.Period(ordinal=t, freq="5min") for t in ticks]
59
+ assert ticks, "no ticks for an unaligned range"
60
+ assert all(per.minute == 0 for per in periods), f"ticks off the hour: {labels}"
61
+ print("PASS: unaligned 5-minute range ticks on the hour")
62
+
63
+
64
+ def test_hourly_six_weeks() -> None:
65
+ """Six weeks of hourly bars: ticks at midnight, labelled as days, not times."""
66
+ days = [d.strftime("%Y-%m-%d") for d in pd.bdate_range("2026-10-12", "2026-11-20")]
67
+ series = trading_days("h", days)
68
+ ax = mg.line_plot(series)
69
+ mg.finalise_plot(ax, title="intraday hourly", dont_save=True, dont_close=True)
70
+ labels = [t.get_text() for t in ax.get_xticklabels()]
71
+ periods = tick_periods(ax, "h")
72
+ assert labels, "no tick labels generated"
73
+ assert all((p.hour, p.minute) == (0, 0) for p in periods), f"day ticks not at midnight: {periods}"
74
+ assert not any(":" in label for label in labels), f"day ticks labelled as times: {labels}"
75
+ plt.close("all")
76
+ print("PASS: hourly bars over six weeks")
77
+
78
+
79
+ def test_date_only_at_new_day() -> None:
80
+ """Hour labels carry the date at a new day only; the year only on the first label."""
81
+ p = pd.period_range("2026-12-31 18:00", "2027-01-01 06:00", freq="h")
82
+ ticks, labels = make_ilabels(p, 6)
83
+ assert ticks, "no ticks generated"
84
+ assert "2026" in labels[0], f"first label lacks the year: {labels[0]!r}"
85
+ new_day = [label for label in labels if "1 Jan" in label]
86
+ assert new_day, f"no label marks the new day: {labels}"
87
+ assert "2027" in new_day[0], f"new year not marked: {new_day[0]!r}"
88
+ assert sum("\n" in label for label in labels) == 2, f"date on more than the day changes: {labels}"
89
+ print("PASS: date only at a new day")
90
+
91
+
92
+ if __name__ == "__main__":
93
+ test_five_minute_two_days()
94
+ test_unaligned_range_ticks_on_the_hour()
95
+ test_hourly_six_weeks()
96
+ test_date_only_at_new_day()
97
+ print("\nAll intraday tick tests passed!")
@@ -0,0 +1,92 @@
1
+ """Test x-axis ticks and labels for weekly PeriodIndex data.
2
+
3
+ Covers:
4
+ - two years of weeks: month ticks on the first week starting in each month, after finalise
5
+ - six months of weeks: week ticks labelled by the week's start day, not its last day
6
+ - fifteen years of weeks: year ticks on the first week starting in each year
7
+ - a weekly series with missing weeks still gets ticks across the whole span
8
+
9
+ Run with: uv run python test/test_weekly_ticks.py
10
+ """
11
+
12
+ import matplotlib as mpl
13
+
14
+ mpl.use("Agg")
15
+ import matplotlib.pyplot as plt
16
+ import pandas as pd
17
+
18
+ import mgplot as mg
19
+ from mgplot.axis_utils import make_ilabels
20
+
21
+ FIRST_WEEK_DAYS = 7 # a week starting on day 1-7 of a month is that month's first week
22
+ YEAR_DIGITS = 4
23
+ MIN_SPAN_TICKS = 6 # a two-year span should get at least this many ticks
24
+
25
+
26
+ def weekly(start: str, periods: int) -> pd.Series:
27
+ """Make a weekly series (weeks Monday to Sunday)."""
28
+ index = pd.period_range(start, periods=periods, freq="W")
29
+ return pd.Series(range(periods), index=index, name="price", dtype=float)
30
+
31
+
32
+ def tick_weeks(ticks: list[int]) -> list[pd.Period]:
33
+ """Read tick ordinals back as weekly Periods."""
34
+ return [pd.Period(ordinal=int(t), freq="W") for t in ticks]
35
+
36
+
37
+ def test_two_years_month_ticks() -> None:
38
+ """Two years of weeks: ticks on the first week starting in a month, after finalise."""
39
+ ax = mg.line_plot(weekly("2024-11-18", 105))
40
+ mg.finalise_plot(ax, title="weekly 2y", dont_save=True, dont_close=True)
41
+ labels = [t.get_text() for t in ax.get_xticklabels()]
42
+ weeks = tick_weeks(list(ax.get_xticks()))
43
+ assert labels, "no tick labels generated"
44
+ assert all(w.start_time.day <= FIRST_WEEK_DAYS for w in weeks), f"not first weeks: {weeks}"
45
+ assert any(label in ("Mar", "May", "Jul") for label in labels), f"no month labels: {labels}"
46
+ assert "2026" in labels, f"year change not labelled: {labels}"
47
+ plt.close("all")
48
+ print("PASS: two years of weeks, month ticks")
49
+
50
+
51
+ def test_six_months_week_ticks_by_start_day() -> None:
52
+ """Six months of weeks: week ticks labelled by start day (16, not 22, for 16-22 Nov)."""
53
+ p = pd.period_range("2026-06-01", "2026-11-16", freq="W")
54
+ ticks, labels = make_ilabels(p, 13)
55
+ weeks = tick_weeks(ticks)
56
+ assert ticks, "no ticks generated"
57
+ for week, label in zip(weeks, labels, strict=True):
58
+ day = label.split("\n")[0].split(" ")[0]
59
+ assert day == str(week.start_time.day), f"{week} labelled {label!r}, not by its start day"
60
+ assert any("\n" in label for label in labels), f"no month marked under a day: {labels}"
61
+ print("PASS: six months of weeks, labelled by start day")
62
+
63
+
64
+ def test_fifteen_years_year_ticks() -> None:
65
+ """Fifteen years of weeks: ticks on the first week starting in a year, labelled as years."""
66
+ p = pd.period_range("2011-01-03", "2025-12-29", freq="W")
67
+ ticks, labels = make_ilabels(p, 13)
68
+ weeks = tick_weeks(ticks)
69
+ assert ticks, "no ticks generated"
70
+ assert all(w.start_time.month == 1 and w.start_time.day <= FIRST_WEEK_DAYS for w in weeks), weeks
71
+ assert all(label.isdigit() and len(label) == YEAR_DIGITS for label in labels), f"not years: {labels}"
72
+ print("PASS: fifteen years of weeks, year ticks")
73
+
74
+
75
+ def test_missing_weeks_still_ticked() -> None:
76
+ """Missing weeks (an incomplete index) still get ticks across the whole span."""
77
+ series = weekly("2024-11-18", 105).iloc[::3]
78
+ ax = mg.line_plot(series)
79
+ mg.finalise_plot(ax, title="weekly gaps", dont_save=True, dont_close=True)
80
+ weeks = tick_weeks(list(ax.get_xticks()))
81
+ assert len(weeks) >= MIN_SPAN_TICKS, f"too few ticks: {weeks}"
82
+ assert weeks[-1] > series.index[len(series) // 2], "ticks stop part-way through the data"
83
+ plt.close("all")
84
+ print("PASS: missing weeks still ticked")
85
+
86
+
87
+ if __name__ == "__main__":
88
+ test_two_years_month_ticks()
89
+ test_six_months_week_ticks_by_start_day()
90
+ test_fifteen_years_year_ticks()
91
+ test_missing_weeks_still_ticked()
92
+ print("\nAll weekly tick tests passed!")