mgplot 0.3.3__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
@@ -8,12 +8,13 @@ such as days, months, quarters, and years.
8
8
  """
9
9
 
10
10
  import calendar
11
+ import math
11
12
  from collections.abc import Callable
12
13
  from enum import Enum
13
14
  from typing import Any, Final
14
15
 
15
16
  from matplotlib.axes import Axes
16
- from pandas import Index, Period, PeriodIndex, RangeIndex, period_range
17
+ from pandas import Index, Period, PeriodIndex, RangeIndex, Timedelta, Timestamp, date_range, period_range
17
18
  from pandas.api.types import is_string_dtype
18
19
 
19
20
  from mgplot.settings import DataT
@@ -125,11 +126,17 @@ class DateLike(Enum):
125
126
  MONTHS = 3
126
127
  DAYS = 4
127
128
  BAD = 5
129
+ HOURS = 6
130
+ MINUTES = 7
131
+ WEEKS = 8
128
132
 
129
133
 
130
134
  frequencies = {
131
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],
132
138
  "D": [DateLike.DAYS, DateLike.MONTHS, DateLike.YEARS],
139
+ "W": [DateLike.WEEKS, DateLike.MONTHS, DateLike.YEARS],
133
140
  "M": [DateLike.MONTHS, DateLike.YEARS],
134
141
  "Q": [DateLike.QUARTERS, DateLike.YEARS],
135
142
  "Y": [DateLike.YEARS],
@@ -142,8 +149,23 @@ intervals = {
142
149
  DateLike.QUARTERS: [1, 2],
143
150
  DateLike.MONTHS: [1, 2, 3, 4, 6],
144
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
145
155
  }
146
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
+
147
169
 
148
170
  def get_count(p: PeriodIndex, max_ticks: int) -> tuple[int, DateLike, int]:
149
171
  """Work out the label frequency and interval for a date-like PeriodIndex.
@@ -162,7 +184,7 @@ def get_count(p: PeriodIndex, max_ticks: int) -> tuple[int, DateLike, int]:
162
184
  error = (0, DateLike.BAD, 0)
163
185
  if p.empty:
164
186
  return error
165
- freq: str = p.freqstr[0].upper()
187
+ freq: str = base_freq(p)
166
188
  if freq not in frequencies:
167
189
  print(f"Unrecognised date-like PeriodIndex frequency {freq}")
168
190
  return error
@@ -331,6 +353,98 @@ def year_labeller(labels: dict[Period, str]) -> dict[Period, str]:
331
353
  return labels
332
354
 
333
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
+
334
448
  def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
335
449
  """Provide a dictionary of labels for the date-like PeriodIndex.
336
450
 
@@ -350,6 +464,9 @@ def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
350
464
  if date_like == DateLike.BAD:
351
465
  return labels
352
466
 
467
+ if base_freq(p) in INTRADAY:
468
+ return make_intraday_labels(p, date_like, interval)
469
+
353
470
  target_freq = r_freqs[date_like]
354
471
  try:
355
472
  complete = period_range(start=p.min(), end=p.max(), freq=p.freqstr)
@@ -357,6 +474,9 @@ def make_labels(p: PeriodIndex, max_ticks: int) -> dict[Period, str]:
357
474
  print(f"Error creating period range: {e}")
358
475
  return labels
359
476
 
477
+ if base_freq(p) == "W":
478
+ return make_weekly_labels(complete, date_like, interval)
479
+
360
480
  match target_freq:
361
481
  case "D":
362
482
  second_interval: Final[int] = 2
@@ -429,8 +549,11 @@ def refresh_period_labels(axes: Axes, max_ticks: int | None = None) -> None:
429
549
  stashed = options.get("max_ticks", DEFAULT_REFRESH_TICKS)
430
550
  max_ticks = stashed if isinstance(stashed, int) else DEFAULT_REFRESH_TICKS
431
551
  xlim = axes.get_xlim()
432
- x_min = min(stash_min, int(xlim[0]))
433
- x_max = max(stash_max, int(xlim[1]))
552
+ # round inwards: only periods inside the view get a label. A bar chart's limits sit
553
+ # half a bar beyond its end bars, and truncating them named the neighbouring period,
554
+ # whose tick set_xticks then widened the axis to show.
555
+ x_min = min(stash_min, math.ceil(xlim[0]))
556
+ x_max = max(stash_max, math.floor(xlim[1]))
434
557
 
435
558
  full_range = period_range(
436
559
  start=Period(ordinal=x_min, freq=freq),
@@ -212,11 +212,16 @@ def check_peelable(value: Any, expected: type) -> bool:
212
212
  def check_type(value: Any, expected: type) -> bool:
213
213
  """Check if a value is of the expected type and reports an error if not.
214
214
 
215
+ As in Python typing (PEP 484), an int satisfies float; a bool, though an int
216
+ subclass, does not.
217
+
215
218
  Args:
216
219
  value: The value to check.
217
220
  expected: The expected type(s).
218
221
 
219
222
  """
223
+ if expected is float and isinstance(value, int) and not isinstance(value, bool):
224
+ return True
220
225
  return expected is Any or isinstance(value, expected)
221
226
 
222
227
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: mgplot
3
- Version: 0.3.3
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,13 +1,13 @@
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=iJlTDplmc2uaoRHYYMxE3miCTmm6Q_ufg2BFSZce-TI,16041
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
7
7
  mgplot/finalise_plot.py,sha256=8NGi2SFAABrP1vjKpHcug8OS6jWWpHErwq1mif6qCCg,24456
8
8
  mgplot/finalisers.py,sha256=-3gSpGa4-z4JyhnrKyFyexKmYcY3u9IlHRDgsv4HqL8,11256
9
9
  mgplot/growth_plot.py,sha256=ahGvOB2hr981KvgoqeoWb7jRg6Uag91JrD6-aKMojXM,8752
10
- mgplot/keyword_checking.py,sha256=8CFexwEK_Uyv3_8hAnJ2ewk0tEjNjkwzKfX2uFw2UpM,11446
10
+ mgplot/keyword_checking.py,sha256=-XXYlrfJOTQkWxA8L_FPxCfRJvKMGR9wKUQprb9O1Hs,11657
11
11
  mgplot/line_plot.py,sha256=9_peu41ivxx3VovDJ-lzM40ld7BQQwRF7BoiZBqBJ9s,10161
12
12
  mgplot/lint-all.sh,sha256=O7ns09v0cQNQ6POWtXtYn6VdtYURHTjy06vntR8tr_U,465
13
13
  mgplot/multi_plot.py,sha256=ONEY16Lql3a7iFzLcWSVcSnoLF0RnACsAo7_yQHJINY,10730
@@ -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.3.dist-info/METADATA,sha256=fH5_Eyv5zwUatIEGe3F9PqcWfyx5-t5h9RKhlxhpno0,7950
24
- mgplot-0.3.3.dist-info/WHEEL,sha256=W3fkpkm7-wf9vBI5Z-7s0eWkeM-spu78I8Neb98DeEg,87
25
- mgplot-0.3.3.dist-info/licenses/LICENSE,sha256=6ZyruOwF8J7mY25-vZHdOibtY8cSNLz0vWeH59TLhtw,1082
26
- mgplot-0.3.3.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