Gold Price Forecast using Neural Networks

Akshay Ardeshana
Analytics Vidhya
Published in
3 min readOct 5, 2020

Step 1:- Information About dataset & basic operations

Step 2:- Visualization of dataset .

Step 3:- Making a window dataset for forecasting

Step 4:- Build a neural network and train and validate on a window dataset

The link for the ipynb notebook file and the dataset is below:-

Step 1:- Information About dataset & basic operations

The dataset contains information about gold and silver prices.

import pandas as pdgold_data=pd.read_csv('/content/drive/MyDrive/dataset/Goldsorted_final.csv')gold_data
Gold dataset

In this dataset, The price is from 22 August 2019 to 28 September 2020.

Step 2:- Visualization of dataset

We are using the TensorFlow 2.3.0 version.

import tensorflow as tfimport numpy as npimport matplotlib.pyplot as pltprint(tf.__version__)

Write a function for the plot.

def plot_series(time, series, format="-", start=0, end=None):  plt.plot(time[start:end], series[start:end], format)  plt.xlabel("index")  plt.ylabel("Gold 999(AM Price)")  plt.grid(True)

Plot a diagram for visualization.

import csvtime_step = []goldinfo = []with open('/content/drive/My Drive/dataset/Goldsorted_final.csv') as csvfile:reader = csv.reader(csvfile, delimiter=',')  next(reader)  for row in reader:    goldinfo.append(float(row[2]))    time_step.append(int(row[0]))series = np.array(goldinfo)time = np.array(time_step)plt.figure(figsize=(10, 6))plot_series(time, series)

Above we are using an index as Time and Gold 999(AM Price) columns as a Value.

Step 3:- Making a window dataset for forecasting

We are using the concept of window dataset for making this dataset.

For more information about the window dataset, you can refer to the below link …

In that, we use the window size as 10 which means the index of 1 to 10 is used as input value X and the 11 value is used as label y. Using TensorFlow, we can easily do this.

split_time = 200time_train = time[:split_time]x_train = series[:split_time]time_valid = time[split_time:]x_valid = series[split_time:]window_size = 10batch_size = 4shuffle_buffer_size = 77def windowed_dataset(series, window_size, batch_size, shuffle_buffer):  dataset = tf.data.Dataset.from_tensor_slices(series)  dataset = dataset.window(window_size + 1, shift=1,      drop_remainder=True)  dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))  dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1]))  dataset = dataset.batch(batch_size).prefetch(1)  return dataset

The windowed_dataset function in the above code snippet is used for making a window dataset.

Let’s call the windowed_dataset function…

dataset = windowed_dataset(x_train, window_size, batch_size, shuffle_buffer_size)

Step 4:- Build a neural network and train and validate on a window dataset

We are using the Dense layer and The Rectified Linear Unit Activation Function.

The optimizer used in this project is Adam. Adam is an optimization algorithm that can be used to update network weights iterative based on training data.

The loss function used in this project is mse.

model = tf.keras.models.Sequential([tf.keras.layers.Dense(64, input_shape=[window_size], activation="relu"),tf.keras.layers.Dense(32, input_shape=[window_size], activation="relu"),tf.keras.layers.Dense(16, input_shape=[window_size], activation="relu"),tf.keras.layers.Dense(8, activation="relu"),tf.keras.layers.Dense(1)])model.compile(loss="mse", optimizer=tf.keras.optimizers.Adam())model1=model.fit(dataset,epochs=1000)
forecast=[]for time in range(len(series) - window_size):  forecast.append(model.predict(series[time:time + window_size][np.newaxis]))forecast = forecast[split_time-window_size:]results = np.array(forecast)[:, 0, 0]plt.figure(figsize=(10, 6))plot_series(time_valid, x_valid)plot_series(time_valid, results)
tf.keras.metrics.mean_absolute_error(x_valid, results).numpy()

bravo! 😜

--

--

Akshay Ardeshana
Analytics Vidhya

Python Developer | Technophile Actively looking for an opportunity in AI/ML