pytrendy 2.0.0.dev3__tar.gz → 2.0.0.dev5__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 (25) hide show
  1. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/PKG-INFO +16 -16
  2. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/README.md +15 -15
  3. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pyproject.toml +1 -1
  4. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/io/plot_pytrendy.py +45 -19
  5. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/io/results_pytrendy.py +17 -26
  6. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_analyse.py +7 -7
  7. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_refine/segment_grouping.py +3 -7
  8. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/LICENSE +0 -0
  9. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/__init__.py +0 -0
  10. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/detect_trends.py +0 -0
  11. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/io/__init__.py +0 -0
  12. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/io/data/classes_signals.csv +0 -0
  13. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/io/data/series_synthetic.csv +0 -0
  14. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/io/data_loader.py +0 -0
  15. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/io/prepare_index.py +0 -0
  16. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/__init__.py +0 -0
  17. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_get.py +0 -0
  18. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_refine/__init__.py +0 -0
  19. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_refine/abrupt_shaving.py +0 -0
  20. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_refine/artifact_cleanup.py +0 -0
  21. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_refine/gradual_expand_contract.py +0 -0
  22. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_refine/trend_classify.py +0 -0
  23. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/post_processing/segments_refine/update_neighbours.py +0 -0
  24. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/process_signals.py +0 -0
  25. {pytrendy-2.0.0.dev3 → pytrendy-2.0.0.dev5}/pytrendy/simpledtw.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pytrendy
3
- Version: 2.0.0.dev3
3
+ Version: 2.0.0.dev5
4
4
  Summary: Trend Detection in Python. Applicable for real-world industry use cases in time series.
5
5
  License: MIT License
6
6
 
@@ -126,16 +126,16 @@ The best detected trend is Down between dates 2025-05-09 - 2025-06-17
126
126
 
127
127
  Full Results:
128
128
  -------------------------------------------------------------------------------
129
- direction start end days total_change change_rank trend_class
130
- time_index
131
- 1 Up 2025-01-02 2025-01-24 22 14.013348 5 gradual
132
- 2 Down 2025-01-25 2025-02-05 11 -13.564214 6 gradual
133
- 3 Flat 2025-02-06 2025-02-09 3 -1.168831 8 NaN
134
- 4 Up 2025-02-10 2025-03-17 35 26.190476 3 gradual
135
- 5 Down 2025-03-18 2025-04-01 14 -22.721861 4 gradual
136
- 6 Up 2025-04-02 2025-05-08 36 72.611833 2 gradual
137
- 7 Down 2025-05-09 2025-06-17 39 -73.253968 1 gradual
138
- 8 Flat 2025-06-18 2025-06-30 12 3.910534 7 NaN
129
+ direction start end steps total_change change_rank trend_class
130
+ time_index
131
+ 1 Up 2025-01-02 2025-01-24 22 14.013348 5 gradual
132
+ 2 Down 2025-01-25 2025-02-05 11 -13.564214 6 gradual
133
+ 3 Flat 2025-02-06 2025-02-09 3 -1.168831 8 NaN
134
+ 4 Up 2025-02-10 2025-03-17 35 26.190476 3 gradual
135
+ 5 Down 2025-03-18 2025-04-01 14 -22.721861 4 gradual
136
+ 6 Up 2025-04-02 2025-05-08 36 72.611833 2 gradual
137
+ 7 Down 2025-05-09 2025-06-17 39 -73.253968 1 gradual
138
+ 8 Flat 2025-06-18 2025-06-30 12 3.910534 7 NaN
139
139
  -------------------------------------------------------------------------------
140
140
  ```
141
141
 
@@ -144,11 +144,11 @@ Explore the strongest uptrends:
144
144
  results.filter_segments(direction='Up', sort_by='change_rank')[:3]
145
145
  ```
146
146
 
147
- | time_index | direction | start | end | trend_class | change | pct_change | days | total_change | SNR | change_rank |
148
- |---|---|---|---|---|---|---|---|---|---|---|
149
- | 7 | Up | 2025-04-02 | 2025-05-08 | gradual | 72.61 | 367.50% | 36 | 72.61 | 21.70 | 2 |
150
- | 4 | Up | 2025-02-10 | 2025-03-17 | gradual | 26.19 | 179.93% | 35 | 26.19 | 18.61 | 3 |
151
- | 1 | Up | 2025-01-02 | 2025-01-24 | gradual | 14.01 | 104.41% | 22 | 14.01 | 22.21 | 5 |
147
+ | time_index | direction | start | end | trend_class | pct_change | steps | total_change | SNR | change_rank |
148
+ |---|---|---|---|---|---|---|---|---|---|
149
+ | 7 | Up | 2025-04-02 | 2025-05-08 | gradual | 367.50% | 36 | 72.61 | 21.70 | 2 |
150
+ | 4 | Up | 2025-02-10 | 2025-03-17 | gradual | 179.93% | 35 | 26.19 | 18.61 | 3 |
151
+ | 1 | Up | 2025-01-02 | 2025-01-24 | gradual | 104.41% | 22 | 14.01 | 22.21 | 5 |
152
152
 
153
153
  `filter_segments` ranks segments by magnitude (`change_rank`). See the [API reference](https://russellsb.github.io/pytrendy/main/reference/pytrendy/io/results_pytrendy/#pytrendy.io.results_pytrendy.PyTrendyResults.filter_segments) for all filter and sort options.
154
154
 
@@ -62,16 +62,16 @@ The best detected trend is Down between dates 2025-05-09 - 2025-06-17
62
62
 
63
63
  Full Results:
64
64
  -------------------------------------------------------------------------------
65
- direction start end days total_change change_rank trend_class
66
- time_index
67
- 1 Up 2025-01-02 2025-01-24 22 14.013348 5 gradual
68
- 2 Down 2025-01-25 2025-02-05 11 -13.564214 6 gradual
69
- 3 Flat 2025-02-06 2025-02-09 3 -1.168831 8 NaN
70
- 4 Up 2025-02-10 2025-03-17 35 26.190476 3 gradual
71
- 5 Down 2025-03-18 2025-04-01 14 -22.721861 4 gradual
72
- 6 Up 2025-04-02 2025-05-08 36 72.611833 2 gradual
73
- 7 Down 2025-05-09 2025-06-17 39 -73.253968 1 gradual
74
- 8 Flat 2025-06-18 2025-06-30 12 3.910534 7 NaN
65
+ direction start end steps total_change change_rank trend_class
66
+ time_index
67
+ 1 Up 2025-01-02 2025-01-24 22 14.013348 5 gradual
68
+ 2 Down 2025-01-25 2025-02-05 11 -13.564214 6 gradual
69
+ 3 Flat 2025-02-06 2025-02-09 3 -1.168831 8 NaN
70
+ 4 Up 2025-02-10 2025-03-17 35 26.190476 3 gradual
71
+ 5 Down 2025-03-18 2025-04-01 14 -22.721861 4 gradual
72
+ 6 Up 2025-04-02 2025-05-08 36 72.611833 2 gradual
73
+ 7 Down 2025-05-09 2025-06-17 39 -73.253968 1 gradual
74
+ 8 Flat 2025-06-18 2025-06-30 12 3.910534 7 NaN
75
75
  -------------------------------------------------------------------------------
76
76
  ```
77
77
 
@@ -80,11 +80,11 @@ Explore the strongest uptrends:
80
80
  results.filter_segments(direction='Up', sort_by='change_rank')[:3]
81
81
  ```
82
82
 
83
- | time_index | direction | start | end | trend_class | change | pct_change | days | total_change | SNR | change_rank |
84
- |---|---|---|---|---|---|---|---|---|---|---|
85
- | 7 | Up | 2025-04-02 | 2025-05-08 | gradual | 72.61 | 367.50% | 36 | 72.61 | 21.70 | 2 |
86
- | 4 | Up | 2025-02-10 | 2025-03-17 | gradual | 26.19 | 179.93% | 35 | 26.19 | 18.61 | 3 |
87
- | 1 | Up | 2025-01-02 | 2025-01-24 | gradual | 14.01 | 104.41% | 22 | 14.01 | 22.21 | 5 |
83
+ | time_index | direction | start | end | trend_class | pct_change | steps | total_change | SNR | change_rank |
84
+ |---|---|---|---|---|---|---|---|---|---|
85
+ | 7 | Up | 2025-04-02 | 2025-05-08 | gradual | 367.50% | 36 | 72.61 | 21.70 | 2 |
86
+ | 4 | Up | 2025-02-10 | 2025-03-17 | gradual | 179.93% | 35 | 26.19 | 18.61 | 3 |
87
+ | 1 | Up | 2025-01-02 | 2025-01-24 | gradual | 104.41% | 22 | 14.01 | 22.21 | 5 |
88
88
 
89
89
  `filter_segments` ranks segments by magnitude (`change_rank`). See the [API reference](https://russellsb.github.io/pytrendy/main/reference/pytrendy/io/results_pytrendy/#pytrendy.io.results_pytrendy.PyTrendyResults.filter_segments) for all filter and sort options.
90
90
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "pytrendy"
3
- version = "2.0.0.dev3"
3
+ version = "2.0.0.dev5"
4
4
  description = "Trend Detection in Python. Applicable for real-world industry use cases in time series."
5
5
  authors = [
6
6
  { name = "Russell Sammut Bonnici", email = "r.sammutbonnici@gmail.com" },
@@ -119,9 +119,13 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
119
119
 
120
120
  # Add shaded regions with fill_between
121
121
  ymin, ymax = ax.get_ylim() # get plot's visible y-range
122
+ # 'date' and 'datetime64' are both real date axes: boundaries must be
123
+ # displaced by the actual point spacing (via _adjacent_to), not a hard-coded
124
+ # one-day step, or non-daily data leaves white gaps between shaded regions.
125
+ is_date_axis = index_type in ('date', 'datetime64')
122
126
  for i, seg in enumerate(segments_enhanced):
123
127
 
124
- if index_type == "date":
128
+ if is_date_axis:
125
129
  start = pd.to_datetime(seg['start'])
126
130
  end = pd.to_datetime(seg['end'])
127
131
  else:
@@ -132,13 +136,14 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
132
136
 
133
137
  # Get context on prev seg if possible
134
138
  prev_seg = segments_enhanced[i-1] if i-1 >= 0 else None
135
- if index_type == "date":
139
+ if is_date_axis:
136
140
  prev_point = _adjacent_to(df.index, start, -1)
137
141
  prev_neighbouring = prev_seg and (prev_point is not None) and (pd.to_datetime(prev_seg['end']) == prev_point)
138
142
  elif index_type == 'string':
139
143
  prev_neighbouring = prev_seg and (prev_seg['end'] == df.index[df.index.get_loc(start) - 1])
140
144
  else:
141
- prev_neighbouring = prev_seg and (prev_seg['end'] == (start - 1))
145
+ prev_point = _adjacent_to(df.index, start, -1)
146
+ prev_neighbouring = prev_seg and (prev_point is not None) and (prev_seg['end'] == prev_point)
142
147
 
143
148
  is_prev_not_trend = prev_seg and (not ('trend_class' in prev_seg))
144
149
 
@@ -149,14 +154,15 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
149
154
 
150
155
  # Get context on next seg if possible
151
156
  next_seg = segments_enhanced[i+1] if i+1 < len(segments_enhanced) else None
152
- if index_type == 'date':
157
+ if is_date_axis:
153
158
  next_point = _adjacent_to(df.index, end, 1)
154
159
  next_neighbouring = next_seg and (next_point is not None) and (pd.to_datetime(next_seg['start']) == next_point)
155
160
  elif index_type == 'string':
156
161
  end_pos = df.index.get_loc(end)
157
162
  next_neighbouring = next_seg and (next_seg['start'] == _safe_adjacent(df.index, end_pos, 1))
158
163
  else:
159
- next_neighbouring = next_seg and (next_seg['start'] == (end + 1))
164
+ next_point = _adjacent_to(df.index, end, 1)
165
+ next_neighbouring = next_seg and (next_point is not None) and (next_seg['start'] == next_point)
160
166
 
161
167
  next_seg_abrupt = next_seg and (('trend_class' in next_seg) and (next_seg['trend_class'] == 'abrupt'))
162
168
  next_seg_noise = next_seg and (next_seg['direction'] == 'Noise')
@@ -165,13 +171,13 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
165
171
  if is_abrupt or is_noise:
166
172
  pass # Keep start as-is for abrupt/noise segments
167
173
  else:
168
- if index_type == 'date':
174
+ if is_date_axis:
169
175
  new_start = _adjacent_to(df.index, start, -1) # Everything else displaced left start
170
176
  elif index_type == 'string':
171
177
  start_pos = df.index.get_loc(start)
172
178
  new_start = _safe_adjacent(df.index, start_pos, -1)
173
179
  else:
174
- new_start = start - 1 # Everything else displaced left start
180
+ new_start = _adjacent_to(df.index, start, -1) # Everything else displaced left start
175
181
 
176
182
  # Check validity of plot start adjustment
177
183
  value_new_start = df.loc[new_start, value_col] if new_start is not None and new_start in df.index else None
@@ -185,7 +191,7 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
185
191
  else:
186
192
  # if not displaced and prev is not trend, adjust by plotting (as prev has already been drawn)
187
193
  if is_prev_not_trend and prev_neighbouring:
188
- if index_type == 'date':
194
+ if is_date_axis:
189
195
  prev_end = pd.to_datetime(segments_enhanced[i-1]['end'])
190
196
  prev_adj_end = _adjacent_to(df.index, prev_end, 1)
191
197
  prev_new_end = prev_adj_end.strftime('%Y-%m-%d') if prev_adj_end is not None else None
@@ -195,7 +201,7 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
195
201
  prev_new_end = _safe_adjacent(df.index, prev_end_pos, 1)
196
202
  else:
197
203
  prev_end = segments_enhanced[i-1]['end']
198
- prev_new_end = prev_end + 1
204
+ prev_new_end = _adjacent_to(df.index, prev_end, 1)
199
205
 
200
206
  if prev_new_end is not None:
201
207
  if index_type == 'string':
@@ -207,13 +213,13 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
207
213
 
208
214
  # Adjust ends when appropriate
209
215
  if (next_seg_abrupt or next_seg_noise) and next_neighbouring:
210
- if index_type == 'date':
216
+ if is_date_axis:
211
217
  new_end = _adjacent_to(df.index, end, 1)
212
218
  elif index_type == 'string':
213
219
  end_pos = df.index.get_loc(end)
214
220
  new_end = _safe_adjacent(df.index, end_pos, 1)
215
221
  else:
216
- new_end = end + 1
222
+ new_end = _adjacent_to(df.index, end, 1)
217
223
 
218
224
  # Check validity of plot end adjustment
219
225
  value_new_end = df.loc[new_end, value_col] if new_end is not None and new_end in df.index else None
@@ -227,7 +233,7 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
227
233
  else:
228
234
  # if not displaced and next is noise, adjust for next plotting round
229
235
  if next_seg_noise and next_neighbouring:
230
- if index_type == 'date':
236
+ if is_date_axis:
231
237
  next_start = pd.to_datetime(segments_enhanced[i+1]['start'])
232
238
  next_adj_start = _adjacent_to(df.index, next_start, -1)
233
239
  if next_adj_start is not None:
@@ -236,7 +242,10 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
236
242
  next_start_pos = df.index.get_loc(segments_enhanced[i+1]['start'])
237
243
  segments_enhanced[i+1]['start'] = _safe_adjacent(df.index, next_start_pos, -1)
238
244
  else:
239
- segments_enhanced[i+1]['start'] = (segments_enhanced[i+1]['start'] - 1)
245
+ next_start = segments_enhanced[i+1]['start']
246
+ next_adj_start = _adjacent_to(df.index, next_start, -1)
247
+ if next_adj_start is not None:
248
+ segments_enhanced[i+1]['start'] = next_adj_start
240
249
  else:
241
250
  pass # Keep end as-is
242
251
 
@@ -265,7 +274,7 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
265
274
 
266
275
  # Add vertical line if next seg is same & touching
267
276
  if next_seg and next_neighbouring and next_seg['direction'] == seg['direction']:
268
- if index_type == 'date':
277
+ if is_date_axis:
269
278
  line_date = pd.to_datetime(seg['end'])
270
279
  else:
271
280
  line_date = seg['end']
@@ -282,13 +291,30 @@ def plot_pytrendy(df: pd.DataFrame, value_col: str, segments_enhanced: list[dict
282
291
  ax.set_xlim(first_date, last_date)
283
292
  ax.set_ylim(ymin, ymax)
284
293
 
285
- if index_type == 'date':
286
- # Major ticks: every 7 days (with labels)
287
- ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
294
+ if index_type in ('date', 'datetime64'):
295
+ index = df.index
296
+ gap_days = (
297
+ np.median(np.diff(index.values)) / np.timedelta64(1, 'D')
298
+ if len(index) > 1 else 1
299
+ )
300
+
301
+ if gap_days <= 1:
302
+ # Daily data: weekly majors on the default weekday, as before.
303
+ ax.xaxis.set_major_locator(mdates.WeekdayLocator(interval=1))
304
+ else:
305
+ # Non-daily spacing: pin majors to the data's own index positions so
306
+ # every major (and its 'major' gridline) lands exactly on an
307
+ # observation, for any cadence including irregular. A WeekdayLocator
308
+ # anchors its interval grid to the Unix epoch, which lands majors
309
+ # beside fortnightly / month-end observations.
310
+ ax.set_xticks(index)
288
311
  ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
289
312
 
290
- # Minor ticks: every day (no labels, just tick marks/grid)
291
- ax.xaxis.set_minor_locator(mdates.DayLocator())
313
+ # Minor ticks: every day, but only when points are daily-or-finer. A daily
314
+ # ruler under non-daily data (e.g. weekly points) misrepresents the sampling,
315
+ # so non-daily spacing gets no minors at all.
316
+ if gap_days <= 1:
317
+ ax.xaxis.set_minor_locator(mdates.DayLocator())
292
318
 
293
319
  # Rotate major tick labels
294
320
  plt.setp(ax.get_xticklabels(), rotation=90, ha='right')
@@ -23,8 +23,8 @@ class PyTrendyResults:
23
23
  List of dictionaries representing individual trend segments.
24
24
  index_type (str):
25
25
  The type of the index used for the segments (``'date'``, ``'datetime64'``,
26
- ``'integer'``, ``'float'``, or ``'string'``). Used to render summaries with the
27
- appropriate descriptor (e.g. ``'days'`` vs ``'index steps'``). Defaults to ``'date'``.
26
+ ``'integer'``, ``'float'``, or ``'string'``). Used to label segment boundaries
27
+ in ``print_summary`` (e.g. ``'dates'`` vs ``'indexes'``). Defaults to ``'date'``.
28
28
  """
29
29
  self.segments = segments
30
30
  self.trend_segments = [seg for seg in self.segments if 'trend_class' in seg] # Get segments that are trends (exclude flats and noise)
@@ -37,11 +37,11 @@ class PyTrendyResults:
37
37
 
38
38
  def set_best(self) -> None:
39
39
  """
40
- Identifies the best trend segment based on its total cumulative change, selecting the one with the lowest change rank.
41
-
42
- - `results.best` returns best based on `total_change` (cumulative sum of differences).
43
- - Identifies the best trend segment based on steepness and duration.
44
- - The segment with the lowest `change_rank` is selected as the best.
40
+ Selects the best trend segment by lowest ``change_rank``.
41
+
42
+ Sets ``self.best`` to the trend segment with the lowest ``change_rank`` (derived from
43
+ each segment's cumulative ``total_change``). Sets ``self.best`` to ``None`` when no
44
+ trend segments exist.
45
45
  """
46
46
  if len(self.trend_segments) == 0:
47
47
  self.best = None
@@ -50,10 +50,11 @@ class PyTrendyResults:
50
50
 
51
51
  def set_summary(self) -> None:
52
52
  """
53
- Computes and stores summary statistics for trend segments, including a tabular overview and counts by direction.
53
+ Computes and stores summary statistics for trend segments.
54
54
 
55
- - Computes summary statistics and stores a compact `DataFrame` of segments.
56
- - Includes counts by direction and trend class, highest total change, and a tabular view.
55
+ Sets ``self.summary`` to counts by direction and trend class, plus the highest total
56
+ change. Sets ``self.df_summary`` to a tabular overview of the segments, indexed by
57
+ ``time_index``.
57
58
  """
58
59
  summary = {}
59
60
 
@@ -77,16 +78,7 @@ class PyTrendyResults:
77
78
  # Set summary df (without extra details)
78
79
  df = pd.DataFrame(self.segments)
79
80
 
80
- unit_descriptor = {
81
- 'date': 'days',
82
- 'integer': 'index steps',
83
- 'float': 'index steps',
84
- 'string': 'index steps',
85
- }.get(self.index_type, 'days')
86
-
87
- df = df.rename({'days' : unit_descriptor}, axis = 1)
88
-
89
- cols = ['time_index', 'direction', 'start', 'end', unit_descriptor, 'total_change', 'change_rank']
81
+ cols = ['time_index', 'direction', 'start', 'end', 'steps', 'total_change', 'change_rank']
90
82
  if len(changes) > 1: # only include trend_class if atleast one trend exists
91
83
  cols += ['trend_class']
92
84
  df = df[cols]
@@ -129,11 +121,11 @@ class PyTrendyResults:
129
121
 
130
122
  def set_df(self) -> pd.DataFrame | None:
131
123
  """
132
- Converts a list of trend segments into a pandas DataFrame for easier downstream analysis and data representation.
124
+ Converts the segment list into a pandas ``DataFrame`` for downstream analysis and export.
133
125
 
134
- - Converts the segment list into a pandas `DataFrame`.
135
- - Useful for downstream analysis and export.
136
- - Alternative data representation to segments. In `dataframe` rather than `dict`
126
+ Returns:
127
+ pd.DataFrame | None: An empty ``DataFrame`` when there are no segments; otherwise
128
+ ``None``, with ``self.df`` set as a side effect.
137
129
  """
138
130
  # Exit if nothing to report on
139
131
  if len(self.segments) == 0:
@@ -156,8 +148,7 @@ class PyTrendyResults:
156
148
  Output format. `'df'` returns a DataFrame, `'dict'` returns a list of dictionaries.
157
149
 
158
150
  Returns:
159
- Union[`list`, `pd.DataFrame`]: Filtered and sorted segments in the specified format.
160
-
151
+ list | pd.DataFrame: Filtered and sorted segments in the specified format.
161
152
  """
162
153
  segments = self.segments
163
154
  if len(segments) == 0:
@@ -19,7 +19,7 @@ def analyse_segments(df: pd.DataFrame, value_col: str, segments: list[dict]) ->
19
19
 
20
20
  - Percent change (based on start/end values)
21
21
 
22
- - Duration in days
22
+ - Duration in index steps
23
23
 
24
24
  - Cumulative total change (sum of diffs)
25
25
 
@@ -40,7 +40,7 @@ def analyse_segments(df: pd.DataFrame, value_col: str, segments: list[dict]) ->
40
40
  Returns:
41
41
  list:
42
42
  A list of enhanced segment dictionaries with additional keys:
43
- - `'total_change'`, `'pct_change'`, `'mltp_change'`, `'days'`, `'SNR'`, `'change_rank'`
43
+ - `'total_change'`, `'pct_change'`, `'mltp_change'`, `'steps'`, `'SNR'`, `'change_rank'`
44
44
  """
45
45
  segments_enhanced = []
46
46
  for segment in segments:
@@ -53,11 +53,11 @@ def analyse_segments(df: pd.DataFrame, value_col: str, segments: list[dict]) ->
53
53
  segment_enhanced['pct_change'] = (float(val_end / val_start - 1) if val_start != 0 else np.nan)
54
54
  segment_enhanced['mltp_change'] = (float(val_end / val_start) if val_start != 0 else np.nan)
55
55
 
56
- # Calculate days & cumulative total change
57
- days = segment['end'] - segment['start']
58
- if days == 0:
59
- days = 1 # edge case for 1 day flat between noise spike & trend
60
- segment_enhanced['days'] = days # set days
56
+ # Calculate steps & cumulative total change
57
+ steps = segment['end'] - segment['start']
58
+ if steps == 0:
59
+ steps = 1 # edge case for 1 step flat between noise spike & trend
60
+ segment_enhanced['steps'] = steps # set steps
61
61
 
62
62
  # Calculate cumulative total change
63
63
  segment_enhanced['total_change'] = float(df_segment[value_col].diff().sum())
@@ -12,13 +12,9 @@ def group_segments(segments: list[dict]) -> list[dict]:
12
12
  """
13
13
  Groups consecutive segments with the same direction if their gap is small.
14
14
 
15
- Segments are grouped if:
16
-
17
- - They share the same `'direction'`
18
- - Their gap is ≤ `GROUPING_DISTANCE`
19
- - They are not classified as `'abrupt'`
20
-
21
- This reduces fragmentation caused by short, noisy segments.
15
+ Segments are grouped when they share the same direction, their gap is ≤
16
+ ``GROUPING_DISTANCE``, and neither is classified as abrupt. This reduces fragmentation
17
+ caused by short, noisy segments.
22
18
 
23
19
  Args:
24
20
  segments (list): List of segment dictionaries.
File without changes