Skip to content

Instantly share code, notes, and snippets.

@capm
Last active August 29, 2015 14:10
Show Gist options
  • Save capm/e168461a83caa37eea52 to your computer and use it in GitHub Desktop.
Save capm/e168461a83caa37eea52 to your computer and use it in GitHub Desktop.
Functions for R
FX.HistData <- function(pair = "EURUSD", period = "day") {
##### Arguments verification Valid pairs to download
pairs.valid <- c("AUDJPY", "AUDUSD", "CHFJPY", "EURCHF", "EURGBP", "EURJPY", "EURUSD", "GBPCHF", "GBPJPY", "GBPUSD", "NZDUSD", "USDCAD", "USDCHF", "USDJPY", "XAGUSD", "XAUUSD")
# Valid download periods
period.valid <- c("day", "hour")
# Create set of warnings
error.string <- c()
# Check if it is a valid pair, if not store a warning
if (pair %in% pairs.valid){valid.pair = TRUE} else {
valid.pair = FALSE
error.string <- c(error.string, "Not a valid FX pair.")
}
# Check if it is a valid period, if not store a warning
if (period %in% period.valid){valid.period <- TRUE} else {
valid.period <- FALSE
error.string <- c(error.string, "Not a valid period")
}
##### Main algorithm If all conditions are true download data
if (valid.pair == TRUE && valid.period == TRUE) {
# Download link
urlFX<-paste('http://www.fxhistoricaldata.com/download/',pair,'?t=',period,sep = '')
# Temporal storage
tFile <- tempfile()
# Download zip file
download.file(urlFX,tFile, mode="wb")
# CSV file name
fxPair.csv <- unzip(tFile, list=TRUE)$Name[1]
#
unzip(tFile, fxPair.csv)
pair.data <- read.table(fxPair.csv, sep=",", header=T)
pair.data <- pair.data[,-3]
pair.data.h <- c('Ticker','Date','Open', 'Low', 'High', "Close")
names(pair.data) <- pair.data.h
pair.data$Date <- as.Date(as.character(pair.data$Date), format = "%Y%m%d")
pair.data <- xts(x = pair.data$Close, order.by = pair.data$Date)
names(pair.data) <- c(pair)
return(pair.data)
} else {
print(error.string)
}
}
getBVL <- function(ticker, date1 = Sys.Date() - 380, date2 = Sys.Date() - 10) {
# Format dates
date1 <- format(date1, "%Y%m%d")
date2 <- format(date2, "%Y%m%d")
# Define url with dates and ticker
urlPrices <- paste("http://www.bvl.com.pe/jsp/cotizacion.jsp?fec_inicio=", date1,
"&fec_fin=", date2, "&nemonico=", ticker, sep = "")
hPrice <- html(urlPrices)
# Extract and clean table
tPrice <- data.frame(hPrice %>% html_table())
# Remove faulty columns
tPrice <- tPrice[-1, c(-9, -10)]
names(tPrice) <- c("Date", "Open", "Close", "Max", "Min", "Average", "Ammount",
"Volume")
# Return table
return(tPrice)
}
GetBondCoupon <- function(bond.tickers){
temp.pattern <- '^[A-Z]+ ([^A-Z]+) [^ ]+$'
temp.coupons <- sub(temp.pattern, '\\1',bond.tickers)
unname(sapply(sub(' ', '+', temp.coupons), function(x) eval(parse(text=x))))
}
GetBondMaturity <- function(bond.ticker) {
temp.mat <- c()
for (i in 1:length(bond.ticker)) {
temp.len <- nchar(bond.ticker[i])
temp.date <- substr(bond.ticker, temp.len - 7, temp.len)
temp.mat <- c(temp.mat, as.Date(temp.date, "%m/%d/%y"))
}
return(as.Date(temp.mat, origin = "1970-1-1"))
}
# Filename: matlab_time.R
# Convert between MATLAB datenum values and R POSIXt time values.
#
# Author: Luke Miller Feb 20, 2011
###############################################################################
#Convert a numeric MATLAB datenum (days since 0000-1-1 00:00) to seconds in
#the Unix epoch (seconds since 1970-1-1 00:00). Specify a time zone if the
#input datenum is anything other than the GMT/UTC time zone.
matlab2POS = function(x, timez = "UTC") {
days = x - 719529 # 719529 = days from 1-1-0000 to 1-1-1970
secs = days * 86400 # 86400 seconds in a day
# This next string of functions is a complete disaster, but it works.
# It tries to outsmart R by converting the secs value to a POSIXct value
# in the UTC time zone, then converts that to a time/date string that
# should lose the time zone, and then it performs a second as.POSIXct()
# conversion on the time/date string to get a POSIXct value in the user's
# specified timezone. Time zones are a goddamned nightmare.
return(as.POSIXct(strftime(as.POSIXct(secs, origin = '1970-1-1',
tz = 'UTC'), format = '%Y-%m-%d %H:%M',
tz = 'UTC', usetz = FALSE), tz = timez))
}
###############################################################################
#Convert POSIXct, POSIXlt or 'seconds since 1970-1-1' to MATLAB datenum value.
#The conversion drops any time zone associated with the POSIXt value. It is the
#user's responsibility to keep track of time zones in MATLAB datenums.
#The constant 719529 in the function is the days from 0000-1-1 to 1970-1-1.
POSIXt2matlab = function(x) {
if (class(x)[1] == "POSIXlt"){
days = as.numeric(as.Date(x)) #extract days since 1970-1-1
frac.day = (((x$hour)*3600) + ((x$min)*60) + x$sec)/86400
datenum = 719529 + days + frac.day
datenum = 719529 + days + frac.day
} else if (class(x)[1] == "POSIXct"){
x = as.POSIXlt(x) #convert to POSIXlt class
days = as.numeric(as.Date(x)) #extract days since 1970-1-1
frac.day = (((x$hour)*3600) + ((x$min)*60) + x$sec)/86400
datenum = 719529 + days + frac.day
} else if (class(x)[1] == "numeric"){
days = x / 86400 #convert seconds to days
datenum = days + 719529
} else {
stop("Input cannot be coerced to POSIXlt or numeric value")
}
return(datenum)
}
#The output is a numeric vector of 'days since 0000-1-1 00:00'.
###############################################################################
#Convert POSIXct or POSIXlt objects to MATLAB datenum, in UTC time zone.
#All time stamps with non-GMT/UTC time zones will be first converted to the
#GMT/UTC time zone, then converted to MATLAB datenum value.
POSIXt2matlabUTC = function(x) {
if (class(x)[1] == "POSIXct") {
x = as.POSIXlt(x, tz = "UTC") #convert to UTC time zone
days = as.numeric(x) / 86400 #convert to days
datenum = days + 719529 #convert to MATLAB datenum
} else if (class(x)[1] == "POSIXlt") {
x = as.POSIXlt(x, tz = "UTC") #convert to UTC time zone
days = as.numeric(x) / 86400 #convert to days
datenum = days + 719529 #convert to MATLAB datenum
} else {stop("POSIXct or POSIXlt object required for input")}
return(datenum)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment