Timeseries

Temporal data is an area in which Pandas actually far outshines R's dataframe libraries. Things like resampling and rolling calculations are baked into the dataframe library and work quite well. Fortunately this is also true of Polars!

Get the data

We'll download a year's worth of daily price and volume data for Bitcoin:

import nanuq

let ohlcvPl = readParquet("data/modern-polars/ohlcv.pq").setSorted("time")
nbShow ohlcvPl
shape: (366, 6)
timeopenhighlowclosevolume
datef64f64f64f64f64
2021-01-0128923.6329600.028624.5729331.6954182.925011
2021-01-0229331.733300.028946.5332178.33129993.873362
2021-01-0332176.4534778.1131962.9933000.05120957.56675
2021-01-0433000.0533600.028130.031988.71140899.88569
2021-01-0531989.7534360.029900.033949.53116049.997038
………………
2021-12-2850701.4450704.0547313.0147543.7445853.33924
2021-12-2947543.7448139.0846096.9946464.6639498.87
2021-12-3046464.6647900.045900.047120.8730352.29569
2021-12-3147120.8848548.2645678.046216.9334937.99796
2022-01-0146216.9347954.6346208.3747722.6519604.46325

Filtering

Since Polars doesn't have an index, we just use .filter:

nbShow ohlcvPl.filter(
  col.time.isBetween(
    date(2021, 2, 1),
    date(2021, 3, 1),
    closed = ClosedInterval.Left))
shape: (28, 6)
timeopenhighlowclosevolume
datef64f64f64f64f64
2021-02-0133092.9734717.2732296.1633526.3782718.276882
2021-02-0233517.0935984.3333418.035466.2478056.65988
2021-02-0335472.7137662.6335362.3837618.8780784.333663
2021-02-0437620.2638708.2736161.9536936.6692080.735898
2021-02-0536936.6538310.1236570.038290.2466681.334275
………………
2021-02-2448891.051374.9946988.6949676.291881.209252
2021-02-2549676.2152041.7346674.3447073.7383310.673121
2021-02-2647073.7348424.1144106.7846276.87109423.200663
2021-02-2746276.8848394.045000.046106.4366060.834292
2021-02-2846103.6746638.4643000.045135.6683055.369042

Resampling

Resampling is like a special case of group_by for a time column. You can of course use regular .group_by with a time column, but it won't be as powerful because it doesn't understand time like resampling methods do.

There are two kinds of resampling: downsampling and upsampling.

Downsampling

Downsampling moves from a higher time frequency to a lower time frequency. This requires some aggregation or subsetting, since we're reducing the number of rows in our data.

In Polars we use the .group_by_dynamic method for downsampling (we also use group_by_dynamic when we want to combine resampling with regular group_by logic).

nbShow ohlcvPl
  .groupByDynamic("time", every = "5d")
  .agg(col(float).mean)
shape: (74, 6)
timeopenhighlowclosevolume
datef64f64f64f64f64
2020-12-2929127.66531450.028785.5530755.0192088.399186
2021-01-0333577.02836008.46431916.19835027.986127574.470245
2021-01-0838733.6139914.54834656.42237655.352143777.954392
2021-01-1336659.6338500.05234539.40637016.338102447.076833
2021-01-1834933.92236232.33432593.01234357.258103530.722029
………………
2021-12-0948918.30450275.08847046.7548166.55437540.581856
2021-12-1447534.1848605.03446260.847561.26438331.91485
2021-12-1947581.12849223.53446987.6148382.44833012.976928
2021-12-2450707.0851407.65649540.15250048.06629607.160572
2021-12-2946836.552548135.492545970.8446881.277531098.406725

Resampling and performing multiple aggregations to each column:

nbShow ohlcvPl
  .groupByDynamic("time", every = "1w", startBy = StartBy.Friday)
  .agg(
    col(float).mean.name.suffix("_mean"),
    col(float).sum.name.suffix("_sum"))
shape: (53, 11)
timeopen_meanhigh_meanlow_meanclose_meanvolume_meanopen_sumhigh_sumlow_sumclose_sumvolume_sum
datef64f64f64f64f64f64f64f64f64f64
2021-01-0132305.78142934706.04571431021.72714333807.135714117435.5928226140.47242942.32217152.09236649.95822049.149598
2021-01-0837869.79714339646.10571434623.33428637827.52135188.296617265088.58277522.74242363.34264792.64946318.076319
2021-01-1536527.89142937412.233961.55142935343.84714394212.715129255695.24261885.4237730.86247406.93659489.005903
2021-01-2231888.54714333498.81142930424.47857132248.00714389649.935836223219.83234491.68212971.35225736.05627549.550849
2021-01-2934511.48285736411.44142933450.0835022.314286102728.42481241580.38254880.09234150.56245156.2719098.973673
……………………………
2021-12-0351448.0252283.33571447781.03571450171.07142955950.739995360136.14365983.35334467.25351197.5391655.179968
2021-12-1048289.28857149744.93142946894.53571448303.97428639077.893639338025.02348214.52328261.75338127.82273545.25547
2021-12-1747381.69285748786.57142946556.29285747839.70285733312.77515331671.85341506.0325894.05334877.92233189.42605
2021-12-2449649.11428650439.62285748528.2549117.9831126.709793347543.8353077.36339697.75343825.86217886.96855
2021-12-3146668.90548251.44545943.18546969.7927271.23060593337.8196502.8991886.3793939.5854542.46121

Upsampling

Upsampling moves in the opposite direction, from low-frequency data to high frequency data. Since we can't create new data by magic, upsampling defaults to filling the new rows with nulls (which we could then interpolate, perhaps). In Polars we have a special upsample method for this.

nbShow ohlcvPl.upsample("time", every = "6h")
shape: (1_461, 6)
timeopenhighlowclosevolume
datef64f64f64f64f64
2021-01-0128923.6329600.028624.5729331.6954182.925011
2021-01-01nullnullnullnullnull
2021-01-01nullnullnullnullnull
2021-01-01nullnullnullnullnull
2021-01-0229331.733300.028946.5332178.33129993.873362
………………
2021-12-3147120.8848548.2645678.046216.9334937.99796
2021-12-31nullnullnullnullnull
2021-12-31nullnullnullnullnull
2021-12-31nullnullnullnullnull
2022-01-0146216.9347954.6346208.3747722.6519604.46325

Rolling / Expanding / EW

Polars supports all three of these. Custom rolling and expanding aggregations are supported in Polars using expr.rolling_map and expr.cumulative_eval respectively, but the docs recommend against using them for performance reasons.

let close = col.close
nbShow ohlcvPl.select(
  col.time,
  close.alias("Raw"),
  close.rollingMean(28).alias("28D MA"),
  (close.cumSum / close.cumCount).alias("Expanding Average"),
  close.ewmMean(alpha = 0.03).alias("EWMA($\\alpha=.03$)"))
shape: (366, 5)
timeRaw28D MAExpanding AverageEWMA($\alpha=.03$)
datef64f64f64f64
2021-01-0129331.69null29331.6929331.69
2021-01-0232178.33null30755.0130776.684924
2021-01-0333000.05null31503.35666731540.491676
2021-01-0431988.71null31624.69531657.716671
2021-01-0533949.53null32089.66232144.418442
……………
2021-12-2847543.7449575.28547406.62610552720.820097
2021-12-2946464.6649192.44892947404.03115752533.132332
2021-12-3047120.8748858.18214347403.25324252370.761977
2021-12-3146216.9348594.46357147400.00304152186.144276
2022-01-0147722.6548543.39857147400.8845952052.237519

Polars doesn't have an expanding_mean or cum_mean yet so we make do by combining cum_sum and cum_count. You could also use cumulative_eval, but it's much slower on large columns, and the docs recommend against it for performance reasons.

Combining rolling aggregations

let meanStdPl = ohlcvPl.select(
  col.time,
  col.close.rollingMean(30, center = true).alias("mean"),
  col.close.rollingStd(30, center = true).alias("std"))
nbShow meanStdPl
shape: (366, 3)
timemeanstd
datef64f64
2021-01-01nullnull
2021-01-02nullnull
2021-01-03nullnull
2021-01-04nullnull
2021-01-05nullnull
………
2021-12-28nullnull
2021-12-29nullnull
2021-12-30nullnull
2021-12-31nullnull
2022-01-01nullnull

Grab Bag

Offsets

Polars has a Duration type for datetime arithmetic, which respects absolute time arithmetic:

nbShow ohlcvPl.select(col.time + duration(days = 80))
shape: (366, 1)
time
date
2021-03-22
2021-03-23
2021-03-24
2021-03-25
2021-03-26
…
2022-03-18
2022-03-19
2022-03-20
2022-03-21
2022-03-22

Holiday calendars

Some functionality for working with business days is available in Polars in the expr.dt namespace.

Timezones

Suppose we know that our timestamps are UTC, and we want to see what time it was in US/Eastern:

nbShow ohlcvPl
  .withColumns(
    col.time
      .cast(DateTime)
      .dt.replaceTimeZone("UTC")
      .dt.convertTimeZone("US/Eastern"))
shape: (366, 6)
timeopenhighlowclosevolume
datetime[ΞΌs, US/Eastern]f64f64f64f64f64
2020-12-31 19:00:00 EST28923.6329600.028624.5729331.6954182.925011
2021-01-01 19:00:00 EST29331.733300.028946.5332178.33129993.873362
2021-01-02 19:00:00 EST32176.4534778.1131962.9933000.05120957.56675
2021-01-03 19:00:00 EST33000.0533600.028130.031988.71140899.88569
2021-01-04 19:00:00 EST31989.7534360.029900.033949.53116049.997038
………………
2021-12-27 19:00:00 EST50701.4450704.0547313.0147543.7445853.33924
2021-12-28 19:00:00 EST47543.7448139.0846096.9946464.6639498.87
2021-12-29 19:00:00 EST46464.6647900.045900.047120.8730352.29569
2021-12-30 19:00:00 EST47120.8848548.2645678.046216.9334937.99796
2021-12-31 19:00:00 EST46216.9347954.6346208.3747722.6519604.46325

Conclusion

Polars has really good time series support, though expanding aggregations and holiday calendars are niches in which it is somewhat lacking.

import nanuqbook
bookInit()

nbText: "# Timeseries"

attribution modernPolars("Timeseries", "timeseries",
  "The tables show 10 rows instead of 5. The data is the book's `ohlcv.pq` (daily Bitcoin prices for 2021, which the book " &
  "downloaded from Binance), read from `data/modern-polars/`; the download code is left " &
  "out. The two plots are shown as the tables they draw.")

nbText: """
Temporal data is an area in which Pandas actually far outshines R's dataframe libraries. Things
like resampling and rolling calculations are baked into the dataframe library and work quite
well. Fortunately this is also true of Polars!

## Get the data

We'll download a year's worth of daily price and volume data for Bitcoin:
"""

tabs """
from datetime import date
import polars as pl

ohlcv_pl = pl.read_parquet("data/modern-polars/ohlcv.pq").set_sorted("time")
ohlcv_pl
""":
  nbCode:
    import nanuq

    let ohlcvPl = readParquet("data/modern-polars/ohlcv.pq").setSorted("time")
    nbShow ohlcvPl

nanuq """
The book fetches the year from Binance's `klines` API the first time and keeps it as
`ohlcv.pq`; the port reads that file. The book also sets `pl.Config.set_tbl_rows(5)`; the port
keeps the default of 10 rows, because Nanuq's `setTblRows` changes printed frames but not yet
the HTML tables of `nbShow`.
"""

nbText: """
## Filtering

Since Polars doesn't have an index, we just use `.filter`:
"""

tabs """
ohlcv_pl.filter(
    pl.col("time").is_between(
        date(2021, 2, 1),
        date(2021, 3, 1),
        closed="left"
    )
)
""":
  nbCode:
    nbShow ohlcvPl.filter(
      col.time.isBetween(
        date(2021, 2, 1),
        date(2021, 3, 1),
        closed = ClosedInterval.Left))

nbText: """
## Resampling

Resampling is like a special case of `group_by` for a time column. You can of course use
regular `.group_by` with a time column, but it won't be as powerful because it doesn't
understand time like resampling methods do.

There are two kinds of resampling: *downsampling* and *upsampling*.

### Downsampling

Downsampling moves from a higher time frequency to a lower time frequency. This requires some
aggregation or subsetting, since we're reducing the number of rows in our data.

In Polars we use the
[`.group_by_dynamic`](https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.group_by_dynamic.html)
method for downsampling (we also use `group_by_dynamic` when we want to combine resampling with
regular group_by logic).
"""

tabs """
(
    ohlcv_pl
    .group_by_dynamic("time", every="5d")
    .agg(pl.col(pl.Float64).mean())
)
""":
  nbCode:
    nbShow ohlcvPl
      .groupByDynamic("time", every = "5d")
      .agg(col(float).mean)

nanuq """
`col(float)` selects the `Float64` columns, as `pl.col(pl.Float64)` does: Nanuq selects columns
by Nim type.
"""

nbText: """
Resampling and performing multiple aggregations to each column:
"""

tabs """
(
    ohlcv_pl
    .group_by_dynamic("time", every="1w", start_by="friday")
    .agg([
        pl.col(pl.Float64).mean().name.suffix("_mean"),
        pl.col(pl.Float64).sum().name.suffix("_sum")
    ])
)
""":
  nbCode:
    nbShow ohlcvPl
      .groupByDynamic("time", every = "1w", startBy = StartBy.Friday)
      .agg(
        col(float).mean.name.suffix("_mean"),
        col(float).sum.name.suffix("_sum"))

nbText: """
### Upsampling

Upsampling moves in the opposite direction, from low-frequency data to high frequency data.
Since we can't create new data by magic, upsampling defaults to filling the new rows with nulls
(which we could then interpolate, perhaps). In Polars we have a special
[`upsample`](https://docs.pola.rs/api/python/stable/reference/dataframe/api/polars.DataFrame.upsample.html)
method for this.
"""

tabs """
ohlcv_pl.upsample("time", every="6h")
""":
  nbCode:
    nbShow ohlcvPl.upsample("time", every = "6h")

nbText: """
## Rolling / Expanding / EW

Polars supports all three of these. Custom rolling and expanding aggregations are supported in
Polars using `expr.rolling_map` and `expr.cumulative_eval` respectively, but the docs recommend
against using them for performance reasons.
"""

tabs """
close = pl.col("close")
ohlcv_pl.select(
    [
        pl.col("time"),
        close.alias("Raw"),
        close.rolling_mean(28).alias("28D MA"),
        (close.cum_sum() / close.cum_count()).alias("Expanding Average"),
        close.ewm_mean(alpha=0.03).alias("EWMA($\\alpha=.03$)"),
    ]
)
""":
  nbCode:
    let close = col.close
    nbShow ohlcvPl.select(
      col.time,
      close.alias("Raw"),
      close.rollingMean(28).alias("28D MA"),
      (close.cumSum / close.cumCount).alias("Expanding Average"),
      close.ewmMean(alpha = 0.03).alias("EWMA($\\alpha=.03$)"))

nanuq """
The book plots these four lines (via pandas and matplotlib, with `plt.ylabel("Close ($)")`);
the port shows the table that the plot is drawn from.
"""

nbText: """
Polars doesn't have an `expanding_mean` or `cum_mean` yet so we make do by combining `cum_sum`
and `cum_count`. You could also use `cumulative_eval`, but it's much slower on large columns,
and the docs recommend against it for performance reasons.

### Combining rolling aggregations
"""

tabs """
mean_std_pl = ohlcv_pl.select(
    [
        "time",
        pl.col("close").rolling_mean(30, center=True).alias("mean"),
        pl.col("close").rolling_std(30, center=True).alias("std"),
    ]
)
mean_std_pl
""":
  nbCode:
    let meanStdPl = ohlcvPl.select(
      col.time,
      col.close.rollingMean(30, center = true).alias("mean"),
      col.close.rollingStd(30, center = true).alias("std"))
    nbShow meanStdPl

nanuq """
The book draws the mean as a line with a band of one standard deviation around it; the port
shows the two columns.
"""

nbText: """
## Grab Bag

### Offsets

Polars has a `Duration` type for datetime arithmetic, which respects absolute time arithmetic:
"""

tabs """
ohlcv_pl.select(pl.col("time") + pl.duration(days=80))
""":
  nbCode:
    nbShow ohlcvPl.select(col.time + duration(days = 80))

nbText: """
### Holiday calendars

Some functionality for working with business days is available in Polars in the
[`expr.dt` namespace](https://docs.pola.rs/api/python/stable/reference/expressions/temporal.html).

### Timezones

Suppose we know that our timestamps are UTC, and we want to see what time it was in
`US/Eastern`:
"""

tabs """
(
    ohlcv_pl
    .with_columns(
        pl.col("time")
        .cast(pl.Datetime)
        .dt.replace_time_zone("UTC")
        .dt.convert_time_zone("US/Eastern")
    )
)
""":
  nbCode:
    nbShow ohlcvPl
      .withColumns(
        col.time
          .cast(DateTime)
          .dt.replaceTimeZone("UTC")
          .dt.convertTimeZone("US/Eastern"))

nbText: """
## Conclusion

Polars has really good time series support, though expanding aggregations and holiday calendars
are niches in which it is somewhat lacking.
"""

bookSave()
Made with nimib and nimibook. Blocks marked "ran" were executed when this page was built.