MG

muhgalihhh

Back to Works

GoldPricePredictionwithKNNandLinearRegression

Data Science & AnalysisMachine Learning, Data Science & Analysis (Asignment) · Universitas Jenderal Soedirman
Python
Gold Price Prediction with KNN and Linear Regression screenshot 1

Overview

This case study predicts gold price movements (Gold Futures) from daily Yahoo Finance data, 1 January 2015 to April 2025. It answers two questions: will the price go up or down, and what will the next closing price be? The forecast was submitted on 22 April 2025 and checked against the real price on 24 April 2025.

  • Context: Machine Learning course case study, Universitas Jenderal Soedirman (2025)

  • Team: Solo

  • Tools: Python, yfinance, Pandas, scikit-learn, Seaborn, Google Colab

Feature Engineering

  • Moving Averages over 5, 10, 20 and 50 days

  • Exponential Moving Averages, which react faster to recent prices

  • Momentum: today's price compared to an earlier one

  • Volatility: standard deviation of the price over a window

  • Calendar features: day, month and day of week

Rows left empty by the rolling windows were dropped, and every feature was standardized with StandardScaler, which matters for a distance-based model like KNN.

Time-Based Split

The data was split chronologically: the oldest 80% (2015 to 2024) for training and the newest 20% (into 2025) for testing, so the models are always evaluated on prices they have never seen.

Model 1: KNN for Direction

A K-Nearest Neighbors classifier predicts whether the next close goes up or down. Odd values of k from 3 to 19 were tested, and k = 19 gave the best accuracy: 89.12%.

Model 2: Linear Regression for Price

A Linear Regression model predicts the next day's closing price.

Metric

Value

MAE

$17.37

RMSE

$24.02

R²

0.9958

Among the coefficients, EMA5 pushes the prediction up strongly, while MA5 has a negative effect.

Forecast for 24 April 2025

Using the last available data point (21 April 2025), the models predicted:

Output

Prediction

Direction

Up, 100% confidence

Closing price

$3,405.36