Data Acquisition and Preparation
Lecture 1 – Confident Presentations (Healthy DMU)
This session is relevant for your assignment.
Click here for the & a file supporting the session.
This link will be used during the session: https://padlet.com/DMUdisability/confident-presentations-e62q6tn8vh9h available to students
The sessions:
Tue 5th 9am HU2.01
Wed 6th 1pm HU2.01
Lecture 2 – Performance & Evaluation II
Slide 1
Slide 2
#UK unemployment
We need to install the libraries before hand, so we can use the commands below
library(readxl)
install.packages(“forecast”)
library(forecast)
We download the data from the ONS and selected the monthly reading
ONS_UKgdp <- read_excel(“ONS UKgdp.xls”)
View(ONS_UKgdp)
par(mfrow = c(1,1))
we define the data as time series and generated our first time series graph
gdp.ts <- ts(ONS_UKgdp$gdpgrowth, start = c(1956,1), end = c(2017, 3), freq = 4)
plot(gdp.ts, xlab = “Date”, ylab = “UK GDP growth”, main = “UK GDP growth”)
This section contains the partition of the dataset into training and validation period.
stepsAhead <- 5
nTrain <- length(gdp.ts) - stepsAhead
train.ts <- window(gdp.ts, start = c(2011, 1), end = c(1956,nTrain))
valid.ts <- window(gdp.ts, start = c(1956, nTrain + 1), end = c(1956, nTrain + stepsAhead))
trainvalid.ts <- window(gdp.ts, start = c(2011, 1), end = c(2017,3))
This is the command for the naive forecast, I am creating the variable ‘naive4cast’, which is going
to capture the results for the naive forecast in the training period.
snaive4cast<-snaive(train.ts, h= 5)
We forecast using the training period
forecast(snaive4cast, h=5)
We find level of accuracy, we will cover this during the next lecture
accuracy(snaive4cast,valid.ts)
We create a histogram of the residuals/errors/ random error
hist(naive4cast$residuals, ylab = “Frequency”, xlab = “Forecast Error”, bty = “l”, main = ““)
We plot the results of the forecast
plot(forecast(snaive4cast), ylim = c(-8,12), ylab = “UK GDP growth”, xlab=“Year-quarter”, bty=“l”,
xaxt=“n”, xlim= c(2011, 2018.5), main = “UK GDP growth forecast (Naive - seasonal)”, flty= 2)
axis(1, at = seq(2011, 2018, 1), labels = format(seq(2011, 2018, 1)))
we plot the validation period
lines (valid.ts)
#we plot the forecast for the validation period
lines(snaive4cast$fitted, lwd = 2)
We do the same, but we use the full time series to forecast 2018
fullnaive <-snaive(trainvalid.ts, h= 12)
forecast(fullnaive)
plot(forecast(fullnaive), ylim = c(0,12), ylab = “UK GDP growth”, xlab=“Year”, bty=“l”,
xaxt=“n”, xlim= c(2011, 2020.5), main = “UK GDP growth forecast 2018 (Naive - Seasonal)”, flty= 2)
axis(1, at = seq(2011, 2019, 1), labels = format(seq(2011, 2019, 1)))
lines(fullnaive$fitted, lwd = 2)
#prediction cones
gdp.ets.aan <- ets(trainvalid.ts, model=“AAN”)
gdp.ets.mnn <- ets(trainvalid.ts, model=“MMN”, damped=FALSE)
gdp.ets.mmdn <- ets(trainvalid.ts, model=“MMN”, damped=TRUE)
gdp.ets.aan.pred <- forecast(gdp.ets.aan, h=12, level= c(0.2,0.4, 0.6, 0.8) )
gdp.ets.mnn.pred <- forecast(gdp.ets.mnn, h=12, level= c(0.2,0.4, 0.6, 0.8) )
gdp.ets.mmdn.pred <- forecast(gdp.ets.mmdn, h=12, level= c(0.2,0.4, 0.6, 0.8) )
par(mfrow = c(1,3)) # this command sets the plot window to show 1 row of 3 plots
plot(gdp.ets.aan.pred, xlab=“Year”, ylab=“GDP growth in %”, ylim= c(-2,5) )
plot(gdp.ets.mnn.pred, xlab=“Year”, ylab=“GDP growth in %”, ylim= c(-2,5) )
plot(gdp.ets.mmdn.pred, xlab=“Year”, ylab=“GDP growth in %”, ylim= c(-2,5) )
accuracy(gdp.ets.mnn.pred$fitted,valid.ts)
#Hyndman, R.J., Koehler, A.B., Snyder, R.D., and Grose, S. (2002) “A state space framework for automatic forecasting using exponential smoothing methods”, International J. Forecasting, 18(3), 439-454.
#Hyndman, R.J., Akram, Md., and Archibald, B. (2008) “The admissible parameter space for exponential smoothing models”. Annals of Statistical Mathematics, 60(2), 407-426.
#Hyndman, R.J., Koehler, A.B., Ord, J.K., and Snyder, R.D. (2008) Forecasting with exponential smoothing: the state space approach, Springer-Verlag. http://www.exponentialsmoothing.net.
par(mfrow = c(1,1))
Code for computing the predictive measures for roll-forward one-month ahead forecasts
we create this variables to generate the roll window
fixed.nValid <- 12
fixed.nTrain <- length(gdp.ts) - fixed.nValid
stepsAhead <- 1
we create the variable error using the command rep, this command replicates a date
error <- rep(0, fixed.nValid - stepsAhead + 1)
percent.error <- rep(0, fixed.nValid - stepsAhead + 1)
we create a loop
for(j in fixed.nTrain:(fixed.nTrain + fixed.nValid - stepsAhead)) {
the training period will increase in one observation/date
train1.ts <- window(gdp.ts, start = c(1956, 1), end = c(1956, j))
de validation period will decrease in one observation/date
valid1.ts <- window(gdp.ts, start = c(1956, j + stepsAhead), end = c(1956, j + stepsAhead))
we create the naive forecast for the training period
naive.pred <- naive(train1.ts, h = stepsAhead)
we save the forecasted results to the variable ‘error’
error[j - fixed.nTrain + 1] <- valid1.ts - naive.pred$mean[stepsAhead]
percent.error[j - fixed.nTrain + 1] <- error[j - fixed.nTrain + 1]/ valid1.ts
}
we calculate the following statistics
mean(abs(error))
sqrt(mean(error^2))
mean(abs(percent.error))
stepsAhead <- 12
nTrain <- length(gdp.ts) - stepsAhead
train.ts <- window(gdp.ts, start = c(1956, 1), end = c(1956,nTrain))
valid.ts <- window(gdp.ts, start = c(1956, nTrain + 1), end = c(1956, nTrain + stepsAhead))
plot(gdp.ts, ylim = c(-6,5), ylab = “UK GDP growth”, xlab=“Year”, bty=“l”,
xaxt=“n”, xlim= c(2011, 2018.5), main = “UK GDP forecast (roll - Naive)”, flty= 2)
axis(1, at = seq(2011, 2018, 1), labels = format(seq(2011, 2018, 1)))
error.ts <- ts(error, start = c(2014,4), end = c(2017, 3), freq = 4)
validation.ts <- window(gdp.ts, start = c(2014, 4), end = c(2017, 3))
forecast.ts <- (validation.ts - error.ts)
we plot the validation period
lines (forecast.ts, lwd=2)
Lecture 3: video: Forecasting Methods & Smoothing Methods I
Lecture 4: video: Smoothing Methods II and III
Lab 7 – Refinitiv: ECOP / Covid: naïve forecast
Adapted from Advanced user Manual for Refinitiv (2016)
Economic Indicator Poll
Another APP to the different economic markets would be the Economic Indicator poll.
By selecting the country as well as the indicator, users can view the Reuters Poll (consolidated from different polls) as well SmartEstimate and the Actual figures.
In the Eikon toolbar, search
Uncheck the boxes below ‘Actual’. You can also explore individual contributors in the tab ‘Contributor Data’. Afterwards, download the actual values by clicking on the appropriate Excel Icon.
Revisiting the dataset of Covid deaths in the UK, what analysis can we perform from the forecasts?
In the search box type ‘United Kingdom weekly deaths’ and choose the ticker ‘aGBEDTEX’
Click on the export ‘excel data’ icon, and download all the available observations of data.
Remember to log in to Refinitiv within your Excel software.
Select the dataset fro row 17 and copy and paste the values in a new sheet; afterwards, delete the sheet ‘Historical Values’. The file should look like in the picture below.
Sort the data by date from oldest to newest.
Save the dataset in your folder as ‘e-deaths.xlsx’
Open RStudio and upload the file ‘covid-deaths.xlsx’
Check what is the directory R is looking at
getwd()
change the working directory
setwd(“C:/Users/Cam/OneDrive - De Montfort University/a-ECON2545 2022-23 PUBLIC/datasets/”)
open the library of commands to download excel files
library(readxl)
#create an object edeaths for the excel file e-deaths.xlsx
edeaths <- read_excel(“e-deaths.xlsx”)
#view the object e
View(edeaths)
Plot the variable ‘average daily deaths’
plot(edeaths$excess)
Enter the following key dates (bulletpoints taken from the Independent and wikipedia) using the command abline. use red for restrictive measures, blue for unrestrictive measures, black for ‘other’ important information.
March 23: The UK public is told that they will only be allowed to leave their homes for limited reasons, including food shopping, exercise once per day, medical need and travelling for work when absolutely necessary. All shops selling non-essential goods are told to close, gatherings of more than two people in public are banned, events including weddings - but excluding funerals - are cancelled.
10 May: Mr Johnson announces the first easing of England’s lockdown, telling people they are allowed to sunbathe in parks and leave the house to exercise more than once a day. He says England may be in a position “to begin the phased reopening of shops” and get primary pupils back to school in steps staggered by year groups “at the earliest by 1 June”.
1 June: Lockdown measures are eased, with school children in England in Reception, Year 1 and Year 6 returning to the classroom.
15 June: England’s retail parks, high streets and shopping centres welcome customers, while zoos and safari parks open their doors for the first time since March. Places of worship reopen for private prayer while some secondary school pupils have begun returning to their classrooms.
16 June: The cheap steroid dexamethasone is hailed as a major breakthrough as a study suggests it is the first drug to reduce deaths from coronavirus.
28 August: Those facilitating or organising illegal raves, unlicensed music events, or any other unlawful gathering of more than 30 people may now face a £10,000 fine, as tougher measures come into force before the bank holiday weekend.
11 September: The R value of coronavirus transmission across the UK rises above 1 for the first time since early March, according to government advisers, with the estimate between 1.0 and 1.2.
18 September: Mr Johnson warns that a second wave of coronavirus has arrived in the UK. Sage estimates the R number - representing the number of people an infected person will pass the virus to - at between 1.1 and 1.4, meaning cases could rise very quickly.Parts of England’s North West, West Yorkshire and the Midlands face tough new restrictions in response to “major increases” in cases.
21 September: Chief scientific adviser Sir Patrick tells a televised briefing the UK could see 50,000 cases a day by mid-October and a daily death toll of 200 or more a month later unless urgent action is taken.
22 September: The prime minister announces new restrictions, including a 10pm curfew on pubs, bars and restaurants in England from 24 September, while face coverings are made mandatory in more scenarios and limits for weddings and receptions are cut to 15 people maximum. Scotland and Northern Ireland deviate from the restrictions in place for England by announcing bans on households mixing indoors, while Wales includes a ban on alcohol sales in off-licences and supermarkets after 10pm in addition to the curfew on hospitality venues.
24 September: New regulations (SI 1029) come into force, in part, at 5 am in England, prohibiting certain ′restricted businesses′ and ′restricted services′ from carrying on that business or providing that service between the hours of 22:00 and 05:00. The regulations affect a wide range of establishments, including restaurants, bars, public houses, social clubs, casinos, bingo halls, bowling alleys, cinemas, theatres, concert halls, amusement arcades, funfairs (indoors or outdoors), theme parks and adventure parks. The protected area of Bolton is excluded from the scope of this legislation as additional restrictions apply
27 September: The Labour Party urges the government to pause the return of university students as thousands self-isolate due to COVID-19 outbreaks, but the return is defended by Culture Secretary Oliver Dowden, who says clear guidelines are in place for universities. David Lammy, the Shadow Secretary of State for Justice, expresses concern that 10pm pub curfews have led to drinkers continuing to socialise afterwards, with them “hanging around towns” and “potentially spreading the virus”.
2 October: Around a quarter of the population of the United Kingdom, about 16.8 million people, are now in local lockdowns. This includes 23% of people in England, 76% of people in Wales and 32% of people in Scotland
14 October: The new three-tier system of restrictions for England, taking effect from 14 October. Areas are grouped into one of three risk categories – medium, high, or very high. Medium areas are subject to the rule of six and the 10pm curfew, high areas have restrictions on indoor meetings but groups of six can continue to meet in outdoor settings, and very high areas will see the closure of businesses such as pubs and casinos, but not restaurants. The Liverpool City Region is the only area to be placed in the very high category
31 October: After scientists project that there could be several thousand COVID deaths a day, Prime Minister Boris Johnson announces a second lockdown for England, for four weeks from Thursday 5 November to Wednesday 2 December, in order to prevent what he describes as a “medical and moral disaster” for the NHS. England will then revert back to the tier system.
We add vertical lines with the command abline
abline(v =4, col=“red”)
abline(v =6, col=“blue”)
there are three events in June, we only use one vertical line
abline(v =7, col=“blue”)
abline(v =9, col=“red”)
abline(v =10, col=“red”)
Was covid a hoax?
Going forward, what timelines makes sense to make the partitions of the data to forecast?
Perform a 12 months forecast using seasonal naïve forecast; what would be the beast ?
install the package forecast if you have not done so previously.
install.packages(“forecast”)
#open the library forecast
library(forecast)
create the object snaive.edeaths to keep in there the snaive estimation
by visualisation I used a 10 months frequency in the waves on this data
#h=6 as the excercise asks for a 6 monts forecast
snaive.edeaths <- snaive(ts(edeaths$excess, frequency = 10), h=12)
plot(snaive.edeaths)
To what extend the excess deaths decreased using the first wave of covid and the last fourth wave?
Excess deaths decreased 83,17%
What are the maximum deaths in the new calculation?
Around 34,881 excess deaths.
Create two horizontal lines, one for zero (2015-19 average), and the second for the peak of the last death wave.
If excess deaths cross that threshold there might be a new lockdown?
Do we anticipate a lockdown this Christmas?
How many excess deaths register the dataset in the first 12 months?
325,624
How many casualties the model forecast in 12 months? Is this the new normal?
The same number of the previous 12 months, 196,080.
What could be an appropriate date to perform a partition?
The troughts of the waves
Why were the data partitioned?
The validation partition provides a benchmark against which to test predictions, which is important because the goal of this effort is to forecast future excess deaths in the context of covid and backlogs in the treatment of other health issues.
Why did the analyst choose 12 months for the validation period?
The forecast horizon is monthly forecasts for 1-12 months ahead. Choosing 12 months for the validation partition allows evaluating the prediction accuracy of 12-month ahead forecasts. A choice of a longer validation period might have been avoided to include recent data in the training period.
What is the naive forecast for the validation period? (assume that you must provide forecasts for 12 months ahead)
Because there is seasonality in the series (waves), the naïve forecast for each of the months in the validation period is equal to an estimation of the duration of the wave, ceteris-paribus of other variables that can shorten or increase the length of the wave.
Compute the RMSE and MAPE for the naive forecasts.
RMSE =
MAPE =
partition of the data and forecast
we define the data as time series and generated our first time series graph
edeaths.ts <- ts(edeaths$excess, start = c(2019,12), end = c(2022, 10), freq = 12)
plot(edeaths.ts, xlab = “Date”, ylab = “weekly excess deaths per month”, main = “UK Excess Deaths”)
stepsAhead <- 9
nTrain <- length(edeaths.ts) - stepsAhead
train.ts <- window(edeaths.ts, start = c(2019, 12), end = c(2019,nTrain+12), freq=12)
lines(train.ts, col=“blue”)
valid.ts <- window(edeaths.ts, start = c(2019, nTrain + 13), end = c(2019, 12+nTrain + stepsAhead), freq=12)
lines(valid.ts, col =“red”)
This is the command for the naive forecast, I am creating the variable ‘naive4cast’, which is going
to capture the results for the naive forecast in the training period.
snaive4cast<-snaive(train.ts, h= 9)
We forecast using the training period
forecast(snaive4cast, h=9)
We find level of accuracy, we will cover this during the next lecture
accuracy(snaive4cast,valid.ts)
plot(snaive4cast)
lines(valid.ts)
We create a histogram of the residuals/errors/ random error
hist(snaive4cast$residuals, ylab = “Frequency”, xlab = “Forecast Error”, bty = “l”, main = ““)
Plot a histogram of the forecast errors that result from the naive forecasts (for the validation period). Plot also a time plot for the naive forecasts and the actual sales numbers in the validation period. What can you say about the behavior of the naive forecasts?
The naïve forecasts are under-predictions of actual sales. This can be seen in both plots.
The analyst found a forecasting model that gives satisfactory performance on the validation set. What must she do to use the forecasting model for generating forecasts for year 2002?
The training and validation periods must be re-combined, and then the forecasting model should be applied to the complete series before producing future forecasts. (we did this at the beginning of this lab)
Lab 8 – Refinitiv: KEYST, ECOW, COUN, WEI / API: Connecting R to Bloomberg
REFINITIV/EIKON – end of cross asset commands
Activity 1. Key Stats
The KeyStats page allows users to compare a maximum of three different securities and to compare them across different valuation methods. In the Eikon Toolbar, search and choose the three securities to compare: Fresnillo, Centamin, and Polymetal. Search the meaning of the indicators and discuss what could be the best gold miner from this selection of companies.
REFINITIV/EIKON – Forex commands
Explore the following:
- FXBUZZ
Bloomberg
Activity 3. finding datasets for assignments
There is a very wide array of information available on Bloomberg. Information can typically be split into country, industry or company information. This information sheet does not cover all of the detailed information which you may need, but should act as a signpost for where to find the information you need.
COUNTRY-LEVEL INFORMATION
ECOW
COUN
WEI
FFM
Hit the key
Activity 3. Using Bloomberg From R and Excel
Bloomberg from R
First, you need to be logged on to Bloomberg.
If the Bloomberg/Excel add-in does not work, then: 1. Close Excel and/or R 2. Keep Bloomberg running 3. Go to Start-> Bloomberg -> API Environment Diagnostics 4. Click Start when the Bloomberg API Diagnostics window has loaded 5. If a “Login to wintrv…” message below then pops up, this occurs when Bloomberg isn’t open – it is highly recommended that you have Bloomberg running; you can proceed without it, but you may not be able to resolve some errors if you do so 6. Once the check is finished, you will get a ‘Diagnostics completed’ message 7. If the Repair button is available to press on the Bloomberg API Diagnostics window, it means it needs to run the repair and you should do so by clicking Repair (it should take a couple of minutes) 8. Once the check is done, and repair if necessary, the ideal state is all green ticks except for 2 yellow “!” for Dotnet Installation and Excel Throttle Interval only. Else, you can still run Excel or R-Studio and see if the Bloomberg-associated functionality is working.
install the Bloomberg package, and connect
install.packages(“Rblpapi”)
library (Rblpapi)
blpConnect()
get the Bloomberg data history for SPY US Equity - last 100 days - and plot it
x <- bdh(“SPY US Equity”, “PX_LAST”, start.date=Sys.Date()-100)
plot(x)
find out what other fields are available for prices
res <- fieldSearch(“price”)
res
get the Bloomberg data history for SPY US Equity - last 100 days - and plot it
x <- bdh(“SPY US Equity”, “OPEN”, start.date=Sys.Date()-100) plot(x)
Bloomberg from Excel
As above, if the Bloomberg/Excel add-in does not work, then repair (Steps 1-8).
Open an Excel Sheet, and type the following into a cell:
Historical prices: BDH(“F US Equity”, “PX_LAST”, “16/11/2000”, “15/11/2016”); this will give you the last traded price (PX_LAST) for ’F US Equity (Ford Motor Company) from 16/11/2000 to 15/11/2016. The first parameter must be the Bloomberg stock code.
For DMU students, this shows how to get data from Bloomberg into Excel. Also for DMU students, this shows how to use Bloomberg.
Lab 9 – API: Getting data from Refinitiv using R script.
Uploading data from Refinitiv into R
There is a big community of developers and users for both R and Refinitiv. Students can visit the forums and ask questions to fix their codes. We will install the eikonapir package; more information about this package can be found at:
Activity 1. Type APPKEY in the Eikon/Refinitiv search box.
Activity 2. Type your name, tick all check the boxes, and click on Register New App.
Activity 3. Read the Term and Conditions. Users/students must not share your App Key for Eikon/Refinitiv.
Activity 4. Copy your App Key using right-click with your mouse.
Activity 5. Paste the App key in the following code in R. You must open RStudio and write the following code within a Rscript
install.packages(“devtools”)
library(devtools)
install_github(“ahmedmohamedali/eikonapir”)
library(eikonapir)
eikonapir:: set_proxy_port(9000L)
eikonapir:: set_app_id(“Type your app key here”)
result <- get_symbology (list(“MSFT.O”, “GOOG.O”, “IBM.N”), “RIC”, list(“ISIN”),
raw_output=FALSE, debug=FALSE)
print(result)
Activity 6. Run the code line by line using ctrl+enter (command +enter for MAC).
Users need to install packages only the first time and update the packages from time to time. Users must open the libraries in line 3 and 5 (devtools and eikonapir) every time they use this rutine. Look carefully at each line and ask questions to your tutor if required.
Activity 7. Making a reference list of assets’ identifiers in a dataframe.
You can use this to find identifiers for datasets you are searching.
This is the outcome:
Activity 8. Get the last price, volume and lower price for IBM, Google, and Microsoft:
Activity 9. Get the number of employees and profit for IBM
Activity 10. Getting time series for MMM and III.L; this is 3M and 3i shares.
You can investigate these businesses in the search box of Refinitiv are.
Review the dataset for both shares with the command View in RStudio.
Activity 11. Download yearly GDP for Italy, and quarterly CPI for Australia.
Activity 12. Forecast five years (20 quarters) of CPI for Australia using moving averages and trailing moving averages (lecture for week 8).
You can inspect the file “lab9.R” available in bb. What is the extend of the inflation/deflation assuming the pandemic never happened?
Lab 10 – Exponential Forecasting
ACTIVITY 1 - Impact of the pandemic on visitors to the UK
Task 1- Find the publication ‘Overseas Travel and Tourism:2020’ on the ONS website and compare the release with the ‘Travel Trends in 2019’. What is the most popular reason to visit the UK? And why the trend change abruptly in 2020?
Task 2 - Search the ‘overseas visitors to the UK’ in Refinitiv; alternatively, you can find the mnemotechnic ‘aGBTOURARR/A’
Task 3 – Review the previous lab 9; using APPKEY in Refinitiv and the library eikonapir in R, get the time series for ‘aGBTOURARR/A’ since the year 2000.
Task 4 – Performe some data management, convert aGBTOURARR/A to a numeric format (if the format is ‘character’) and set the series as a data frame in R.
Task 5 – Open the library ‘forecast’ and ‘zoo’; what are these libraries for? Type ‘?forecast’ and ‘?zoo’ in the console without the quotes.
Task 6 – Set the dataset as a timeseries and plot the data.
Task 7 - perform double differencing on the data and plot the results. What is the effect on the data? Plot the double-differenced data.
Task 8 – Perform a partition of the data with a validation period equal to 36 months.
Task 9 - Perform a simple exponential forecast with additive errors and nothing for the trend and the seasonal component. Plot the results and compute the indicators of accuracy.
Task 10 – repeat the procedure, this time do not use the double-differenced series, use the original data set and calculate the best Holt’s specification (Explain the Holt’s method discussed during the lecture). Show the accuracy measures and plot the forecasts.
Forecast with double-differencing
Forecast with the original data
What is the best forecasting technique for this data? Double-differencing or forecast with the original data?
ACTIVITY 2 - Forecasting Department store sales; CH5, problem 5, p110-112.
The figure above is a time plot of the seasonally adjusted pre-September-11 Air series. Which of the following smoothing methods would be adequate for forecasting this series?
Naive forecasts
Moving average (with what window width?)
Simple exponential smoothing
Double exponential smoothing
Holt-Winter’s exponential smoothing
Note that the seasonally-adjusted series still contains a trend, and hence double exponential smoothing is needed.
Lab 11 – MCQs assessment
MCQs, weight 20%, deadline Dec 6, 2023 during the Lab sessions. Group 1: 11-12 noon, Group 2: 2-3 PM. The assessment for group 2 is from 2-3 PM to accomodate a guest speaking session.