
Imagine you are building an application that needs to predict next month's product sales, estimate future website traffic, or forecast electricity consumption. You have historical data, but predicting what happens next is not as simple as applying a standard machine learning algorithm.
Time-series data has a specific structure. Every observation is connected to a point in time, and the order of those observations matters. Seasonality, trends, holidays, and unexpected changes can all influence future values.
This is where Darts time-series forecasting becomes useful. Darts is an open-source Python library that simplifies forecasting by providing a consistent interface for traditional statistical models, machine learning algorithms, and deep learning architectures.
Instead of implementing every forecasting algorithm manually, you can use Darts to prepare time-series data, train different models, evaluate predictions, and generate future forecasts with relatively little code.
In this tutorial, we will build a practical forecasting workflow using Python and Darts. We will load historical data, prepare it, train forecasting models, compare their performance, and predict future values.
1. What Is Darts?
Darts is a Python library designed specifically for time-series forecasting.
It provides a unified API for working with different forecasting approaches, including:
Statistical models such as ARIMA and Exponential Smoothing.
Machine learning models such as Random Forest and regression models.
Deep learning models such as N-BEATS, N-HiTS, and Temporal Convolutional Networks.
Forecasting models that support multiple time series.
Probabilistic forecasting with prediction intervals.
One of its biggest advantages is that you do not need to completely change your workflow when switching between forecasting algorithms.
For example, you can train an Exponential Smoothing model and later replace it with N-BEATS while keeping much of the surrounding data preparation and evaluation code unchanged.
Why use Darts?
Consider a typical sales forecasting application. You might need to:
Read historical sales records.
Convert the records into a time-series format.
Identify trends and seasonal patterns.
Train multiple forecasting algorithms.
Compare their prediction accuracy.
Forecast sales for the next 30 days.
Darts provides tools for each of these steps.
2. Install Darts and Required Libraries
Before building the forecasting model, create a Python environment and install the required packages.
python -m venv venvActivate it on macOS or Linux:
source venv/bin/activateOn Windows:
venv\Scripts\activateInstall the dependencies:
pip install "u8darts[torch]" pandas numpy matplotlib scikit-learnThe u8darts[torch] package includes Darts with PyTorch-based deep learning support.
You can verify the installation:
import darts
print("Darts version:", darts.__version__)If the version prints successfully, the installation is ready.
3. Understand the Time-Series Dataset
For this example, we will build a forecasting model using daily sales data.
Our dataset will contain two columns:
Date | Sales |
|---|---|
2025-01-01 | 120 |
2025-01-02 | 135 |
2025-01-03 | 128 |
2025-01-04 | 142 |
2025-01-05 | 150 |
The objective is to use historical sales values to predict the next 30 days.
For a real business application, this data could come from a database, an API, or a CSV export from an e-commerce platform.
For this tutorial, we will generate a sample dataset containing a trend, weekly seasonality, and some random variation. This makes the forecasting workflow reproducible without requiring an external dataset.
import numpy as np
import pandas as pd
np.random.seed(42)
dates = pd.date_range(
start="2025-01-01",
periods=365,
freq="D"
)
trend = np.linspace(100, 180, 365)
weekly_seasonality = 15 * np.sin(
2 * np.pi * np.arange(365) / 7
)
noise = np.random.normal(0, 5, 365)
sales = trend + weekly_seasonality + noise
df = pd.DataFrame({
"Date": dates,
"Sales": sales
})
print(df.head())The generated dataset contains:
A gradual increase in sales over time.
A repeating weekly pattern.
Random fluctuations that simulate real-world variation.
This is a simplified dataset, but it is useful for understanding the forecasting workflow.
4. Convert Pandas DataFrame into a Darts TimeSeries
Darts uses its own TimeSeries object to represent time-series data.
You can create one directly from a Pandas DataFrame.
from darts import TimeSeries
series = TimeSeries.from_dataframe(
df,
time_col="Date",
value_cols="Sales",
freq="D"
)
print(series)Here:
time_colidentifies the date column.value_colsidentifies the values we want to forecast.freq="D"tells Darts that the observations are daily.
Darts supports different time frequencies, including daily, weekly, monthly, and hourly data.
Getting the frequency right is important because forecasting models rely on the time structure of the dataset.
Visualize the data
Before training a model, visualize the historical values.
import matplotlib.pyplot as plt
series.plot()
plt.title("Daily Sales")
plt.xlabel("Date")
plt.ylabel("Sales")
plt.show()A chart helps you identify whether the data contains a trend, repeating patterns, or unusual fluctuations.
For production datasets, it is also worth checking missing dates, duplicate timestamps, and unexpected gaps.
5. Split the Dataset into Training and Testing Data
One common mistake in time-series machine learning is randomly splitting the dataset.
In traditional machine learning, random splitting is often acceptable. However, time-series forecasting must respect chronological order.
We should train the model using historical observations and evaluate it on later observations.
train, test = series.split_before(0.8)
print("Training observations:", len(train))
print("Testing observations:", len(test))This gives us approximately:
80% of the observations for training.
20% of the observations for testing.
The training data contains earlier dates, while the testing data contains later dates.
This simulates a realistic forecasting scenario: using the past to predict the future.
6. Build Your First Forecasting Model Using Exponential Smoothing
Let's start with a statistical forecasting algorithm.
Exponential Smoothing is useful when the data contains patterns that can be represented through level, trend, and seasonality components.
Darts provides an implementation that is straightforward to use.
from darts.models import ExponentialSmoothing
model = ExponentialSmoothing()
model.fit(train)
forecast = model.predict(len(test))The fit() method trains the model using historical observations.
The predict() method generates future predictions. Here, we are asking it to predict the same number of observations as the test dataset.
Visualize actual versus predicted sales
import matplotlib.pyplot as plt
series.plot(label="Actual Sales")
forecast.plot(label="Predicted Sales")
plt.title("Actual vs Predicted Sales")
plt.legend()
plt.show()This visualization helps us understand how closely the forecast follows the actual sales values.
For data with strong weekly seasonality, explicitly configuring the seasonal period can also be useful. For daily data with a weekly pattern, the seasonal period is typically seven observations.
model = ExponentialSmoothing(
seasonal_periods=7
)
model.fit(train)
forecast = model.predict(len(test))The appropriate seasonal period depends on the data. For monthly sales with yearly seasonality, it may be 12.
7. Evaluate the Forecasting Model
A model can generate predictions, but how do we know whether those predictions are accurate?
Darts provides several evaluation metrics.
We will use Mean Absolute Error (MAE), Root Mean Squared Error (RMSE), and Mean Absolute Percentage Error (MAPE).
from darts.metrics import (
mae,
rmse,
mape
)
print("MAE:", mae(test, forecast))
print("RMSE:", rmse(test, forecast))
print("MAPE:", mape(test, forecast))Let's understand these metrics.
Mean Absolute Error (MAE) measures the average absolute difference between actual and predicted values.
Root Mean Squared Error (RMSE) gives larger errors more weight because the errors are squared before averaging.
Mean Absolute Percentage Error (MAPE) expresses prediction error as a percentage of actual values. It can be problematic when actual values are zero or close to zero.
For example, if your actual sales are 200 units and the model predicts 190 units, the absolute error is 10 units.
Do not choose a model based on one metric alone. Consider the business impact of different types of forecasting errors.
8. Try a Machine Learning Model with Random Forest
Statistical models are useful, but sometimes we need more flexibility.
Darts also supports regression-based forecasting models.
A Random Forest model can learn relationships between previous observations and future values.
from darts.models import RandomForest
rf_model = RandomForest(
lags=14,
n_estimators=100,
random_state=42
)
rf_model.fit(train)
rf_forecast = rf_model.predict(len(test))The lags=14 parameter tells the model to use the previous 14 observations as input features.
For example, when predicting tomorrow's sales, the model can use the previous 14 days of sales information.
This approach is useful when recent observations contain information about future values.
Evaluate its performance:
print("Random Forest MAE:", mae(test, rf_forecast))
print("Random Forest RMSE:", rmse(test, rf_forecast))
print("Random Forest MAPE:", mape(test, rf_forecast))Now we can compare the Random Forest model against Exponential Smoothing.
Keep in mind that the best model depends on the dataset. A more complex algorithm does not automatically produce better predictions.
9. Build a Deep Learning Forecasting Model with N-BEATS
Now let's explore a deep learning approach.
N-BEATS is a neural network architecture designed for time-series forecasting.
Unlike traditional forecasting algorithms, it learns forecasting patterns through neural network layers.
Darts provides an implementation of N-BEATS.
from darts.models import NBEATSModel
nbeats_model = NBEATSModel(
input_chunk_length=30,
output_chunk_length=7,
n_epochs=50,
random_state=42,
batch_size=32
)
nbeats_model.fit(
train,
verbose=True
)Let's understand the main parameters:
input_chunk_length=30: The model uses 30 historical observations as input.output_chunk_length=7: The model predicts seven observations per output chunk.n_epochs=50: The model trains for 50 epochs.batch_size=32: Training processes observations in batches of 32.
Generate predictions:
nbeats_forecast = nbeats_model.predict(
n=len(test)
)Evaluate the model:
print("N-BEATS MAE:", mae(test, nbeats_forecast))
print("N-BEATS RMSE:", rmse(test, nbeats_forecast))
print("N-BEATS MAPE:", mape(test, nbeats_forecast))N-BEATS can be useful for more complex forecasting problems, but it generally requires more training time and computational resources than simpler statistical models.
For a small dataset, a simpler algorithm may perform just as well or even better.
10. Compare Different Forecasting Models
After training multiple algorithms, compare their performance using the same test dataset.
results = pd.DataFrame({
"Model": [
"Exponential Smoothing",
"Random Forest",
"N-BEATS"
],
"MAE": [
mae(test, forecast),
mae(test, rf_forecast),
mae(test, nbeats_forecast)
],
"RMSE": [
rmse(test, forecast),
rmse(test, rf_forecast),
rmse(test, nbeats_forecast)
],
"MAPE": [
mape(test, forecast),
mape(test, rf_forecast),
mape(test, nbeats_forecast)
]
})
print(results.sort_values("MAE"))This creates a comparison table containing the evaluation metrics for each model.
You can use the results to identify which model performs best on your test data.
For a reliable comparison, make sure all models use the same training and testing periods and equivalent forecasting conditions.
11. Forecast the Next 30 Days
Once you have evaluated the models, you can train your selected model using all available historical data.
For this example, let's use the N-BEATS model.
final_model = NBEATSModel(
input_chunk_length=30,
output_chunk_length=7,
n_epochs=50,
random_state=42,
batch_size=32
)
final_model.fit(series)
future_forecast = final_model.predict(
n=30
)The model now uses the complete historical dataset to generate predictions for the next 30 days.
Visualize the results:
series.plot(label="Historical Sales")
future_forecast.plot(
label="Next 30 Days Forecast"
)
plt.title("30-Day Sales Forecast")
plt.xlabel("Date")
plt.ylabel("Sales")
plt.legend()
plt.show()This is the basic workflow behind a sales forecasting application.
You could extend it to forecast inventory demand, website traffic, electricity consumption, or other business metrics.
12. Save and Load Your Forecasting Model
In a real application, you should not train the model every time someone requests a forecast.
Instead, train it periodically and save the trained model.
Darts supports model persistence.
final_model.save("sales_forecasting_model.pt")Load it later:
loaded_model = NBEATSModel.load(
"sales_forecasting_model.pt"
)
future_forecast = loaded_model.predict(
n=30
)This allows you to separate model training from prediction.
For example, a scheduled background job could retrain the model every week, while your API serves forecasts using the latest saved model.
13. Integrate Darts with a FastAPI Application
If you are building a Python backend, you can expose forecasting functionality through a REST API.
For example, create a simple FastAPI endpoint that loads a trained model and returns future predictions.
Install FastAPI:
pip install fastapi uvicornCreate main.py:
from fastapi import FastAPI
from darts.models import NBEATSModel
app = FastAPI()
model = NBEATSModel.load(
"sales_forecasting_model.pt"
)
@app.get("/forecast")
def get_forecast():
prediction = model.predict(n=30)
forecast_data = [
{
"date": str(date),
"predicted_sales": float(value)
}
for date, value in zip(
prediction.time_index,
prediction.values().flatten()
)
]
return {
"forecast_days": 30,
"predictions": forecast_data
}Run the application:
uvicorn main:app --reloadOpen the following endpoint:
http://127.0.0.1:8000/forecastThe API returns JSON containing the predicted sales values and their corresponding dates.
This is a simple example. A production API should also validate inputs, handle model-loading errors, manage model versions, and avoid retraining during individual requests.
14. Important Considerations for Production Forecasting
A forecasting model that works on a sample dataset may not perform equally well with real business data.
Before deploying it, consider the following points.
Handle missing observations
Real-world datasets frequently contain missing dates or incomplete records.
Check whether your time series has missing values and decide whether interpolation, forward filling, or another domain-specific strategy is appropriate.
Understand seasonality
Sales data may contain weekly, monthly, or yearly patterns.
A forecasting model should be configured and evaluated according to the actual seasonal structure of the data.
Avoid data leakage
Never use future information while training or evaluating a forecasting model.
Keep your validation data later than your training data, and ensure that transformations are fitted using training information only.
Monitor forecasting accuracy
A model that performs well today may become less accurate when customer behavior or market conditions change.
Monitor prediction errors and retrain the model when performance drops.
Consider external variables
Sales are not influenced only by previous sales values.
Promotions, holidays, discounts, weather, and marketing campaigns can all affect future demand.
Darts supports additional covariates for models that can use them. Including relevant external variables can improve forecasts when those variables are available at prediction time.
Conclusion
Time-series forecasting is an important part of modern data-driven applications. Whether you are predicting product demand, website traffic, inventory requirements, or electricity consumption, choosing the right forecasting approach can make a significant difference.
Darts makes this process easier by providing a consistent interface for statistical, machine learning, and deep learning models.
In this tutorial, we built a complete forecasting workflow using Python and Darts. We generated sample sales data, converted it into a Darts TimeSeries, trained Exponential Smoothing, Random Forest, and N-BEATS models, compared their performance, and generated a 30-day forecast.
The most important takeaway is that you should not automatically choose the most advanced model. Start with a simple baseline, evaluate it using chronological data, and introduce more complex models only when they provide measurable improvements.
If you are learning Python for machine learning or building practical AI applications, Darts is a useful library to add to your toolkit.
Technical author and software engineer at DevByte. Writing deep-dive tutorials on distributed systems, modern full-stack web architectures, and cloud deployments.


