R/saveInstruments.R

###############################################################################
# R (http://r-project.org/) Instrument Class Model
#
# Copyright (c) 2009-2012
# Peter Carl, Dirk Eddelbuettel, Jeffrey Ryan, 
# Joshua Ulrich, Brian G. Peterson, and Garrett See
#
# This library is distributed under the terms of the GNU Public License (GPL)
# for full details see the file COPYING
#
# $Id$
#
###############################################################################


#' Save and Load all instrument definitions
#' 
#' Saves (loads) the .instrument environment to (from) disk.
#' 
#' After you have defined some instruments, you can use \code{saveInstruments}
#' to save the entire .instrument environment to disk.
#'
#' \code{loadInstruments} will read a file that contains instruments and add 
#' those instrument definitions to your .instrument environment.  
#' \code{reloadInstruments} will remove all instruments in the current 
#' .instrument environment before loading instruments from disk.
#' 
#' The \code{file_name} should have a file extension of \dQuote{RData}, 
#' \dQuote{rda}, \dQuote{R}, or \dQuote{txt}.  If the \code{file_name} does not
#' end with one of those, \dQuote{.RData} will be appended to the 
#' \code{file_name}
#' 
#' If the file extension is \dQuote{R} or \dQuote{txt}, \code{saveInstruments}
#' will create a text file of \R code that can be \code{\link{source}}d to 
#' load instruments back into the .instrument environment.
#' 
#' @aliases saveInstruments loadInstruments
#' @param file_name name of file. e.g. \dQuote{MyInstruments.RData}.  
#' As an experimental feature, a \code{list} or \code{environment} can be passed 
#' to \code{file_name}.
#' @param dir Directory of file (defaults to current working directory. ie. "")
#' @param compress argument passed to \code{\link{save}}, default is "gzip"
#' @return Called for side-effect
#' @author Garrett See
#' @seealso save, load load.instrument define_stocks, define_futures,
#' define_options (option_series.yahoo)
#' @examples
#' \dontrun{
#' stock("SPY", currency("USD"), 1)
#' tmpdir <- tempdir()
#' saveInstruments("MyInstruments.RData", dir=tmpdir)
#' rm_instruments(keep.currencies=FALSE)
#' loadInstruments("MyInstruments.RData", dir=tmpdir)
#' # write .R file that can be sourced
#' saveInstruments("MyInstruments.R", dir=tmpdir)
#' rm_instruments(keep.currencies=FALSE)
#' loadInstruments("MyInstruments.R", dir=tmpdir)
#' #source(file=paste(tmpdir, "MyInstruments.R", sep="/")) # same
#' unlink(tmpdir, recursive=TRUE)     
#' }
#' @export 
#' @rdname saveInstruments
saveInstruments <- function(file_name="MyInstruments", dir="", compress="gzip") {
	if (!is.null(dir) && !dir == "" && substr(dir,nchar(dir),nchar(dir)) != "/")
		dir <- paste(dir,"/",sep="")
    ssfn <- strsplit(file_name, "\\.")[[1]]
	extension <- if (tolower(tail(ssfn, 1)) %in% c('rda', 'rdata', 'r', 'txt')) {
        file_name <- paste(ssfn[1:(length(ssfn)-1)], collapse=".")
        tail(ssfn, 1)
    } else "RData"
    file.name <- paste(dir, file_name, ".", extension, sep="")
	# if extension is "R", "r", or "txt" create a file that can be sourced
    if (tolower(extension) %in% c("r", "txt")) {
        cat("#auto-generated by FinancialInstrument:::saveInstruments\n\n",
            "require(FinancialInstrument)\n\n", file=file.name)
        for (s in ls_instruments()) {
            sink(file.name, append=TRUE)
            cat('assign("', s, '", pos=FinancialInstrument:::.instrument, ', 
                'value=\n', sep="", append=TRUE)
            dput(getInstrument(s))
            cat(")\n\n", append=TRUE)
            sink()
            #system(paste("cat", file.name)) #for debugging    
        }
    } else save(.instrument, file = file.name, compress=compress)	
}


#' @export
#' @rdname saveInstruments
loadInstruments <-function(file_name="MyInstruments", dir="") {
    if (is.environment(file_name) || is.list(file_name)) {
        ilist <- as.list(file_name)
        if (!all(vapply(ilist, function(x) length(x[["primary_id"]]) == 1L, 
                        TRUE))) {
            stop("all instruments must have exactly one primary_id")
        }
        for (i in seq_along(ilist)) {
            assign(ilist[[i]][["primary_id"]], ilist[[i]],
                   pos=.instrument)
        }
        return(invisible(NULL))
	}
    if (!is.null(dir) && !dir == "" && substr(dir,nchar(dir),nchar(dir)) != "/")
		dir <- paste(dir,"/",sep="")
    ssfn <- strsplit(file_name, "\\.")[[1]]
    extension <- if (tolower(tail(ssfn, 1)) %in% c('rda', 'rdata', 'r', 'txt')) {
        file_name <- paste(ssfn[1:(length(ssfn)-1)], collapse=".")
        tail(ssfn, 1)
    } else "RData"
    file.name <- paste(dir, file_name, ".", extension, sep="")
    if (tolower(extension) %in% c("r", "txt")) {
        if (substr(readLines(file.name, 1L), 1, 5) != "#auto") {
            warning(paste(file.name, "was not created by 'saveInstruments'"))
        }
        source(file.name)
    } else {
        tmpenv <- new.env()
        load(paste(dir,file_name,".",extension,sep=""),envir=tmpenv)
        il <- ls(tmpenv$.instrument, all.names=TRUE)
        for (i in il) {
             assign(i, tmpenv$.instrument[[i]], 
                    pos=.instrument, inherits=FALSE)
        }
    }
}


#' @export
#' @rdname saveInstruments
reloadInstruments <- function(file_name="MyInstruments", dir="") {
    rm_instruments(keep.currencies=FALSE)
    loadInstruments(file_name=file_name, dir=dir)
}
braverock/FinancialInstrument documentation built on May 13, 2019, 2:32 a.m.