forecastforge 0.4.0__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.
Files changed (49) hide show
  1. forecastforge/__init__.py +41 -0
  2. forecastforge/cli/__init__.py +12 -0
  3. forecastforge/cli/__main__.py +13 -0
  4. forecastforge/cli/main.py +477 -0
  5. forecastforge/common/__init__.py +6 -0
  6. forecastforge/config/__init__.py +61 -0
  7. forecastforge/config/_optional.py +39 -0
  8. forecastforge/config/device.py +98 -0
  9. forecastforge/config/environment.py +50 -0
  10. forecastforge/config/paths.py +131 -0
  11. forecastforge/config/runtime.py +76 -0
  12. forecastforge/config/seed.py +56 -0
  13. forecastforge/config/settings.py +249 -0
  14. forecastforge/core/__init__.py +21 -0
  15. forecastforge/core/errors.py +42 -0
  16. forecastforge/data/__init__.py +31 -0
  17. forecastforge/data/loaders.py +62 -0
  18. forecastforge/data/source.py +140 -0
  19. forecastforge/data/synthetic.py +212 -0
  20. forecastforge/data/yfinance_source.py +105 -0
  21. forecastforge/evaluation/__init__.py +44 -0
  22. forecastforge/evaluation/backtest.py +372 -0
  23. forecastforge/evaluation/benchmark.py +557 -0
  24. forecastforge/evaluation/metrics.py +318 -0
  25. forecastforge/features/__init__.py +67 -0
  26. forecastforge/features/builtins.py +540 -0
  27. forecastforge/features/frame.py +241 -0
  28. forecastforge/features/pipeline.py +84 -0
  29. forecastforge/features/transform.py +104 -0
  30. forecastforge/models/__init__.py +36 -0
  31. forecastforge/models/base.py +178 -0
  32. forecastforge/models/baselines.py +172 -0
  33. forecastforge/models/gbm.py +282 -0
  34. forecastforge/models/statistical.py +213 -0
  35. forecastforge/monitoring/__init__.py +6 -0
  36. forecastforge/pipelines/__init__.py +25 -0
  37. forecastforge/pipelines/synthetic_backtest.py +168 -0
  38. forecastforge/py.typed +0 -0
  39. forecastforge/schemas/__init__.py +19 -0
  40. forecastforge/schemas/time_series.py +101 -0
  41. forecastforge/schemas/validation.py +222 -0
  42. forecastforge/serving/__init__.py +5 -0
  43. forecastforge/tracking/__init__.py +6 -0
  44. forecastforge/utils/__init__.py +6 -0
  45. forecastforge-0.4.0.dist-info/METADATA +609 -0
  46. forecastforge-0.4.0.dist-info/RECORD +49 -0
  47. forecastforge-0.4.0.dist-info/WHEEL +4 -0
  48. forecastforge-0.4.0.dist-info/entry_points.txt +2 -0
  49. forecastforge-0.4.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,540 @@
1
+ """The built-in, leakage-safe feature transforms.
2
+
3
+ Every transform here is causal: the value at row *t* is computed from rows
4
+ ``<= t`` only. That property is verified by ``tests/features/test_leakage.py``
5
+ for each class, using both a truncation test (recompute on a prefix) and a
6
+ perturbation test (scramble the future and confirm the past does not move).
7
+
8
+ The set is deliberately small. It covers the features that actually matter
9
+ for daily price series — memory, trend, dispersion, momentum, and seasonality
10
+ — and nothing that would smuggle future information in. Levels (raw price) are
11
+ not emitted as features: they are non-stationary and a model that receives
12
+ them will happily learn a spurious trend.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ from collections.abc import Sequence
18
+ from typing import ClassVar, Literal
19
+
20
+ import numpy as np
21
+ import pandas as pd
22
+
23
+ from forecastforge.core.errors import DataValidationError
24
+ from forecastforge.features.frame import FeatureSet
25
+ from forecastforge.features.transform import Transform
26
+
27
+ __all__ = [
28
+ "MACD",
29
+ "RSI",
30
+ "CalendarFeatures",
31
+ "Lag",
32
+ "Returns",
33
+ "RollingStat",
34
+ "Volatility",
35
+ ]
36
+
37
+ RollingStatistic = Literal["mean", "std", "min", "max"]
38
+ CalendarComponent = Literal[
39
+ "dayofweek",
40
+ "dayofmonth",
41
+ "month",
42
+ "quarter",
43
+ "dayofyear",
44
+ "weekofyear",
45
+ "dow_cyclic",
46
+ "month_cyclic",
47
+ ]
48
+
49
+
50
+ def _resolve_column(features: FeatureSet, column: str | None) -> str:
51
+ """Return ``column``, defaulting to the target, and check it exists.
52
+
53
+ Args:
54
+ features: The set whose columns are searched.
55
+ column: Explicit column name, or ``None`` to use the target.
56
+
57
+ Returns:
58
+ The resolved column name.
59
+
60
+ Raises:
61
+ DataValidationError: If an explicit ``column`` is not present.
62
+ """
63
+ if column is None:
64
+ return features.target
65
+ if column not in features.frame.columns:
66
+ available = ", ".join(repr(str(name)) for name in features.frame.columns[:6])
67
+ raise DataValidationError(
68
+ f"column {column!r} is not present; available columns: {available}"
69
+ )
70
+ return column
71
+
72
+
73
+ def _require_positive(series: pd.Series, *, transform: str) -> None:
74
+ """Reject non-positive values, which a log transform cannot represent.
75
+
76
+ Args:
77
+ series: The input column.
78
+ transform: Transform name, used in the error message.
79
+
80
+ Raises:
81
+ DataValidationError: If any value is zero or negative.
82
+ """
83
+ if (series <= 0).any():
84
+ count = int((series <= 0).sum())
85
+ raise DataValidationError(
86
+ f"{transform} requires strictly positive values, found {count} value(s) <= 0"
87
+ )
88
+
89
+
90
+ class Lag(Transform):
91
+ """Add lagged copies of a column — the series' own memory.
92
+
93
+ Args:
94
+ periods: One or more positive look-back lengths, in rows. Duplicates
95
+ are collapsed and the result is sorted ascending.
96
+ column: Column to lag. Defaults to the target.
97
+
98
+ Raises:
99
+ DataValidationError: If ``periods`` is empty or contains a
100
+ non-positive value.
101
+
102
+ Note:
103
+ Row *t* receives the value from row ``t - p``, so the first ``p`` rows
104
+ are NaN. This is the canonical warm-up: it is unavoidable and it is
105
+ reported by :attr:`FeatureSet.warmup`.
106
+ """
107
+
108
+ name: ClassVar[str] = "lag"
109
+
110
+ def __init__(self, periods: int | Sequence[int], column: str | None = None) -> None:
111
+ values = [periods] if isinstance(periods, int) else list(periods)
112
+ if not values:
113
+ raise DataValidationError("Lag needs at least one period")
114
+ if any(period <= 0 for period in values):
115
+ raise DataValidationError(f"lag periods must be positive, got {values}")
116
+ self.periods: tuple[int, ...] = tuple(sorted(set(values)))
117
+ self.column = column
118
+
119
+ def output_columns(self, features: FeatureSet) -> tuple[str, ...]:
120
+ """Return one ``{column}_lag{p}`` name per requested period."""
121
+ column = _resolve_column(features, self.column)
122
+ return tuple(f"{column}_lag{period}" for period in self.periods)
123
+
124
+ def compute(self, features: FeatureSet) -> pd.DataFrame:
125
+ """Shift the column forward, producing NaN for the warm-up rows."""
126
+ column = _resolve_column(features, self.column)
127
+ series = features.frame[column]
128
+ return pd.DataFrame(
129
+ {f"{column}_lag{period}": series.shift(period) for period in self.periods},
130
+ index=features.frame.index,
131
+ )
132
+
133
+ def _describe(self) -> str:
134
+ return f"periods={self.periods}, column={self.column!r}"
135
+
136
+
137
+ class RollingStat(Transform):
138
+ """Add a trailing rolling statistic of a column.
139
+
140
+ The window ends at the current row, so the value at *t* summarises
141
+ ``(t - window + 1) .. t`` and never looks ahead.
142
+
143
+ Args:
144
+ window: Number of rows in the window.
145
+ stat: One of ``"mean"``, ``"std"``, ``"min"``, ``"max"``.
146
+ min_periods: Observations required before a value is emitted.
147
+ Defaults to ``window``, which makes the warm-up region explicit
148
+ instead of letting a half-filled window leak a misleading value.
149
+ column: Column to summarise. Defaults to the target.
150
+
151
+ Raises:
152
+ DataValidationError: If ``window`` is not positive, ``stat`` is
153
+ unknown, or ``min_periods`` is outside ``1..window``.
154
+ """
155
+
156
+ name: ClassVar[str] = "rolling"
157
+ _STATS: ClassVar[frozenset[str]] = frozenset({"mean", "std", "min", "max"})
158
+
159
+ def __init__(
160
+ self,
161
+ window: int,
162
+ stat: RollingStatistic = "mean",
163
+ min_periods: int | None = None,
164
+ column: str | None = None,
165
+ ) -> None:
166
+ if window <= 0:
167
+ raise DataValidationError(f"window must be positive, got {window}")
168
+ if stat not in self._STATS:
169
+ raise DataValidationError(
170
+ f"unknown rolling statistic {stat!r}; valid: {sorted(self._STATS)}"
171
+ )
172
+ resolved_min = window if min_periods is None else min_periods
173
+ if not 1 <= resolved_min <= window:
174
+ raise DataValidationError(
175
+ f"min_periods must be between 1 and {window}, got {resolved_min}"
176
+ )
177
+ self.window = window
178
+ self.stat = stat
179
+ self.min_periods = resolved_min
180
+ self.column = column
181
+
182
+ def output_columns(self, features: FeatureSet) -> tuple[str, ...]:
183
+ """Return the single ``{column}_rolling_{stat}_{window}`` name."""
184
+ column = _resolve_column(features, self.column)
185
+ return (f"{column}_rolling_{self.stat}_{self.window}",)
186
+
187
+ def compute(self, features: FeatureSet) -> pd.DataFrame:
188
+ """Apply the trailing rolling statistic."""
189
+ column = _resolve_column(features, self.column)
190
+ rolling = features.frame[column].rolling(window=self.window, min_periods=self.min_periods)
191
+ match self.stat:
192
+ case "mean":
193
+ values = rolling.mean()
194
+ case "std":
195
+ values = rolling.std()
196
+ case "min":
197
+ values = rolling.min()
198
+ case "max":
199
+ values = rolling.max()
200
+ return pd.DataFrame({self.output_columns(features)[0]: values}, index=features.frame.index)
201
+
202
+ def _describe(self) -> str:
203
+ return (
204
+ f"window={self.window}, stat={self.stat!r}, "
205
+ f"min_periods={self.min_periods}, column={self.column!r}"
206
+ )
207
+
208
+
209
+ class Returns(Transform):
210
+ """Add simple or log returns of a column.
211
+
212
+ Returns are scale-free, which makes them comparable across assets and
213
+ across time — a property raw prices do not have.
214
+
215
+ Args:
216
+ periods: Look-back distance in rows. ``1`` is the one-day return.
217
+ log: When true, emit ``log(x[t]) - log(x[t - periods])``; otherwise
218
+ emit ``x[t] / x[t - periods] - 1``.
219
+ column: Column to differentiate. Defaults to the target.
220
+
221
+ Raises:
222
+ DataValidationError: If ``periods`` is not positive, or a log return
223
+ is requested for a column containing non-positive values.
224
+ """
225
+
226
+ name: ClassVar[str] = "returns"
227
+
228
+ def __init__(
229
+ self,
230
+ periods: int = 1,
231
+ log: bool = False,
232
+ column: str | None = None,
233
+ ) -> None:
234
+ if periods <= 0:
235
+ raise DataValidationError(f"periods must be positive, got {periods}")
236
+ self.periods = periods
237
+ self.log = log
238
+ self.column = column
239
+
240
+ def output_columns(self, features: FeatureSet) -> tuple[str, ...]:
241
+ """Return ``{column}_logret{p}`` or ``{column}_ret{p}``."""
242
+ column = _resolve_column(features, self.column)
243
+ prefix = "logret" if self.log else "ret"
244
+ return (f"{column}_{prefix}{self.periods}",)
245
+
246
+ def compute(self, features: FeatureSet) -> pd.DataFrame:
247
+ """Differentiate the column, leaving the warm-up rows as NaN."""
248
+ column = _resolve_column(features, self.column)
249
+ series = features.frame[column]
250
+ if self.log:
251
+ _require_positive(series, transform=type(self).__name__)
252
+ values = np.log(series).diff(self.periods)
253
+ else:
254
+ # fill_method=None keeps pandas from padding across gaps, which
255
+ # would silently invent a return that never happened.
256
+ values = series.pct_change(periods=self.periods, fill_method=None)
257
+ return pd.DataFrame({self.output_columns(features)[0]: values}, index=features.frame.index)
258
+
259
+ def _describe(self) -> str:
260
+ return f"periods={self.periods}, log={self.log}, column={self.column!r}"
261
+
262
+
263
+ class CalendarFeatures(Transform):
264
+ """Add calendar features derived from the timestamp index.
265
+
266
+ Seasonality in financial series is real (day-of-week effects, month-end
267
+ flows), and calendar columns are the cheapest way to let a model see it.
268
+ These depend only on the timestamp itself, so they are causal by
269
+ construction.
270
+
271
+ Args:
272
+ components: Which calendar components to emit. Supported values are
273
+ ``dayofweek``, ``dayofmonth``, ``month``, ``quarter``,
274
+ ``dayofyear``, ``weekofyear``, ``dow_cyclic`` and
275
+ ``month_cyclic``. The two ``*_cyclic`` options emit sine/cosine
276
+ pairs, which preserve the wrap-around distance that a raw integer
277
+ (December = 12, January = 1) destroys.
278
+
279
+ Raises:
280
+ DataValidationError: If ``components`` is empty or names an unknown
281
+ component.
282
+ """
283
+
284
+ name: ClassVar[str] = "calendar"
285
+ _VALID: ClassVar[frozenset[str]] = frozenset(
286
+ {
287
+ "dayofweek",
288
+ "dayofmonth",
289
+ "month",
290
+ "quarter",
291
+ "dayofyear",
292
+ "weekofyear",
293
+ "dow_cyclic",
294
+ "month_cyclic",
295
+ }
296
+ )
297
+
298
+ def __init__(self, components: Sequence[CalendarComponent]) -> None:
299
+ values = tuple(components)
300
+ if not values:
301
+ raise DataValidationError("CalendarFeatures needs at least one component")
302
+ invalid = sorted(set(values) - self._VALID)
303
+ if invalid:
304
+ raise DataValidationError(
305
+ f"unknown calendar component(s) {invalid}; valid: {sorted(self._VALID)}"
306
+ )
307
+ self.components = values
308
+
309
+ def _names(self, component: str) -> tuple[str, ...]:
310
+ """Return the output column names for one component."""
311
+ if component == "dow_cyclic":
312
+ return ("dt_dow_sin", "dt_dow_cos")
313
+ if component == "month_cyclic":
314
+ return ("dt_month_sin", "dt_month_cos")
315
+ return (f"dt_{component}",)
316
+
317
+ def output_columns(self, features: FeatureSet) -> tuple[str, ...]:
318
+ """Return every column this transform will emit, in order."""
319
+ names: list[str] = []
320
+ for component in self.components:
321
+ names.extend(self._names(component))
322
+ return tuple(names)
323
+
324
+ def compute(self, features: FeatureSet) -> pd.DataFrame:
325
+ """Extract the requested components from the index."""
326
+ index = features.index
327
+ columns: dict[str, pd.Series] = {}
328
+ for component in self.components:
329
+ if component == "dayofweek":
330
+ columns["dt_dayofweek"] = pd.Series(index.day_of_week, index=index)
331
+ elif component == "dayofmonth":
332
+ columns["dt_dayofmonth"] = pd.Series(index.day, index=index)
333
+ elif component == "month":
334
+ columns["dt_month"] = pd.Series(index.month, index=index)
335
+ elif component == "quarter":
336
+ columns["dt_quarter"] = pd.Series(index.quarter, index=index)
337
+ elif component == "dayofyear":
338
+ columns["dt_dayofyear"] = pd.Series(index.day_of_year, index=index)
339
+ elif component == "weekofyear":
340
+ columns["dt_weekofyear"] = pd.Series(
341
+ index.isocalendar().week.to_numpy(), index=index
342
+ )
343
+ elif component == "dow_cyclic":
344
+ angle = 2.0 * np.pi * index.day_of_week.to_numpy() / 7.0
345
+ columns["dt_dow_sin"] = pd.Series(np.sin(angle), index=index)
346
+ columns["dt_dow_cos"] = pd.Series(np.cos(angle), index=index)
347
+ else: # month_cyclic
348
+ angle = 2.0 * np.pi * (index.month.to_numpy() - 1) / 12.0
349
+ columns["dt_month_sin"] = pd.Series(np.sin(angle), index=index)
350
+ columns["dt_month_cos"] = pd.Series(np.cos(angle), index=index)
351
+ return pd.DataFrame(columns, index=index)
352
+
353
+ def _describe(self) -> str:
354
+ return f"components={self.components}"
355
+
356
+
357
+ class RSI(Transform):
358
+ """Add Wilder's Relative Strength Index.
359
+
360
+ RSI maps recent gains against recent losses onto ``0..100`` and is the
361
+ standard overbought/oversold indicator.
362
+
363
+ Args:
364
+ window: Smoothing period. The conventional default is 14.
365
+ column: Column to measure. Defaults to the target.
366
+
367
+ Raises:
368
+ DataValidationError: If ``window`` is not positive.
369
+
370
+ Note:
371
+ Wilder's original recursion is expressed as an exponentially weighted
372
+ mean with ``alpha = 1 / window`` and ``adjust=False``. The recursion
373
+ runs forward in time only, which is what keeps the feature causal.
374
+ When the window contains no movement at all the ratio is undefined;
375
+ those rows report the neutral value ``50``.
376
+ """
377
+
378
+ name: ClassVar[str] = "rsi"
379
+
380
+ def __init__(self, window: int = 14, column: str | None = None) -> None:
381
+ if window <= 0:
382
+ raise DataValidationError(f"window must be positive, got {window}")
383
+ self.window = window
384
+ self.column = column
385
+
386
+ def output_columns(self, features: FeatureSet) -> tuple[str, ...]:
387
+ """Return the single ``{column}_rsi{window}`` name."""
388
+ column = _resolve_column(features, self.column)
389
+ return (f"{column}_rsi{self.window}",)
390
+
391
+ def compute(self, features: FeatureSet) -> pd.DataFrame:
392
+ """Compute RSI from one-step price changes."""
393
+ column = _resolve_column(features, self.column)
394
+ delta = features.frame[column].diff()
395
+ gains = delta.clip(lower=0.0)
396
+ losses = (-delta).clip(lower=0.0)
397
+
398
+ alpha = 1.0 / self.window
399
+ avg_gain = gains.ewm(alpha=alpha, adjust=False, min_periods=self.window).mean()
400
+ avg_loss = losses.ewm(alpha=alpha, adjust=False, min_periods=self.window).mean()
401
+
402
+ with np.errstate(divide="ignore", invalid="ignore"):
403
+ ratio = avg_gain / avg_loss
404
+ values = 100.0 - (100.0 / (1.0 + ratio))
405
+
406
+ # A window with no gains and no losses has no defined ratio; report
407
+ # the neutral midpoint instead of a NaN in the middle of the series.
408
+ flat = (avg_gain == 0.0) & (avg_loss == 0.0)
409
+ values = values.mask(flat, 50.0)
410
+ return pd.DataFrame({self.output_columns(features)[0]: values}, index=features.frame.index)
411
+
412
+ def _describe(self) -> str:
413
+ return f"window={self.window}, column={self.column!r}"
414
+
415
+
416
+ class MACD(Transform):
417
+ """Add the Moving Average Convergence Divergence indicator.
418
+
419
+ MACD compares a fast and a slow exponential moving average; the signal
420
+ line smooths MACD itself, and the histogram is their difference.
421
+
422
+ Args:
423
+ fast: Span of the fast EMA.
424
+ slow: Span of the slow EMA. Must exceed ``fast``.
425
+ signal: Span of the signal EMA.
426
+ column: Column to measure. Defaults to the target.
427
+
428
+ Raises:
429
+ DataValidationError: If a span is not positive or ``slow <= fast``.
430
+ """
431
+
432
+ name: ClassVar[str] = "macd"
433
+
434
+ def __init__(
435
+ self,
436
+ fast: int = 12,
437
+ slow: int = 26,
438
+ signal: int = 9,
439
+ column: str | None = None,
440
+ ) -> None:
441
+ if fast <= 0 or slow <= 0 or signal <= 0:
442
+ raise DataValidationError(
443
+ f"MACD spans must be positive, got fast={fast}, slow={slow}, signal={signal}"
444
+ )
445
+ if slow <= fast:
446
+ raise DataValidationError(
447
+ f"slow span must exceed fast span, got fast={fast}, slow={slow}"
448
+ )
449
+ self.fast = fast
450
+ self.slow = slow
451
+ self.signal = signal
452
+ self.column = column
453
+
454
+ def output_columns(self, features: FeatureSet) -> tuple[str, ...]:
455
+ """Return the MACD, signal, and histogram column names."""
456
+ column = _resolve_column(features, self.column)
457
+ return (
458
+ f"{column}_macd",
459
+ f"{column}_macd_signal",
460
+ f"{column}_macd_hist",
461
+ )
462
+
463
+ def compute(self, features: FeatureSet) -> pd.DataFrame:
464
+ """Compute the MACD line, its signal line, and the histogram."""
465
+ column = _resolve_column(features, self.column)
466
+ series = features.frame[column]
467
+ fast_ema = series.ewm(span=self.fast, adjust=False, min_periods=self.fast).mean()
468
+ slow_ema = series.ewm(span=self.slow, adjust=False, min_periods=self.slow).mean()
469
+ macd = fast_ema - slow_ema
470
+ signal = macd.ewm(span=self.signal, adjust=False, min_periods=self.signal).mean()
471
+
472
+ macd_name, signal_name, hist_name = self.output_columns(features)
473
+ return pd.DataFrame(
474
+ {macd_name: macd, signal_name: signal, hist_name: macd - signal},
475
+ index=features.frame.index,
476
+ )
477
+
478
+ def _describe(self) -> str:
479
+ return f"fast={self.fast}, slow={self.slow}, signal={self.signal}, column={self.column!r}"
480
+
481
+
482
+ class Volatility(Transform):
483
+ """Add a trailing rolling volatility of log returns.
484
+
485
+ Volatility is the standard risk input: it says how much the series has
486
+ been moving, which is often more predictable than its direction.
487
+
488
+ Args:
489
+ window: Number of returns in the rolling window.
490
+ annualize: Multiply by ``sqrt(periods_per_year)`` so the value reads
491
+ as an annualised figure.
492
+ periods_per_year: Trading periods in a year; 252 for daily bars.
493
+ column: Column to measure. Defaults to the target.
494
+
495
+ Raises:
496
+ DataValidationError: If ``window`` or ``periods_per_year`` is not
497
+ positive, or the column contains non-positive values (a log
498
+ return is undefined for them).
499
+ """
500
+
501
+ name: ClassVar[str] = "volatility"
502
+
503
+ def __init__(
504
+ self,
505
+ window: int = 20,
506
+ annualize: bool = True,
507
+ periods_per_year: int = 252,
508
+ column: str | None = None,
509
+ ) -> None:
510
+ if window <= 0:
511
+ raise DataValidationError(f"window must be positive, got {window}")
512
+ if periods_per_year <= 0:
513
+ raise DataValidationError(f"periods_per_year must be positive, got {periods_per_year}")
514
+ self.window = window
515
+ self.annualize = annualize
516
+ self.periods_per_year = periods_per_year
517
+ self.column = column
518
+
519
+ def output_columns(self, features: FeatureSet) -> tuple[str, ...]:
520
+ """Return ``{column}_vol{w}``, suffixed ``_raw`` when not annualised."""
521
+ column = _resolve_column(features, self.column)
522
+ suffix = "" if self.annualize else "_raw"
523
+ return (f"{column}_vol{self.window}{suffix}",)
524
+
525
+ def compute(self, features: FeatureSet) -> pd.DataFrame:
526
+ """Take the rolling standard deviation of one-step log returns."""
527
+ column = _resolve_column(features, self.column)
528
+ series = features.frame[column]
529
+ _require_positive(series, transform=type(self).__name__)
530
+ log_returns = np.log(series).diff()
531
+ values = log_returns.rolling(window=self.window, min_periods=self.window).std()
532
+ if self.annualize:
533
+ values = values * float(np.sqrt(self.periods_per_year))
534
+ return pd.DataFrame({self.output_columns(features)[0]: values}, index=features.frame.index)
535
+
536
+ def _describe(self) -> str:
537
+ return (
538
+ f"window={self.window}, annualize={self.annualize}, "
539
+ f"periods_per_year={self.periods_per_year}, column={self.column!r}"
540
+ )