How To Build a Gold Prediction Model with Python and Prophet

Predicting the price of gold is a key interest for investors, economists, and financial analysts. While no model is a perfect crystal ball, we can use powerful time-series forecasting tools to analyze historical trends and project future possibilities.

In this tutorial, we'll use Prophet, a fast and reliable forecasting library developed by Meta (formerly Facebook). It's particularly good at handling data with strong seasonal patterns and trends. 📈

We will walk through the full process in a Jupyter Notebook, covering two different goals:

  1. Outcome 1: Loading data, training a model, and displaying an interactive forecast chart directly within your notebook for analysis.
  2. Outcome 2: Running the same forecast but exporting the results to a standalone HTML file and an Excel sheet, perfect for sharing with others.

📈 If you’re interested in working with me on a freelance project, message me on my social platforms below!




Prerequisites: Installing the Libraries

Before we start, you'll need to install the necessary Python libraries. Open a new cell in your Jupyter Notebook and run the following command. The ! tells Jupyter to run this as a shell command.

!pip install pandas prophet plotly xlsxwriter

Here's what each library does:

  • pandas: The most popular library for data loading, manipulation, and analysis.
  • prophet: Meta's time-series forecasting library.
  • plotly: Used for creating rich, interactive charts.
  • xlsxwriter: A library for writing files in the Microsoft Excel .xlsx format.



Download the Dataset

This tutorial requires a CSV file with historical gold price data. You can download this dataset here.

📊 Download Gold Price Dataset

Click the button below to Download Excel Sheet. Download this file and practice.

9
Download IconDownload File



The Core Code: Loading Data and Training the Model

Both of our scripts share the same foundation: loading the data, preparing it, and training the Prophet model. Let's break down these initial functions which are common to both approaches.

1. Displaying the Forecast Interactively

For displaying The Gold Rate forecast interactively in Jupyter Notebook You just need to copy past Code Given below in Jupyter Notebook and then Run

🐍 Python Code
# Gold Price Prediction
import pandas as pd
from prophet import Prophet
from prophet.plot import plot_plotly
import plotly.graph_objects as go

def load_and_prepare_data(filepath: str) -> pd.DataFrame:
    """Load CSV, convert to 10g gold price, and prepare for Prophet."""
    df = pd.read_csv(filepath)
    df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
    df = df.sort_values('Date')

    df['Gold_10g_USD'] = df['Close'] * (10 / 31.1035)
    df['Gold_10g_USD_24K'] = df['Gold_10g_USD']

    df_prophet = df[['Date', 'Gold_10g_USD_24K']].rename(columns={'Date': 'ds', 'Gold_10g_USD_24K': 'y'})
    return df_prophet

def train_and_forecast(df_prophet: pd.DataFrame, forecast_days: int = 3650) -> tuple[Prophet, pd.DataFrame]:
    """Train Prophet model and forecast future prices."""
    model = Prophet()
    model.fit(df_prophet)
    future = model.make_future_dataframe(periods=forecast_days)
    forecast = model.predict(future)
    return model, forecast

def plot_forecast_with_actual(model: Prophet, forecast: pd.DataFrame, original_df: pd.DataFrame) -> None:
    """Interactive plot of forecast with actual historical data and $ prefix."""
    fig = plot_plotly(model, forecast)

    fig.add_trace(go.Scatter(
        x=original_df['ds'],
        y=original_df['y'],
        mode='lines',
        name='Actual (10g Gold Price)',
        line=dict(color='black', width=2)
    ))

    fig.update_layout(
        title="Gold Price Forecast vs Actual (10g USD)",
        xaxis_title="Date",
        yaxis_title="Price (USD)",
        yaxis=dict(tickprefix="$"),
        legend=dict(x=0.01, y=0.99)
    )
    fig.show()

if __name__ == "__main__":
    filepath = "XAU USD Gold Price.csv"
    df_prophet = load_and_prepare_data(filepath)
    model, forecast = train_and_forecast(df_prophet, forecast_days=3650)
    plot_forecast_with_actual(model, forecast, df_prophet)

After running this code, the interactive visualization will appear Like below image.



2. Exporting to HTML and Excel

To export the gold rate interactive forecast visualization to HTML and Excel files using Jupyter Notebook, simply copy and paste the code given below into your Jupyter Notebook and then run it.

🐍 Python Code
# Gold Price Prediction With Export HTML & Excel Data
import pandas as pd
from prophet import Prophet
from prophet.plot import plot_plotly
import plotly.graph_objects as go

def load_and_prepare_data(filepath: str) -> pd.DataFrame:
    df = pd.read_csv(filepath)
    df['Date'] = pd.to_datetime(df['Date'], dayfirst=True)
    df = df.sort_values('Date')
    df['Gold_10g_USD'] = df['Close'] * (10 / 31.1035)
    df['Gold_10g_USD_24K'] = df['Gold_10g_USD']
    df_prophet = df[['Date', 'Gold_10g_USD_24K']].rename(columns={'Date': 'ds', 'Gold_10g_USD_24K': 'y'})
    return df_prophet

def train_and_forecast(df_prophet: pd.DataFrame, forecast_days: int = 3650) -> tuple[Prophet, pd.DataFrame]:
    model = Prophet()
    model.fit(df_prophet)
    future = model.make_future_dataframe(periods=forecast_days)
    forecast = model.predict(future)
    return model, forecast

def export_forecast_to_excel(forecast: pd.DataFrame, output_path: str = "Gold_Price_Forecast.xlsx") -> None:
    forecast_to_export = forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].copy()
    forecast_to_export.columns = ['Date', 'Predicted Price', 'Lower Bound', 'Upper Bound']
    with pd.ExcelWriter(output_path, engine='xlsxwriter') as writer:
        forecast_to_export.to_excel(writer, sheet_name='Forecast', index=False)

def save_interactive_plot(model: Prophet, forecast: pd.DataFrame, original_df: pd.DataFrame, output_html: str = "Gold_Price_Forecast.html") -> None:
    fig = plot_plotly(model, forecast)
    fig.add_trace(go.Scatter(
        x=original_df['ds'],
        y=original_df['y'],
        mode='lines',
        name='Actual (10g Gold Price)',
        line=dict(color='black', width=2)
    ))
    fig.update_layout(
        title="Gold Price Forecast vs Actual (10g USD)",
        xaxis_title="Date",
        yaxis_title="Price (USD)",
        yaxis=dict(tickprefix="$"),
        legend=dict(x=0.01, y=0.99)
    )
    fig.write_html(output_html)

if __name__ == "__main__":
    filepath = "XAU USD Gold Price.csv"
    df_prophet = load_and_prepare_data(filepath)
    model, forecast = train_and_forecast(df_prophet, forecast_days=3650)
    export_forecast_to_excel(forecast, "Gold_Price_Forecast.xlsx")
    save_interactive_plot(model, forecast, df_prophet, "Gold_Price_Forecast.html")

After running this code, the interactive visualization HTML and Excel files will be saved in the folder where Python is installed.



📹 Video Tutorial




Conclusion

You've successfully built a 10-year gold price forecast using Prophet! More importantly, you now have two distinct methods for handling the output: one for quick, personal analysis (fig.show()) and another for creating professional, shareable reports (fig.write_html() and .to_excel()).

Disclaimer: Remember, all financial forecasts are models based on historical trends. They are not guarantees of future performance, do not account for sudden market shocks or geopolitical events, and are provided for educational purposes only.

Post a Comment

Previous Post Next Post