pytrendy 2.0.0.dev6__py3-none-any.whl → 2.0.0.dev7__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.
@@ -8,6 +8,16 @@ import matplotlib.patches as mpatches
8
8
  from matplotlib import colors as mcolors
9
9
 
10
10
 
11
+ # Tick-density calibration. All private (no public API).
12
+ _MAX_PINNED_TICKS = 40 # label-density target for pinned and calendar majors (lower = sparser)
13
+ _WEEKLY_MAX_SPAN_DAYS = 200 # daily spans up to here use weekly majors
14
+ _BIWEEKLY_MAX_SPAN_DAYS = 400 # ...to here biweekly majors; beyond, month majors
15
+ _MAX_MINOR_TICKS = 900 # minor-ruler legibility target; matplotlib's hard ceiling is MAXTICKS (1000)
16
+ _YEAR_MAJOR_MIN_SPAN_DAYS = 1460 # monthly-or-coarser spans switch to year majors from ~4 years
17
+ _MULTI_DAY_MAJOR_TICK_LENGTH = 6 # explicit observation ticks need extra length on wide, short figures
18
+ _MULTI_DAY_MINOR_TICK_LENGTH = 4 # long enough to read the ruler, short enough to keep majors dominant
19
+
20
+
11
21
  def _annotation_color(color):
12
22
  """
13
23
  Return a darker annotation colour for a segment fill colour.
@@ -68,6 +78,227 @@ def _adjacent_to(index, value, offset):
68
78
  return None # non-unique index: no well-defined adjacent point
69
79
  return _safe_adjacent(index, pos, offset)
70
80
 
81
+ def _thinned_positions(index, cap):
82
+ """Observation positions thinned to at most *cap* ticks."""
83
+ if len(index) <= cap:
84
+ return index
85
+ return index[::int(np.ceil(len(index) / cap))]
86
+
87
+ def _pinned_tick_positions(index):
88
+ """Pick tick positions pinned to observations, thinned past the cap.
89
+
90
+ Purely positional (``index[::ceil(n/_MAX_PINNED_TICKS)]``), so it is
91
+ agnostic to index granularity: non-daily dates (weekly, fortnightly,
92
+ month-end, yearly) and numerical indexes all follow the same rule. Used as
93
+ the fallback when no calendar unit fits a multi-day cadence.
94
+ """
95
+ return _thinned_positions(index, _MAX_PINNED_TICKS)
96
+
97
+ def _sampling_locator(interval_days):
98
+ """Locator marking every *interval_days*, or None when unexpressible.
99
+
100
+ matplotlib's time locators align by minute-of-hour or hour-of-day, so a
101
+ sampling gap is expressible only if it divides an hour (``MinuteLocator``)
102
+ or a day (``HourLocator``, ``DayLocator``). 30-minute bars ->
103
+ ``MinuteLocator(30)``, hourly -> ``HourLocator(1)``, daily ->
104
+ ``DayLocator()``. A 45- or 90-minute gap has no such locator, so callers
105
+ fall back to positional ticks.
106
+ """
107
+ minutes = interval_days * 24 * 60
108
+ if abs(minutes - round(minutes)) > 1e-6:
109
+ return None
110
+ minutes = int(round(minutes))
111
+ if minutes < 1:
112
+ return None
113
+ if minutes < 60:
114
+ return mdates.MinuteLocator(interval=minutes) if 60 % minutes == 0 else None
115
+ if minutes % 60:
116
+ return None
117
+ hours = minutes // 60
118
+ if hours < 24:
119
+ return mdates.HourLocator(interval=hours) if 24 % hours == 0 else None
120
+ return mdates.DayLocator(interval=max(1, int(np.ceil(interval_days - 1e-9))))
121
+
122
+ def _minor_locator(step_days, span_steps, index):
123
+ """True-granularity minor locator, thinned under matplotlib's tick limit.
124
+
125
+ The interval tracks the data's own sampling gap. When the span projects more
126
+ than ``_MAX_MINOR_TICKS`` of them the interval is coarsened by
127
+ ``ceil(count / limit)``. matplotlib's hard ceiling is ``MAXTICKS`` (1000), but
128
+ 900 is the legibility target -- a ruler, not a band (e.g. 60 days of
129
+ 30-minute bars: 2880 -> interval x4 -> every 2 hours, ~720 ticks). Returns an
130
+ explicit array of positions for a gap no locator can express (e.g. 45-minute
131
+ bars), thinned to the same target.
132
+ """
133
+ base = _sampling_locator(step_days)
134
+ if base is None:
135
+ # Inexpressible cadence -> the true-granularity ruler as explicit
136
+ # observation positions. Fixed ticks bypass Locator.MAXTICKS, so the
137
+ # thinning here is our own legibility choice.
138
+ return _thinned_positions(index, _MAX_MINOR_TICKS)
139
+ if span_steps <= _MAX_MINOR_TICKS:
140
+ return base
141
+ # Coarsen to the first expressible multiple, so 30-minute bars thin to whole
142
+ # hours rather than an unexpressible 5.5 hours (which would drop the ruler).
143
+ factor = int(np.ceil(span_steps / _MAX_MINOR_TICKS))
144
+ locator = _sampling_locator(step_days * factor)
145
+ while locator is None:
146
+ factor += 1
147
+ locator = _sampling_locator(step_days * factor)
148
+ return locator
149
+
150
+
151
+ def _divides(step_days, unit_days):
152
+ """True if *step_days* is at most *unit_days* and divides it near-exactly."""
153
+ if step_days <= 0 or step_days > unit_days:
154
+ return False
155
+ ratio = unit_days / step_days
156
+ return abs(ratio - round(ratio)) < 1e-6
157
+
158
+ def _expressible_hour_interval(step_days, min_hours):
159
+ """Smallest whole-hour interval >= *min_hours* an ``HourLocator`` can mark.
160
+
161
+ ``HourLocator`` aligns to whole hours of the day, so only intervals dividing
162
+ 24 hours are expressible; the interval must also divide the sampling gap
163
+ evenly so every observation lands on a major gridline. Returns the interval
164
+ in hours, or None when no hour granularity fits (e.g. a 5-hour gap).
165
+ """
166
+ step_minutes = step_days * 24 * 60
167
+ for hours in range(1, 24):
168
+ if 24 % hours or hours < min_hours:
169
+ continue
170
+ ratio = hours * 60 / step_minutes
171
+ if abs(ratio - round(ratio)) < 1e-6:
172
+ return hours
173
+ return None
174
+
175
+ def _intraday_major_locator(step_days, span_days):
176
+ """Major locator for sub-daily data, widening with span; None if no unit fits.
177
+
178
+ Each rung searches upward from its preferred interval for the smallest
179
+ expressible multiple that also divides the sampling gap; only when none
180
+ exists does the next rung get a turn, and the terminal fallback is positional
181
+ ticks. A 30-minute gap gives 2-hour majors under a one-day span, 6-hour over
182
+ three days, days thereafter; a 45-minute gap gives 3-hour majors under a day
183
+ (the smallest whole-hour multiple of 45 minutes), then 6-hour over three
184
+ days, and nothing expressible beyond -- where the caller pins positions.
185
+ """
186
+ if span_days <= 1:
187
+ # Exactly-hourly keeps HourLocator(1); every other cadence starts at 2 h.
188
+ floor = 1 if np.isclose(step_days, 1 / 24) else 2
189
+ hours = _expressible_hour_interval(step_days, floor)
190
+ if hours is not None:
191
+ return mdates.HourLocator(interval=hours)
192
+ if span_days <= 3:
193
+ hours = _expressible_hour_interval(step_days, 6)
194
+ if hours is not None:
195
+ return mdates.HourLocator(interval=hours)
196
+ if not _divides(step_days, 1):
197
+ return None
198
+ if span_days <= 7:
199
+ return mdates.DayLocator()
200
+ if span_days <= _WEEKLY_MAX_SPAN_DAYS:
201
+ return mdates.WeekdayLocator(interval=1)
202
+ if span_days <= _BIWEEKLY_MAX_SPAN_DAYS:
203
+ return mdates.WeekdayLocator(interval=2)
204
+ return mdates.MonthLocator()
205
+
206
+
207
+ def _format_for(major_locator):
208
+ """Major label format keyed to the major unit, not the span.
209
+
210
+ Hour-or-finer majors carry date and time on two lines (sub-day plots need
211
+ the clock); day-or-coarser majors (Day/Weekday/Month locators, or pinned
212
+ positions) read as dates only. So a 3-7-day span on the day rung no longer
213
+ labels a trailing ``00:00``.
214
+ """
215
+ if isinstance(major_locator, (mdates.HourLocator, mdates.MinuteLocator,
216
+ mdates.SecondLocator)):
217
+ return '%Y-%m-%d\n%H:%M'
218
+ return '%Y-%m-%d'
219
+
220
+
221
+ def _calendar_major_positions(index, step_days, span_days):
222
+ """Calendar-unit majors, snapped to the first available observation.
223
+
224
+ Majors step up from the cadence to a calendar unit: weekly-ish cadences
225
+ (< 15 days) read month by month; monthly-or-coarser cadences use year majors
226
+ once the span reaches ~4 years (shorter monthly series stay month-based);
227
+ yearly cadences always use year majors. The interval scales so the label
228
+ count stays near ``_MAX_PINNED_TICKS``, and each period's tick lands on the
229
+ first observed point in it.
230
+ """
231
+ use_years = step_days >= 200 or (step_days >= 15 and span_days >= _YEAR_MAJOR_MIN_SPAN_DAYS)
232
+ units = span_days / (365.25 if use_years else 30.44)
233
+ interval = max(1, int(np.ceil(units / _MAX_PINNED_TICKS)))
234
+ if not use_years and step_days >= 15:
235
+ interval = max(2, interval)
236
+ periods = index.to_period('Y' if use_years else 'M')
237
+ starts = np.r_[True, periods[1:] != periods[:-1]]
238
+ return index[np.flatnonzero(starts)[::interval]]
239
+
240
+
241
+ def _date_tick_spec(index, span_steps):
242
+ """Pick date-axis tick strategy from sampling cadence and span.
243
+
244
+ *span_steps* is the positional span ``len(index) - 1``. Cadence is read once
245
+ from the median calendar gap (median is DST-robust for daily data):
246
+
247
+ * Non-daily (gap > 1 day: weekly, fortnightly, month-end, yearly, ...):
248
+ majors step up to a calendar unit -- month periods for weekly-ish
249
+ cadences, year periods for monthly-or-coarser cadences once the span
250
+ reaches ~4 years (yearly cadences always) -- scaled to keep labels near
251
+ ``_MAX_PINNED_TICKS`` and snapped to the first available observation in
252
+ each period. Minors are the data's own granularity as positional ticks at
253
+ the observations, thinned to ``_MAX_MINOR_TICKS``.
254
+ * Daily (gap of one day): the original span-in-steps ladder -- weekly ->
255
+ biweekly -> month majors, with a daily minor ruler.
256
+ * Sub-daily: minors follow the true sampling granularity (30-minute bars ->
257
+ every 30 minutes, hourly -> every hour), thinned below
258
+ ``_MAX_MINOR_TICKS``; majors widen with the span in calendar days
259
+ (hours -> 6 hours -> days -> weeks -> months). When no major unit divides
260
+ the gap (45- or 90-minute bars past a few days), majors fall back to
261
+ positional ticks; when no minor locator can express the gap, the minor slot
262
+ becomes explicit positions at the observations.
263
+
264
+ The one-year minor cut-off applies to the daily and sub-daily rulers only;
265
+ multi-day minors thin (never drop) under ``_MAX_MINOR_TICKS``.
266
+
267
+ Returns ``(major_locator, minor_locator, pinned_positions, date_format)``.
268
+ The major slot is a locator or None; the minor slot is a locator, an array of
269
+ positions, or None; locators and pinned positions are mutually exclusive.
270
+ Multi-day calendar majors are returned in ``pinned_positions`` so they land
271
+ on observations rather than calendar boundaries.
272
+ """
273
+ # The one calendar read: the series' sampling cadence in days, taken as the
274
+ # median calendar gap between observations. Median (not mean) so DST shifts
275
+ # and occasional gaps don't skew it.
276
+ diffs = np.diff(index.values)
277
+ median_step_days = np.median(diffs) / np.timedelta64(1, 'D') if len(diffs) else 1
278
+ span_days = span_steps * median_step_days
279
+
280
+ if median_step_days > 1:
281
+ pinned = _calendar_major_positions(index, median_step_days, span_days)
282
+ return None, _thinned_positions(index, _MAX_MINOR_TICKS), pinned, '%Y-%m-%d'
283
+
284
+ # Minors only while the span is within a year; past that the axis reads as a
285
+ # calendar.
286
+ minor = _minor_locator(median_step_days, span_steps, index) if span_days <= 365 else None
287
+
288
+ if np.isclose(median_step_days, 1):
289
+ if span_days <= _WEEKLY_MAX_SPAN_DAYS:
290
+ return mdates.WeekdayLocator(interval=1), mdates.DayLocator(), None, '%Y-%m-%d'
291
+ if span_days <= _BIWEEKLY_MAX_SPAN_DAYS:
292
+ return mdates.WeekdayLocator(interval=2), mdates.DayLocator(), None, '%Y-%m-%d'
293
+ # Beyond ~13 months: month majors with the year-capped minor ruler.
294
+ return mdates.MonthLocator(), minor, None, '%Y-%m-%d'
295
+
296
+ major = _intraday_major_locator(median_step_days, span_days)
297
+ if major is None:
298
+ return None, minor, _pinned_tick_positions(index), _format_for(major)
299
+ return major, minor, None, _format_for(major)
300
+
301
+
71
302
  def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict], index_type: str = "date", suppress_show: bool = False, plot_params: dict = None) -> plt.Figure:
72
303
  """
73
304
  Visualizes detected trend segments over the original time series signal.
@@ -320,28 +551,36 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
320
551
 
321
552
  if index_type in ('date', 'datetime64'):
322
553
  index = df.index
323
- gap_days = (
324
- np.median(np.diff(index.values)) / np.timedelta64(1, 'D')
325
- if len(index) > 1 else 1
326
- )
327
-
328
- if gap_days <= 1:
329
- # Daily data: weekly majors on the default weekday, as before.
330
- ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
331
- else:
332
- # Non-daily spacing: pin majors to the data's own index positions so
554
+ span_steps = len(index) - 1
555
+
556
+ major, minor, pinned, date_format = _date_tick_spec(index, span_steps)
557
+ if pinned is not None:
558
+ # Positional ticks: pin majors to the data's own index positions so
333
559
  # every major (and its 'major' gridline) lands exactly on an
334
560
  # observation, for any cadence including irregular. A WeekdayLocator
335
561
  # anchors its interval grid to the Unix epoch, which lands majors
336
562
  # beside fortnightly / month-end observations.
337
- ax.set_xticks(index)
338
- ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
339
-
340
- # Minor ticks: every day, but only when points are daily-or-finer. A daily
341
- # ruler under non-daily data (e.g. weekly points) misrepresents the sampling,
342
- # so non-daily spacing gets no minors at all.
343
- if gap_days <= 1:
344
- ax.xaxis.set_minor_locator(mdates.DayLocator())
563
+ ax.set_xticks(pinned)
564
+ else:
565
+ # Locator-based majors: coarsen with span so long series avoid a
566
+ # wall of labels. Minors carry the data's own sampling granularity
567
+ # where a matplotlib locator can express it, else they are omitted.
568
+ ax.xaxis.set_major_locator(major)
569
+ if minor is not None:
570
+ if isinstance(minor, (np.ndarray, pd.Index)):
571
+ # Inexpressible cadence: explicit positional ruler, bypassing
572
+ # Locator.MAXTICKS.
573
+ ax.set_xticks(minor, minor=True)
574
+ is_multi_day = (len(index) > 1 and
575
+ np.median(np.diff(index.values)) / np.timedelta64(1, 'D') > 1)
576
+ if is_multi_day:
577
+ ax.tick_params(axis='x', which='major', length=_MULTI_DAY_MAJOR_TICK_LENGTH,
578
+ width=1.0)
579
+ ax.tick_params(axis='x', which='minor', length=_MULTI_DAY_MINOR_TICK_LENGTH,
580
+ width=0.8)
581
+ else:
582
+ ax.xaxis.set_minor_locator(minor)
583
+ ax.xaxis.set_major_formatter(mdates.DateFormatter(date_format))
345
584
 
346
585
  # Rotate major tick labels
347
586
  plt.setp(ax.get_xticklabels(), rotation=90, ha='right')
@@ -386,4 +625,4 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
386
625
  plt.tight_layout()
387
626
  if not suppress_show:
388
627
  plt.show()
389
- return fig
628
+ return fig
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytrendy
3
- Version: 2.0.0.dev6
3
+ Version: 2.0.0.dev7
4
4
  Summary: Trend Detection in Python. Applicable for real-world industry use cases in time series.
5
5
  License: MIT License
6
6
 
@@ -42,7 +42,8 @@ Classifier: Intended Audience :: Developers
42
42
  Classifier: Operating System :: OS Independent
43
43
  Provides-Extra: dev
44
44
  Provides-Extra: docs
45
- Requires-Dist: matplotlib (==3.10.8)
45
+ Requires-Dist: matplotlib (==3.11.2) ; (python_version >= "3.11") and (extra == "dev")
46
+ Requires-Dist: matplotlib (>=3.10)
46
47
  Requires-Dist: mkdocs (>=1.6,<2) ; extra == "docs"
47
48
  Requires-Dist: mkdocs-api-autonav (==0.4.0) ; extra == "docs"
48
49
  Requires-Dist: mkdocs-jupyterlite (==0.4.1) ; extra == "docs"
@@ -4,7 +4,7 @@ pytrendy/io/__init__.py,sha256=-cUdMdV4Apjev8QH_6VOWISp4UPaJHu02BTNIYO3rb0,1357
4
4
  pytrendy/io/data/classes_signals.csv,sha256=D9sPKQjSvAQc3ZCWUwahyzU4fKOjYMRbXPM4aSj8gsY,251
5
5
  pytrendy/io/data/series_synthetic.csv,sha256=NHsAKmNu5uWYkOXg_uAJ3xZKEEFaXYsjT4dhcZJvjLY,8681
6
6
  pytrendy/io/data_loader.py,sha256=p49OVeFw-39fc0BDD32w8s90N0UZnO3gHz_1hby4evE,1136
7
- pytrendy/io/plot_pytrendy.py,sha256=-U4xrOL0N9mmm6DNPRvF3EN7rgSbLwlVjVIcXzCbGwE,18033
7
+ pytrendy/io/plot_pytrendy.py,sha256=i-XQVtIlEbB_JXW63biti-CRvyhhKD4Gf_Lz0BNzPVE,29953
8
8
  pytrendy/io/prep_index.py,sha256=RG35V51mIi_dLo-Ee8UL6y4SAXW6l_Vpzeq8H3x9FOc,8342
9
9
  pytrendy/io/prep_signal_params.py,sha256=RMG9sW6FXQg7TGdfPaCkOaOdYu6H6X-a3qHFiI9i2RQ,2670
10
10
  pytrendy/io/results_pytrendy.py,sha256=tEF3H2jfQaosqNJxC1PPtO1-mTwE1gdk9K48pDVTJ_s,7858
@@ -20,7 +20,7 @@ pytrendy/post_processing/segments_refine/trend_classify.py,sha256=aJwutjfMz64t7f
20
20
  pytrendy/post_processing/segments_refine/update_neighbours.py,sha256=4MqOEllUADv8W5nBwfGL3NZNlM9cEYwh3ohb3VWIWU8,3784
21
21
  pytrendy/process_signals.py,sha256=xl_hGfigX4CgmCE4b97Y5yyHHDtaqUPjRRXllDCuiL4,12166
22
22
  pytrendy/simpledtw.py,sha256=tGsbnRgh4VqnA5XVxPCfYHnJXjvLlVHVGHQ4cGX4eUw,2945
23
- pytrendy-2.0.0.dev6.dist-info/METADATA,sha256=oHQmQRvVDYdSHe4tb6kc2ZVES8mCjkPNIc6cXIP_6ds,8695
24
- pytrendy-2.0.0.dev6.dist-info/WHEEL,sha256=EGEvSphFYqXKs23-kQBeyNoJP1nrT8ZJKQoi5p5DYL8,88
25
- pytrendy-2.0.0.dev6.dist-info/licenses/LICENSE,sha256=I00f93GihSG6Gqqw3qerxzO53oj_crz0sjynXCiHX_0,1079
26
- pytrendy-2.0.0.dev6.dist-info/RECORD,,
23
+ pytrendy-2.0.0.dev7.dist-info/METADATA,sha256=Gm8ZOvjSYnd2caAV4tcoktx4EYSyCNGPkDuDSf0Eln8,8780
24
+ pytrendy-2.0.0.dev7.dist-info/WHEEL,sha256=L-WvLdSBvJWHXv5zrQxDvNRnIgoBzLUpcbuiw19KCuQ,88
25
+ pytrendy-2.0.0.dev7.dist-info/licenses/LICENSE,sha256=I00f93GihSG6Gqqw3qerxzO53oj_crz0sjynXCiHX_0,1079
26
+ pytrendy-2.0.0.dev7.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 2.4.0
2
+ Generator: poetry-core 2.5.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any