Skip to content
Time Series Forecasting with TimeGPT
Getting Started with TimeGPT
%%capture
%pip install nixtla>=0.5.1
%pip install yfinance
import pandas as pd
import yfinance as yf
from nixtla import NixtlaClientGet your API Key at dashboard.nixtla.io
import os
timegpt_api_key = os.environ["TIMEGPT_API_KEY"]
# Setup NixtlaClient
nixtla_client = NixtlaClient(api_key = timegpt_api_key)
# Downloading Amazon stock price data
ticker = 'AMZN'
amazon_stock_data = yf.download(ticker)
amazon_stock_data = amazon_stock_data.reset_index()
# Displaying the dataset
amazon_stock_data.head()
amazon_stock_data.describe()nixtla_client.plot(amazon_stock_data, time_col='Date', target_col='Close')model = nixtla_client.forecast(df=amazon_stock_data, model='timegpt-1', h=24,freq="B", time_col='Date', target_col='Close')
model.tail()nixtla_client.plot(amazon_stock_data, model, time_col='Date', target_col='Close',max_insample_length=60 )Loading the Australian Electricity Demand Dataset
The Dataset is from https://zenodo.org/records/4659727
import pandas as pd
def read_tsf_from_file(file_path):
data = []
start_date = pd.to_datetime('2002-01-01 00:00:00')
# Open and read the file from the directory
with open(file_path, 'r') as file:
for line in file:
if line.startswith('T'):
parts = line.strip().split(':')
unique_id = parts[0] + '-' + parts[1]
values = list(map(float, parts[3].split(',')[:-1]))
# Generate datetime index at half-hour intervals
periods = len(values)
date_range = pd.date_range(start=start_date, periods=periods, freq='30min')
# Append to data list
for dt, value in zip(date_range, values):
data.append([unique_id, dt, value])
# Convert the list of data into a DataFrame
return pd.DataFrame(data, columns=['unique_id', 'ds', 'y'])
# Example usage
file_path = 'australian_electricity_demand_dataset.tsf'
demand_df = read_tsf_from_file(file_path)
# Display the dataframe
demand_df.head()nixtla_client.plot(
demand_df,
max_insample_length=365,
)Anomaly Detection
# Detect anomalies
anomalies_df = nixtla_client.detect_anomalies(
demand_df,
time_col='ds',
target_col='y',
freq='H',
)
anomalies_df[anomalies_df["anomaly"]==1].head()