# How to use the data.snb.ch API with R # Swiss National Bank, 2024 # ========================================================================================== # README # - Please read https://data.snb.ch/de/help_api # - Look through this R code and read the help for information on unknown R functions/packages. # - You can change the script as necessary # - Please only retrieve data if there really are new data available. # To find out if there are new data available, you can use the lastUpdate method or eTags. # See https://data.snb.ch/de/help_api # If excessive use of the data portal leads to any disruption, we reserve the right # to block the IP address of the user concerned. # COPYRIGHT, LIMITATION OF LIABILITY AND DATA PROTECTION # https://www.snb.ch/de/srv/disclaimer_liability # ========================================================================================== # load packages, please install if missing # ---------------------------------------- # install.packages("RCurl") # install.packages("jsonlite") library(RCurl) library(jsonlite) # Download Data # ------------- localDataFile <- "BSTA@SNB.MONA_B.BIL.AKT.FMI.GFG.csv" download.file("https://data.snb.ch/api/warehouse/cube/BSTA.SNB.MONA_B.BIL.AKT.FMI.GFG/data/csv/de?dimSel=KONSOLIDIERUNGSSTUFE(B),INLANDAUSLAND(T,I,A),WAEHRUNG(T,CHF,EUR),BANKENGRUPPE(A40)&fromDate=2023-05&toDate=2024-05", method="curl", destfile=localDataFile) # if it fails, check method parameter # Download Structure Descriptions # ------------------------------- localStrFile <- "BSTA@SNB.MONA_B.BIL.AKT.FMI.GFG.json" download.file("https://data.snb.ch/api/warehouse/cube/BSTA.SNB.MONA_B.BIL.AKT.FMI.GFG/dimensions/de", method="curl", destfile=localStrFile) # Load the downloaded files into R-Session # ---------------------------------------- rawData <- read.table(localDataFile, skip=3, header = TRUE, sep=";") strData <- fromJSON(paste(readLines(localStrFile, encoding = "UTF-8"), collapse="")) # Use the Data # ------------ head(rawData)