🚀 Your Algo Edge Just Leveled Up — Premium Plans Are Here!🚀

A year in, our Starter, Pro, and Elite Quant Plans are crushing it—members are live-trading bots and booking 1-on-1 wins. Now with annual + lifetime deals for max savings.

Every premium member gets: Full code from every article Private GitHub repos + templates 3–5 deep-dive paid articles/mo Early access + live strategy teardowns

Pick your edge:

  • Starter (€20/mo) → 1 paid article + public repos

  • Builder (€30/mo) → Full code + private repos (most popular)

  • Master (€50/mo) → Two 1-on-1 calls + custom bot built for you

Best deals: 📅 Annual: 2 months FREE 🔒 Lifetime: Own it forever + exclusive perks

First 50 annual/lifetime signups get a free 15-min audit. Don’t wait—the market won’t.

— AlgoEdge Insights Team

A few years back, I was helping a buddy figure out how many cupcakes his little bakery should whip up for the holiday rush. We had sales data from the past couple of years, but staring at those numbers felt like trying to read tea leaves. That’s when I stumbled across Darts, a Python library that turned our guessing game into something way more solid. Today, I want to share how this tool works — because forecasting isn’t just for data nerds; it’s for anyone with a question about tomorrow.

Image by — darts/github

Darts: The Friend Who Makes Predictions Fun

Picture Darts as that reliable pal who’s got a knack for spotting patterns. It’s a Python library built to tackle time series forecasting — think sales trends, weather shifts, or even how many passengers hop on a plane each month. I love it because it doesn’t care if you’re a stats newbie or a machine-learning wizard; it’s got tools for everyone. From old-school tricks like ARIMA to flashy neural networks, Darts is like a kitchen stocked with every gadget you might need.

Back to my bakery story: we used Darts to predict cupcake demand, and it saved us from a mountain of unsold frosting. Let’s break it down with some real-life vibes and code you can try yourself.

The full end-to-end workflow is available in a Google Colab notebook, exclusively for paid subscribers of my newsletter. Paid subscribers also gain access to the complete article, including the full code snippet in the Google Colab notebook, which is accessible below the paywall at the end of the article. Subscribe now to unlock these benefits

Setting Up: As Easy as Preheating an Oven

pip install darts
import pandas as pd
import numpy as np
from darts import TimeSeries
from darts.models import ExponentialSmoothing# Create sample data
date_rng = pd.date_range(start='2023-01-01', periods=100, freq='D')
data = np.random.randn(100) * 10 + 50  # Random values around 50

# Create a DataFrame
df = pd.DataFrame({'Date': date_rng, 'Value': data})

# Convert to TimeSeries
train = TimeSeries.from_dataframe(df, 'Date', 'Value')

It’s that simple — like grabbing a bag of flour from the store [cupcake analogy]. Done. Now you’re ready to bake some forecasts.

What Darts Can Do for You

1. A Toolbox Full of Options

Darts has a bunch of ways to crunch your numbers:

  • ARIMA: The trusty recipe for steady trends — like knowing Tuesday’s always slow at the bakery.

  • Exponential Smoothing: Perfect for seasonal swings, like extra cupcake sales around Valentine’s Day.

  • Boosted Models: Think of XGBoost as the espresso shot in your forecasting latte.

  • Deep Learning: N-BEATS and TFT are like sous-chefs with a futuristic edge.

  • Regression: Toss in past data and let it simmer.

2. Extra Ingredients Welcome

Got something else affecting your numbers? Like how a local festival boosts cupcake sales? Darts lets you mix in those “covariates” to make your predictions tastier.

3. Fine-Tuning Without the Fuss

Ever tweak a recipe on the fly? Darts uses Optuna to tweak itself — think of it like adjusting the sugar till it’s just right. We’ll get to that in a bit.

Baking a Forecast: The Cupcake Edition

Let’s say I’m back at the bakery with my AirPassengers dataset — yep, I’m switching gears to a classic example, but imagine it’s cupcake sales instead. Here’s how we’d figure out the last 36 months of demand.

Step 1: Gather Your Ingredients

We’ve got a CSV with monthly “cupcake” sales (okay, it’s passengers, but roll with me). Load it up:

import pandas as pd
from darts import TimeSeries
from darts.models import ExponentialSmoothing
from darts.metrics import mae, rmse
import matplotlib.pyplot as plt

# Grab the sales log
df = pd.read_csv("AirPassengers.csv", delimiter=",")

# Turn it into something Darts can chew on
series = TimeSeries.from_dataframe(df, "Month", "#Passengers")

# Split it: most for baking (training), the last 36 months to taste-test (validation)
train = series[:-36]  # First 108 months (Jan 1949 - Dec 1957)
val = series[-36:]   # Last 36 months (Jan 1958 - Dec 1960)

# Create and fit an Exponential Smoothing model
model = ExponentialSmoothing(seasonal_periods=12)  # 12 months for yearly seasonality
model.fit(train)

# Predict the next 36 months
prediction = model.predict(n=36)

# Evaluate the predictions
mae_error = mae(val, prediction)
rmse_error = rmse(val, prediction)
print(f"Mean Absolute Error (MAE): {mae_error:.2f}")
print(f"Root Mean Squared Error (RMSE): {rmse_error:.2f}")

# Visualize the results
plt.figure(figsize=(12, 6))
train.plot(label="Training Data")
val.plot(label="Actual Validation Data")
prediction.plot(label="Predicted Validation Data", linestyle="--")
plt.title("AirPassengers Forecasting")
plt.xlabel("Month")
plt.ylabel("#Passengers")
plt.legend()
plt.grid(True)
plt.show()

# Optional: Print a few values for inspection
print("\nFirst 5 training values:")
print(train[:5].values())
print("\nFirst 5 validation values:")
print(val[:5].values())
print("\nFirst 5 predicted values:")
print(prediction[:5].values())

Think of train as your batter and val as the cupcakes you’re saving to see if they’re any good.

Step 2: Whip Up the Mix

Since cupcake sales spike around holidays, I went with Exponential Smoothing — it’s like knowing December’s gonna be nuts.

# Create sample data
date_rng = pd.date_range(start='2023-01-01', periods=100, freq='D')
data = np.random.randn(100) * 10 + 50  # Random values around 50

# Create a DataFrame
df = pd.DataFrame({'Date': date_rng, 'Value': data})

# Convert to TimeSeries
train = TimeSeries.from_dataframe(df, 'Date', 'Value')
# Initialize the model
model = ExponentialSmoothing()

# Fit the model
model.fit(train)

# Predict the next 10 time steps
forecast = model.predict(10)

# Print the forecast
print(forecast)
import matplotlib.pyplot as plt

# Plot the original data
train.plot(label="Training Data", color='blue')

# Plot the forecast
forecast.plot(label="Forecast", color='red')

# Customize the plot
plt.title("Exponential Smoothing Forecast")
plt.xlabel("Date")
plt.ylabel("Value")
plt.legend()
plt.show()

That’s it. The oven’s preheated, and the batter’s ready.

Step 3: Bake and Guess

Now, let’s predict those last 36 months and see how wild it might get.

# Bake up 36 months’ worth, with some wiggle room
prediction = model.predict(n=len(val), num_samples=1000)

This gives us a forecast with a little “maybe more, maybe less” built in — like guessing how many folks might crash the bakery on a whim.

import numpy as np

# Assuming `prediction` is the output of model.predict()
mean_forecast = np.mean(prediction, axis=1)  # Mean prediction per time step
lower_bound = np.percentile(prediction, 5, axis=1)  # 5th percentile (lower uncertainty bound)
upper_bound = np.percentile(prediction, 95, axis=1)  # 95th percentile (upper uncertainty bound)
import matplotlib.pyplot as plt

time_steps = range(len(val))  # X-axis (assumed same length as validation set)

plt.figure(figsize=(12, 6))

# Plot the mean forecast
plt.plot(time_steps, mean_forecast, label="Mean Prediction", color='blue')

# Plot the confidence interval (shaded region)
plt.fill_between(time_steps, lower_bound, upper_bound, color='blue', alpha=0.2, label="90% Confidence Interval")

# Plot the actual validation data for comparison (if available)
plt.plot(time_steps, val, label="Actual Data", color='black', linestyle='dashed')

plt.xlabel("Time")
plt.ylabel("Predicted Value")
plt.legend()
plt.title("Probabilistic Forecast with Confidence Intervals")
plt.show()

Step 4: Taste Test with a Picture

logo

Subscribe to our premium content to read the rest.

Become a paying subscriber to get access to this post and other subscriber-only content.

Upgrade

Keep Reading