Introduction
In this tutorial, you'll learn how to use Google's TimesFM-3, a powerful time series forecasting model that can predict multiple related time series simultaneously. This model is particularly useful for business analytics, financial forecasting, and IoT data analysis where multiple related metrics need to be predicted at once. We'll walk through setting up the environment, loading sample data, and making predictions using TimesFM-3's zero-shot capabilities.
Prerequisites
Before starting this tutorial, you should have:
- Basic Python knowledge
- Python 3.8 or higher installed
- Access to a computer with internet connection
- Basic understanding of time series data (data that changes over time, like stock prices or temperature readings)
Step-by-Step Instructions
1. Setting Up Your Environment
1.1 Install Required Packages
First, we need to install the necessary Python packages. Open your terminal or command prompt and run:
pip install torch pandas numpy
Why this step? We need PyTorch for deep learning operations, pandas for data handling, and numpy for numerical computations.
1.2 Create a New Python File
Create a new file called timesfm_tutorial.py and open it in your code editor.
2. Understanding Time Series Data
2.1 What is Time Series Data?
Time series data consists of measurements taken at regular intervals over time. Examples include:
- Stock prices every minute
- Temperature readings every hour
- Sales figures every day
For TimesFM-3, we'll work with multivariate time series - data with multiple related metrics.
2.2 Creating Sample Data
Let's create some sample multivariate time series data:
import pandas as pd
import numpy as np
dates = pd.date_range('2023-01-01', periods=100, freq='D')
# Create three related time series
np.random.seed(42)
series1 = np.cumsum(np.random.randn(100)) + 100 # Stock price-like data
series2 = series1 * 0.8 + np.cumsum(np.random.randn(100)) * 0.5 # Related metric
series3 = series1 * 0.3 + np.random.randn(100) * 2 # Another related metric
# Create DataFrame
data = pd.DataFrame({
'date': dates,
'metric1': series1,
'metric2': series2,
'metric3': series3
})
print(data.head())
Why this step? We're creating realistic sample data to demonstrate how TimesFM-3 works with multiple related time series.
3. Preparing Data for TimesFM-3
3.1 Understanding TimesFM-3 Input Format
TimesFM-3 expects data in a specific format. We need to separate past data from future data and ensure proper structure:
# Prepare past data (what we know)
past_data = data[['metric1', 'metric2', 'metric3']].values
# Prepare future data (what we want to predict)
future_data = np.array([[105.0, 85.0, 30.0]]) # Example future values
print("Past data shape:", past_data.shape)
print("Future data shape:", future_data.shape)
Why this step? TimesFM-3 needs to know what historical data it should use for predictions and what future values it should consider.
3.2 Creating the Data Structure
Let's create a function to prepare our data properly:
def prepare_timesfm_data(past_data, future_data=None, prediction_length=5):
"""Prepare data for TimesFM-3 input format"""
# Create time steps
time_steps = len(past_data)
# For demonstration, we'll use a simple approach
# In practice, TimesFM-3 handles this automatically
return {
'past_values': past_data,
'future_values': future_data,
'prediction_length': prediction_length
}
# Prepare our data
prepared_data = prepare_timesfm_data(past_data, future_data)
print("Data prepared for TimesFM-3")
Why this step? This function structures our data in the format TimesFM-3 expects, making it ready for prediction.
4. Using TimesFM-3 for Predictions
4.1 Simulating TimesFM-3 Usage
While we can't directly run TimesFM-3 without the actual model weights (which have a non-commercial license), we can demonstrate how it would be used:
def simulate_timesfm_prediction(data):
"""Simulate how TimesFM-3 would make predictions"""
# In a real implementation, this would call the actual model
print("Simulating TimesFM-3 prediction...")
# Extract past values
past_values = data['past_values']
# Get last few values for prediction
last_values = past_values[-10:] # Last 10 time steps
# Simple prediction logic (this is just a demonstration)
predictions = []
for i in range(data['prediction_length']):
# Predict next values based on trends
pred = last_values[-1] + np.random.randn() * 2
predictions.append(pred)
last_values = np.append(last_values[1:], pred)
return predictions
# Make predictions
predictions = simulate_timesfm_prediction(prepared_data)
print("Predictions for next 5 time steps:", predictions)
Why this step? This simulates how TimesFM-3 would process the data and generate predictions, helping you understand the workflow.
4.2 Interpreting Results
Let's create a simple visualization of our predictions:
import matplotlib.pyplot as plt
# Plot the results
plt.figure(figsize=(12, 6))
# Plot historical data
plt.plot(range(len(past_data)), past_data[:, 0], label='Metric 1 (Historical)', linewidth=2)
plt.plot(range(len(past_data)), past_data[:, 1], label='Metric 2 (Historical)', linewidth=2)
plt.plot(range(len(past_data)), past_data[:, 2], label='Metric 3 (Historical)', linewidth=2)
# Plot predictions (simulated)
future_steps = range(len(past_data), len(past_data) + len(predictions))
plt.plot(future_steps, predictions, 'ro--', label='Predictions', linewidth=2)
plt.xlabel('Time Steps')
plt.ylabel('Values')
plt.title('TimesFM-3 Multivariate Time Series Forecasting')
plt.legend()
plt.grid(True)
plt.show()
Why this step? Visualizing predictions helps you understand how the model's outputs relate to the actual data patterns.
5. Analyzing the Model's Capabilities
5.1 Zero-Shot Learning Concept
TimesFM-3's key feature is zero-shot learning - it can make predictions without needing to be fine-tuned for specific tasks:
- It works with multiple related time series
- No special training required for new prediction tasks
- Can handle different types of time series data
Why this matters: This makes TimesFM-3 very flexible and easy to use for various forecasting problems.
5.2 Benefits of Multivariate Forecasting
By predicting multiple related series simultaneously, TimesFM-3 can:
- Understand relationships between different metrics
- Improve accuracy by considering correlations
- Make more informed predictions
Why this matters: In real-world applications, metrics are often related - understanding these relationships improves forecasting quality.
Summary
In this tutorial, you've learned how to:
- Set up a Python environment for time series analysis
- Create and structure multivariate time series data
- Understand how TimesFM-3 processes time series data
- Simulate how the model would make predictions
- Visualize time series forecasts
While we couldn't run the actual TimesFM-3 model due to licensing restrictions, you now understand the workflow and concepts behind this powerful time series forecasting technology. This knowledge will help you when you encounter TimesFM-3 in production environments or when working with similar multivariate forecasting models.
Remember that TimesFM-3 is designed to work with large datasets and complex time series patterns, making it particularly valuable for business analytics and scientific research applications.



