top of page
  • Nikhil Adithyan

Forecasting Gold Prices with TimeGPT

Updated: Aug 19

Leveraging LLMs to predict market trends



Gold has long been considered a valuable commodity and a safe-haven asset for investors. Accurate forecasting of gold prices is crucial for making informed investment decisions, managing risk, and successful trading strategies. In this article, we will explore how TimeGPT, a state-of-the-art time series LLM model, can be used in conjunction with gold price data extracted from a reliable data provider, MetalpriceAPI, to forecast future prices.


TimeGPT

TimeGPT is the first foundation model for time series, introduced in the paper: TimeGPT-1. It was trained on publicly available time series datasets from various domains spanning finance, economics, healthcare, and IoT sensors. It is a Transformer-based time series model incorporating self-attention mechanisms to capture the intricacies of temporal patterns. The model features an encoder-decoder structure with multiple layers, residual connections, and layer normalization. By integrating local positional encoding and leveraging historical data windows, TimeGPT enriches its input to forecast future values with accuracy.


TimeGPT’s performance in time series forecasting surpasses conventional benchmarks, demonstrating state-of-the-art results in relative Mean Absolute Error (rMAE) and relative Root Mean Squared Error (rRMSE) metrics across various frequencies making it a good candidate for price forecasting.


Getting The Data

To be able to forecast gold prices we must undertake the following steps:


  1. Sign up for a MetalpriceAPI account here. Obtain an API key which will be used to authenticate your requests and retrieve the data.

  2. Use the Python requests library to make HTTP requests to the API endpoint and retrieve the last 365 days of daily gold price data.

  3. Parse the API response, which is in JSON format, and extract the relevant price information.

  4. Preprocess the data by taking the reciprocal of the returned to get the USD price of gold per troy ounce


Here’s an example code snippet that demonstrates how to implement the above steps using Python:



import requests
import pandas as pd

metalprice_api_key = '<your_api_key>'

def get_gold_prices(api_key):
    
    url = f'https://api.metalpriceapi.com/v1/timeframe?api_key={api_key}&start_date=2023-06-01&end_date=2024-05-31&base=USD&currencies=XAU'
    response = requests.get(url)
    data = response.json()
    
    prices = []
    dates = []
    
    for date, price in data['rates'].items():
        prices.append(price['XAU'])
        dates.append(date)
    
    return prices, dates

# Retrieve the gold prices and dates
gold_prices, dates = get_gold_prices(metalprice_api_key)

# Create a DataFrame to store the prices and dates
df = pd.DataFrame({'Date': dates, 'Price': gold_prices})

# Convert the 'Date' column to datetime format
df['Date'] = pd.to_datetime(df['Date'])

# Apply the reciprocal transformation to the prices
df['Price'] = 1 / df['Price']


Setting up TimeGPT

Next, in order to use TimeGPT we want to set up an account with Nixtla, the time series research and machine learning company that created TimeGPT. Note the TimeGPT is a closed-source model and is currently available to use for free.


  1. Setup an account and get the API key here

  2. We install the Nixtla library and import the NixtaClient

  3. The input into timeGPT is a dataframe with two columns one named “ds” which contains the time variable and the other called “y” which encapsulates the predictor. We rename our original dataframe columns to conform to these naming conventions

  4. We define the input parameters as:

    1. the list of confidence levels to be considered for forecasting levels

    2. the number of forecast periods in the future "h"


In the case of daily gold prices, the forecast period frequency is daily. The forecasting can’t be too far into the future, otherwise, the model will return a warning on the model horizon being exceeded, leading to inaccurate forecasts.



pip install nixtla

from nixtla import NixtlaClient

nixtla_api_key = '<your_nixtla_api_key>'

# initiate nixtla client

nixtla_client = NixtlaClient(
   
    api_key = nixtla_api_key
)

# rename columns 
df.rename(columns={'Date': 'ds', 'Price': 'y'}, inplace=True)

# define the relevant confidence levels

level = [50,80,90] # confidence levels 

fcst = nixtla_client.forecast(df, h=7, level=level)
fcst.head()

nixtla_client.plot(df, fcst, level=level)

A plot will be generated with the forecast and the nominated confidence intervals.



We can zoom in on the days leading up to the forecast horizon by passing a shorter lead-up period to the max_insample_length parameter, note this doesn’t create a new forecast with a shorter context window, but rather zooms in on the chart



nixtla_client.plot(df, fcst, level=level, max_insample_length=30)


The forecasted prices and confidence interval can be viewed by displaying the dataframe holding the forecasts.



fcst.head(7)


The above dataframe represents the price predictions for Gold made by TimeGPT. Each row in the dataframe corresponds to a specific date (ds) and contains the predicted Gold price (TimeGPT) for that date.


Additionally, the dataframe includes various prediction intervals, denoted as TimeGPT-lo-90, TimeGPT-lo-80, TimeGPT-lo-50, TimeGPT-hi-50, TimeGPT-hi-80, and TimeGPT-hi-90. These intervals represent the lower and upper bounds of the predicted price at different confidence levels, where lo indicates the lower bound and hi indicates the upper bound. For instance, TimeGPT-lo-90 and TimeGPT-hi-90 represent the 90% confidence interval, meaning there is a 90% probability that the actual price will fall within this range.


The dataframe allows analysts to understand not just the central price prediction but also the uncertainty and possible variation around this prediction. For each date, the central prediction is accompanied by ranges that show how much the price might deviate. For example, on June 1, 2024, the predicted price is 2341.20, but the actual price could vary between 2285.81 and 2396.59 with 90% confidence.


Conclusion

Forecasting gold prices accurately is essential for investors and traders to navigate the complexities of the gold market. The ability to predict future price movements allows for better risk management and more strategic investment decisions.


By combining the advanced capabilities of TimeGPT with daily price data obtained through the MetalpriceAPI, we can create a powerful framework for predicting gold price trends. This integration of cutting-edge technology and reliable data sources enhances the precision of forecasts, providing investors with a significant edge in the market.


With that being said, you’ve reached the end of the article. I hope you learned something new and useful today about utilizing advanced AI models like TimeGPT for gold price forecasting. Accurate predictions can significantly impact your investment outcomes, and I encourage you to explore these tools further. Thank you very much for your time.

Comments


bottom of page