mgplot 0.3.4__py3-none-any.whl → 0.3.5__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.
mgplot/axis_utils.py CHANGED
@@ -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
@@ -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):
@@ -1,6 +1,6 @@
1
1
  mgplot/__init__.py,sha256=9AXauCKo2XlPP-yfDQRnEXr3X9OI2A7kCe0zDcbLRn8,3305
2
2
  mgplot/annotation_utils.py,sha256=p0iju88_QGsfzttK3sn53DwF4hD3ZXiCJVkE6RENovw,20972
3
- mgplot/axis_utils.py,sha256=oolTlkMzsBMkfpfSR1BeCunjM4nnthBJ2sDuRD1INGg,16302
3
+ mgplot/axis_utils.py,sha256=tr1NPKBHriOVIPewHlFjIzNBH-cE3Slr1dJhNzZ3ffE,21605
4
4
  mgplot/bar_plot.py,sha256=FobAsadYSEf-U0RZFgZutTzse4Rgr0TDFyWUMM68JVs,12513
5
5
  mgplot/colors.py,sha256=f5q4z7kORUu66uAxNeK9KAZ64gv_7h_x2qH53BvzwPw,4848
6
6
  mgplot/fill_between_plot.py,sha256=XJvtkBeOkohHyayQnu84jURapB5RsMAR-3SaskHkHfM,3361
@@ -20,7 +20,7 @@ mgplot/seastrend_plot.py,sha256=hi9t0cY0bHdIOU5abLMX7qvAp_hlVLlJFyEKNBzg6Ts,2000
20
20
  mgplot/settings.py,sha256=GxIR-CvVmUwHBhD_H0MDcG1Fxc7-bUndPn4tA5MGzn4,5581
21
21
  mgplot/summary_plot.py,sha256=Kg7VD8KFIls4KlD4jeaaXnDw51BZ3p_wMAUpjG49zGQ,11102
22
22
  mgplot/utilities.py,sha256=269tGaEt4sMqPKSr1sUXfBjN7RLvCugLwN6EjTS2uE0,8536
23
- mgplot-0.3.4.dist-info/METADATA,sha256=CnV_ALt9EbHX8GyXqX1t746jMqCYMlF7xts7HMs4AHc,7950
24
- mgplot-0.3.4.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
25
- mgplot-0.3.4.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
26
- mgplot-0.3.4.dist-info/RECORD,,
23
+ mgplot-0.3.5.dist-info/METADATA,sha256=wBPrEodfN4wwTaNqg8QG_YroCi5ldcPoHuWGllulh7I,8490
24
+ mgplot-0.3.5.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
25
+ mgplot-0.3.5.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
26
+ mgplot-0.3.5.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: hatchling 1.32.4
2
+ Generator: hatchling 1.33.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any