-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDownloadingDataDemonstration.R
More file actions
393 lines (283 loc) · 10.3 KB
/
DownloadingDataDemonstration.R
File metadata and controls
393 lines (283 loc) · 10.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
#####################################################################
# Project: Downloading Data using R
# Author(s): Monroe Gamble
# Last revision: 11/04/2019
# This script demonstrates how to download data from a variety of sources using R
#####################################################################
#set workind Driectory -----------------------------------------
setwd('***REPLACE W/ YOUR DIRECTORY***/DownloadingDataR')
# Install Packages -----------------------------------------
# Pro-tip: Ctrl + click to open file
source('Supplements/Setup.R') #SETUP FILE NOT INCLUDED. Install Packages below.#
# Load Libraries -----------------------------------------
library(tidyverse)
###### Haver Example ###############################
library(Haver)
# Use the documentation
# ?Haver
# Haver US GDP Data, Core PCE & WTI ---------------------------------------------------------------------
# GDPA@USECON Trade-weighted major currencies index (Mar 1973=100)
# JCXFEBM@USECON Core Personal Consumption Expenditures (PCE)
# PZTEX@USECON West Texas intermediate, Cushing (CME Group)
# Set start and end dates
haver_start <- as.Date('01/31/1990', format = "%m/%d/%Y")
haver_end <- Sys.Date() #Today's Date
# Step 1. Just Read it in ----------------------------------------------
# Quarterly GDP
haver.data(codes = 'USECON:gdp', start = haver_start, end = haver_end,
freq = 'q', rtype = 'data.frame' , eop.dates = TRUE) #%>% #data is unwiedly!!!
# head()
# tail(10)
# Pro-tip: Autoformat Ctrl+Shift+A
# Step 2. Assignment Operator ----------------------------------------------
# Store Data Frame as Tibble
GDP <-
haver.data(
codes = 'USECON:gdp',
start = haver_start,
end = haver_end,
freq = 'q',
rtype = 'data.frame' ,
eop.dates = TRUE
)
GDP
#Head for first 6 rows / tail for last few
GDP %>% head()
GDP %>% tail()
# Convert data to tibble - "modern data.frame"
GDP %>% as_tibble()
# Fix rows
GDP %>% rownames_to_column("Date") %>% as_tibble()
#Pro-tip: Pipe-it up!!! (%>%) https://www.datacamp.com/community/tutorials/pipe-r-tutorial
# https://www.youtube.com/watch?v=e66pZFg3j_8
# Step 3. Downloading multiple variables ----------------------------------------------
haver.data(
codes = c('USECON:gdp', 'USECON:JCXFEBM'),
start = haver_start,
end = haver_end,
freq = 'q',
rtype = 'data.frame' ,
eop.dates = TRUE
) %>%
rownames_to_column("Date") %>%
as_tibble()
#Put it in a list: GDP, PCE, WTI
var_list <- c('USECON:gdp', 'USECON:JCXFEBM', 'USECON:PZTEX') # Not case sensitive
haver.data(
codes = var_list,
start = haver_start,
end = haver_end,
freq = 'q',
rtype = 'data.frame' ,
eop.dates = TRUE
) %>%
rownames_to_column("Date") %>%
as_tibble()
# Pro-tip: If you do it over and over CREATE A FUNCITON!!!
fix_rows <-
function(x) {
x %>%
rownames_to_column("Date") %>%
as_tibble()
}
# Download Data using function to fix rows
haver.data(
codes = var_list,
start = haver_start,
end = haver_end,
freq = 'q',
rtype = 'data.frame' ,
eop.dates = TRUE
) %>%
fix_rows()
# Add data pull check to function
fix_rows <-
function(x) {
data <-
x %>%
rownames_to_column("Date") %>%
as_tibble()
if (nrow(x) == 0) {
stop(paste("Haver pull for didn't return any data."), call.=FALSE)
} else {
cat("Pulled Haver data.")
}
return(data) # Tell function to return data
}
# Download data using function to fix rows & check data
haver.data(
codes = var_list,
start = haver_start,
end = haver_end,
freq = 'q',
rtype = 'data.frame' ,
eop.dates = TRUE
) %>%
fix_rows()
#Don't forget to store data
data <-
haver.data(
codes = var_list,
start = haver_start,
end = haver_end,
freq = 'q',
rtype = 'data.frame' ,
eop.dates = TRUE
) %>%
fix_rows()
# Clean environment
rm(GDP)
##### Exporting & Importing Tabular Data ######################
library(readr)
# Export / Save Tabular Data ---------------------------------------
# dir.create("data")
# unlink("data", recursive = T)
# Save CSV
write_csv(data, "GDP_PCE_WTI.csv")
# Save TSV
write_tsv(data, "GDP_PCE_WTI.tsv")
# Save TXT (write csv can be used to create .txt file)
write_csv(data, "GDP_PCE_WTI.txt")
# Save as Rdata file (Large files)
write_rds(data, "GDP_PCE_WTI.Rds")
# saves in current directory
getwd()
# List files in directory
list.files()
# Delete file
unlink("GDP_PCE_WTI.Rds")
# Delete mutliple files
file.remove("GDP_PCE_WTI.tsv", "GDP_PCE_WTI.txt")
# List files in directory
list.files()
# Save Delimitted file
write_delim(data, "GDP_PCE_WTI_DELIM.txt", delim = " ") #space
# Append - Same file Name Overwrties file, specifying append adds to file
write_delim(data, "GDP_PCE_WTI_DELIM.txt", delim = "@@", append = T)
# Overwite file
write_delim(data, "GDP_PCE_WTI_DELIM.txt", delim = "/")
# Import / Load Data Tabular Data ---------------------------------------
# wipes everything
rm(list = ls())
# Load CSV
read_csv("GDP_PCE_WTI.csv")
# Load Delimited
read_delim("GDP_PCE_WTI_DELIM.txt", delim = "/")
# Don't forget to store data
data <- read_csv("GDP_PCE_WTI.csv")
data
###### FRED ###############################
library(fredr)
#SP500 S&P 500 (https://fred.stlouisfed.org/series/SP500)
#DCOILWTICO Crude Oil Prices: West Texas Intermediate (WTI) - Cushing, Oklahoma
# Download S&P 500 data
sp500 <-
fredr(
series_id = 'SP500',
)
#Requires Fed Key
source("Source/FredKey.R")
sp500 <-
fredr(
series_id = 'SP500',
)
read.csv("FRED_Data.xlsx")
ggplot(sp500, aes(x=date, y=value)) +
geom_line() +
theme_minimal()
# Download WTI
WTI <-
fredr(
series_id = 'DCOILWTICO',
)
#Pro-tip: FRED data download defaults to a tibble
# # NBER Recessions
# fredr(
# series_id = 'USRECQ',
# ) %>% tail(40)
###### Plotly ###############################
library(plotly)
plot_ly(sp500, x = ~date, y = ~value, type = 'scatter', mode = 'lines')
##### Exporting & Importing Excel Data ######################
library(readxl) # Read Files
library(xlsx) # Export Files (not part of tidyverse)
# Export / Save Excel ------------------------------------------------
write.xlsx(sp500, "sp500.xlsx", row.names = FALSE)
# Pass it a data frame
sp500_df <- sp500 %>% as.data.frame()
# Save Excel file using 'xlsx' package
write.xlsx(sp500_df, "FRED_Data.xlsx", row.names = FALSE, sheetName = "sp500")
# Convert WTI to data frame
WTI_df <- WTI %>% as.data.frame()
# Specifying Append adds a sheet to existing file
write.xlsx(WTI_df, "FRED_Data.xlsx", row.names = FALSE, append = T, sheetName = "WTI")
# Clean environment
rm(sp500, sp500_df, WTI, WTI_df)
# Import / Load Excel Data -----------------------------------------------------
# Load by sheet name or index (multiple sheets)
sp500 <- read.xlsx("FRED_Data.xlsx", sheetName = "sp500") %>%
as_tibble() #Loads at dataframe, convert to tibble
sp500
# Load by Index
WTI <- read.xlsx("FRED_Data.xlsx", sheetIndex = 2) %>%
as_tibble() #Loads at dataframe, convert to tibble
WTI
# Load using readxl (tidyverse)
read_excel("FRED_Data.xlsx", sheet = 1) #Loads as tibble
read_xlsx("FRED_Data.xlsx", sheet = 1) #Loads as tibble
##### Load Data from the web
# SURVEY OF PROFESSIONAL FORECASTERS (SPF) -------------------------------------
dispersion1 <- 'https://www.philadelphiafed.org/-/media/research-and-data/real-time-center/survey-of-professional-forecasters/data-files/files/dispersion_corecpi.xlsx?la=en'
download.file(dispersion1, destfile = "SPF_Forecast.xlsx", mode = 'wb')
SPF_dispersion <-
readxl::read_xlsx('SPF_Forecast.xlsx', skip = 9, na = '#N/A')
SPF_dispersion
# Advanced: Downloading multiple sheets ----------------------------------------------------------------
# SPF Dispersion 1
dispersion1 <-
'https://www.philadelphiafed.org:443/-/media/research-and-data/real-time-center/survey-of-professional-forecasters/historical-data/dispersion_1.xlsx'
# SPF Dispersion 2
dispersion2 <-
'https://www.philadelphiafed.org:443/-/media/research-and-data/real-time-center/survey-of-professional-forecasters/historical-data/dispersion_2.xlsx'
# Save SPF Data
lapply(list(dispersion1, dispersion2), function(x) {
download.file(x, destfile = paste0(sub(".*/(.*.xlsx).*", "\\1", x)), mode = 'wb')})
# Retrieve Sheets
sheetnames <- list('PCE', 'COREPCE', 'UNEMP', 'RGDP')
disp1 <-
lapply(sheetnames[1:3], function(x){read_xlsx('dispersion_1.xlsx', sheet = x, skip = 9, na = '#N/A')}) %>%
as.data.frame()
disp2 <- read_xlsx('dispersion_2.xlsx', sheet = sheetnames[[4]], skip = 9, na = '#N/A') %>%
as.data.frame()
# Create excel workbook
write.xlsx(disp1, "dispersion_merge2.xlsx", row.names = FALSE, append = T, sheetName = "dispersion 1")
# Add Second Sheet
write.xlsx(disp2, "dispersion_merge2.xlsx", row.names = FALSE, append = T, sheetName = "dispersion 2")
###### Quantmod ############################
library(quantmod)
# Load Market Data -----------------------------------------
getSymbols("AMZN")
AMZN_df <- data.frame(AMZN) %>%
rownames_to_column() %>%
rename(Date = rowname) %>%
mutate(Date = as.Date(Date))
getSymbols("GOOGL")
GOOGL_df <- data.frame(GOOGL) %>%
rownames_to_column() %>%
rename(Date = rowname) %>%
mutate(Date = as.Date(Date))
getSymbols("^GSPC")
sp500_df <- data.frame(GSPC) %>%
rownames_to_column() %>%
rename(Date = rowname) %>%
mutate(Date = as.Date(Date))
# Plot using Plotly
plot_ly(sp500_df, x = ~Date, y = ~GSPC.Close, type = 'scatter', mode = 'lines', name = 'S&P 500') %>%
add_trace(data = AMZN_df, y = ~AMZN.Close, name = "AMZN") %>%
add_trace(data = GOOGL_df, y = ~GOOGL.Close, name = "GOOGL") %>%
layout(
yaxis = list(title = "Dollars (US)",
hoverformat = '$,f')
)
#########################################################################
# Data Import Cheatsheet: https://resources.rstudio.com/rstudio-cheatsheets/data-import-cheat-sheet