· 6 years ago · Nov 25, 2019, 07:08 PM
1### Install packages if needed, then load them quietly
2packages <- c("fredr", "forecast", "ggplot2", "dplyr", "magrittr", "tsibble")
3new.packages <- packages[!(packages %in% installed.packages()[,"Package"])]
4if(length(new.packages)) install.packages(new.packages, quiet = TRUE)
5invisible(lapply(packages, "library",
6 quietly = TRUE,
7 character.only = TRUE,
8 warn.conflicts = FALSE))
9
10### Edit "FRED_API_key.R" and add your personal API key to access the FRED database.
11### You may request an API key at: https://research.stlouisfed.org/useraccount/apikeys
12fredr_set_key("INSERT_YOUR_FRED_API_KEY_HERE")
13
14### What are the start/end dates you are interested in
15Start_Date = as.Date("1971-01-01")
16End_Date = as.Date("1985-01-01")
17
18### Fetch gold price data from FRED
19data <- as_tsibble(fredr(series_id = "GOLDAMGBD228NLBM",
20 frequency = "m",
21 observation_start = Start_Date,
22 observation_end = End_Date))
23
24Date <- as.Date(data %>% pull('date'))
25Values <- data %>% pull('value')
26
27Values.norm <- Values / Values[1]
28Values.gold <- data.frame(Date = Date, Values = Values.norm)
29
30### Fetch Wilshire 5000 stock price data from FRED
31data <- as_tsibble(fredr(series_id = "WILL5000INDFC",
32 frequency = "m",
33 observation_start = Start_Date,
34 observation_end = End_Date))
35
36Date <- as.Date(data %>% pull('date'))
37Values <- data %>% pull('value')
38
39# Normalize the data with respect to the start date
40Values.norm <- Values / Values[1]
41Values.stocks <- data.frame(Date = Date, Values = Values.norm)
42
43### Create a data frame for graphing
44Values.graph <- data.frame(Date = Values.gold$Date,
45 Gold = Values.gold$Values,
46 Stocks = Values.stocks$Values)
47
48### Graph performance of gold vs stocks
49P <- ggplot(data = Values.graph, mapping = aes(x = Date, y = Gold))
50P <- P + geom_line(data = Values.graph,
51 mapping = aes(x = Date, y = Gold),
52 size = 1.3, color="gold")
53P <- P + geom_line(data = Values.graph,
54 mapping = aes(x = Date, y = Stocks),
55 size = 1.3, color="darkred")
56P <- P + theme(legend.position = "right")
57P <- P + labs(title = paste("Gold prices vs Wilshire 5000 stock index relative to", Start_Date),
58 xlab = "Year",
59 ylab = "")
60P <- P + xlab("Year")
61P <- P + ylab("Percent")
62print(P)