Forecasting — a simple example

Global financial markets are a very interesting place to study financial time series, especially stock prices. Every year billions and billions of dollars are being traded and everybody tries to predict them.

Photo by Michael Dziedzic on Unsplash

But what is the best way to do it? How can I find the best model given the data?

In this simple tutorial I will give a small sample how can you write a simple code in R to predict stock prices.

The rule of thumb is to have to do a 80/20 split of the data, where you use 80% of the data to train your model and use the remaining 20% to test it.

Part 1

Firstly, we need to get the data and we will use data from Yahoo Finance.

Now that we have the data it is time to turn it into a dataframe.

FTSE$Date <- as.Date(FTSE$Date, format = “%d-%m-%y”)

FTSE_2 <- as.data.frame((FTSE))

Next turn it into list.

Part 2

Secondly, let us write the function that would be used to predict the time series. We can literary decide on any model and any time horizon.

Note: In the arm function you can change the model to anyone you please. For this exercise I have picked an ets model

arm <- function(x) plot(forecast(ets(x$Price),100))

Now we will apply it to our list.

forecast <- lapply(mylist,arm)

Now let’s turn the results back into a dataframe

forecast_2 <- as.data.frame(forecast)

You can view the forecast in your Rstudio Plot pane or you can export it and view it Excel.

I hope you have enjoyed the article and see you soon.

--

--

Alexander Marinov

Alexander Marinov has a wide-ranging skills including within financial services, programming and project management.