
This “capstone” project combines all the Polars time-series skills you’ve learned. In this exercise, you’ll put Polars Time-Series Analysis techniques into practice.
Goal: Take noisy, daily stock data and find the long-term monthly trend and the short-term 7-day moving average.
Step 1: The Setup
Let’s create a (simplified) dataset of daily prices.
import polars as pl
from datetime import date, timedelta
# Create 100 days of noisy data
dates = [date(2025, 1, 1) + timedelta(days=i) for i in range(100)]
prices = [100 + (i/10) + (i % 5) for i in range(100)] # Noisy trend
df = pl.DataFrame({"date": dates, "price": prices})
print(df.head())Step 2: The Analysis Pipeline
We’ll chain all our commands.
- Cast the
priceto a float. - Calculate the 7-day rolling average.
- Calculate the monthly average.
# 1. Cast and calculate the 7-day moving average
df_with_ma = df.with_columns(
pl.col("price").cast(pl.Float64),
pl.col("price").rolling("date", window_size="7d").mean().alias("7_day_MA")
)
# 2. Calculate the monthly average
# We use group_by_dynamic to "resample"
df_monthly = (
df_with_ma.group_by_dynamic("date", every="1mo")
.agg(pl.col("price").mean().alias("monthly_avg"))
)
print("\n--- 7-Day Moving Average ---")
print(df_with_ma.tail())
print("\n--- Monthly Average ---")
print(df_monthly)Output:
--- 7-Day Moving Average --- ... │ 2025-04-06 ┆ 113.5 ┆ 112.214286 │ │ 2025-04-07 ┆ 111.6 ┆ 112.5 │ │ 2025-04-08 ┆ 112.7 ┆ 112.7 │ │ 2025-04-09 ┆ 113.8 ┆ 112.9 │ │ 2025-04-10 ┆ 113.9 ┆ 113.0 │ └────────────┴───────┴────────────┘ --- Monthly Average --- shape: (4, 2) ┌─────────────────────┬─────────────┐ │ date ┆ monthly_avg │ │ --- ┆ --- │ │ datetime[μs] ┆ f64 │ ╞═════════════════════╪═════════════╡ │ 2025-01-01 00:00:00 ┆ 103.4 │ │ 2025-02-01 00:00:00 ┆ 106.35 │ │ 2025-03-01 00:00:00 ┆ 109.15 │ │ 2025-04-01 00:00:00 ┆ 111.45 │ └─────────────────────┴─────────────┘
You’ve successfully taken noisy data and extracted both the short-term and long-term trends!
Key Takeaways
- This capstone project uses Polars for time-series analysis of daily stock data.
- The goal is to identify both the long-term monthly trend and the short-term 7-day moving average.
- Step 1 involves creating a simplified dataset of daily prices.
- In Step 2, cast the price to a float, calculate the 7-day rolling average, and compute the monthly average.
- Successfully extracting trends shows effective use of Polars Time-Series Analysis.





