[Blotter-commits] r727 - in pkg/FinancialInstrument: . R man sandbox

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Thu Aug 11 21:11:55 CEST 2011


Author: gsee
Date: 2011-08-11 21:11:53 +0200 (Thu, 11 Aug 2011)
New Revision: 727

Added:
   pkg/FinancialInstrument/sandbox/DJIA.index.R
Modified:
   pkg/FinancialInstrument/DESCRIPTION
   pkg/FinancialInstrument/NAMESPACE
   pkg/FinancialInstrument/R/buildSpread.R
   pkg/FinancialInstrument/R/load.instruments.R
   pkg/FinancialInstrument/R/synthetic.R
   pkg/FinancialInstrument/man/buildSpread.Rd
   pkg/FinancialInstrument/man/synthetic.instrument.Rd
Log:
- synthetic and buildSpread now return primary_id (instead of being invisible)
- patched buildSpread bug where stocks AT&T (T) and Ford (F) were being treated like TRUE and FALSE 
- in buildSpread, multiplier is now inverse of divisor (instead of using multiplier as divisor)
- buildBasket is now an alias for buildSpread
- formatted warning messages (added some spaces) in load.instruments
- added DJIA.index to sandbox. Simple example of one way to define/build a price-weighted index.
- bump version


Modified: pkg/FinancialInstrument/DESCRIPTION
===================================================================
--- pkg/FinancialInstrument/DESCRIPTION	2011-08-10 20:45:51 UTC (rev 726)
+++ pkg/FinancialInstrument/DESCRIPTION	2011-08-11 19:11:53 UTC (rev 727)
@@ -11,7 +11,7 @@
     meta-data and relationships. Provides support for
     multi-asset class and multi-currency portfolios.  Still
     in heavy development.
-Version: 0.4.3
+Version: 0.4.4
 URL: https://r-forge.r-project.org/projects/blotter/
 Date: $Date$
 Depends:

Modified: pkg/FinancialInstrument/NAMESPACE
===================================================================
--- pkg/FinancialInstrument/NAMESPACE	2011-08-10 20:45:51 UTC (rev 726)
+++ pkg/FinancialInstrument/NAMESPACE	2011-08-11 19:11:53 UTC (rev 727)
@@ -1,5 +1,6 @@
 export(bond)
 export(bond_series)
+export(buildBasket)
 export(buildHierarchy)
 export(buildRatio)
 export(build_series_symbols)

Modified: pkg/FinancialInstrument/R/buildSpread.R
===================================================================
--- pkg/FinancialInstrument/R/buildSpread.R	2011-08-10 20:45:51 UTC (rev 726)
+++ pkg/FinancialInstrument/R/buildSpread.R	2011-08-11 19:11:53 UTC (rev 727)
@@ -9,6 +9,7 @@
 #' However, the returned series will be univariate. It does not build Bid Ask Mid data 
 #' like fn_SpreadBuilder does.
 #'
+#' TODO: allow for multiplier (divisor) that is a vector.
 #' @param spread_id The name of the instrument that contains members and memberratio 
 #' @param Dates date range to subset on, will be used for \code{\link[quantmod]{getSymbols}} 
 #' if the instrument is not available via \code{\link{get}}
@@ -33,7 +34,9 @@
 #' spread("SPYDIA", "USD", c("SPY","DIA"),c(1,-1)) #define it.
 #' buildSpread('SPYDIA') #build it.
 #' head(SPYDIA)
+#'
 #' }
+#' @rdname buildSpread
 #' @export
 buildSpread <- function(spread_id, Dates = NULL, onelot=TRUE, prefer = NULL, auto.assign=TRUE, env=.GlobalEnv) #overwrite=FALSE
 {
@@ -48,7 +51,7 @@
     #if (!inherits(try(get(spread_id),silent=TRUE), "try-error") && overwrite==FALSE) #Doesn't work..returns vector of FALSE
 	#stop(paste(spread_instr,' price series already exists. Try again with overwrite=TRUE if you wish to replace it.')) 
 
-    spread_currency <- spread_instr$currency    
+    spread_currency <- spread_instr$currency 
     spread_mult <- as.numeric(spread_instr$multiplier)
     if (is.null(spread_mult) || spread_mult == 0) spread_mult <- 1
     spread_tick <- spread_instr$tick_size
@@ -66,10 +69,10 @@
         instr_currency <- instr$currency
         instr_mult <- as.numeric(instr$multiplier)
         instr_ratio <- spread_instr$memberratio[i]
-        instr_prices <- try(get(as.character(spread_instr$members[i],envir=.GlobalEnv)),silent=TRUE)
+        instr_prices <- try(get(as.character(spread_instr$members[i]),envir=.GlobalEnv),silent=TRUE)
         # If we were able to find instr_prices in .GlobalEnv, check to make sure there is data between from and to.
         #if we couldn't find it in .GlobalEnv or there's no data between from and to, getSymbols
-        if (inherits(instr_prices, "try-error") || (!is.null(Dates) && length(instr_prices[Dates]) == 0)) {
+        if (inherits(instr_prices, "try-error") || length(instr_prices) < 2 || (!is.null(Dates) && length(instr_prices[Dates]) == 0)) {
             if (is.null(Dates)) {
                 warning(paste(spread_instr$members[i],"not found in .GlobalEnv, and no Dates supplied. Trying getSymbols defaults.") )
                 instr_prices <- getSymbols(as.character(spread_instr$members[i]),auto.assign=FALSE)
@@ -101,7 +104,7 @@
 	        pref='Price'
           } else pref=colnames(instr_prices)[1]
         } else pref=prefer
-        if (ncol(instr_prices > 1)) instr_prices <- getPrice(instr_prices,prefer=pref)
+        if (!is.logical(instr_prices) || ncol(instr_prices) > 1) instr_prices <- getPrice(instr_prices,prefer=pref)
         if (instr$currency != spread_currency) 
             instr_prices <- redenominate(instr_prices,spread_currency,instr$currency)
         instr_norm <- instr_prices * instr_mult * instr_ratio
@@ -124,15 +127,20 @@
         spreadlevel = spreadlevel/abs(spread_instr$memberratio[1]) #abs() takes care of things like a crack spread which is -3:2:1.
     colnames(spreadlevel) <- paste(spread_id,pref,sep='.')
     #Divide by multiplier and round according to tick_size of spread_instr
-    if (is.null(spread_tick) || spread_tick == 0) ret <- spreadlevel/spread_mult
-    else ret <- round((spreadlevel / spread_mult) / spread_tick, spread_tick) * spread_tick
+    if (is.null(spread_tick) || spread_tick == 0) ret <- spreadlevel*spread_mult
+    else ret <- round((spreadlevel * spread_mult) / spread_tick, spread_tick) * spread_tick
     if (auto.assign) {
         assign(spread_id, ret, pos=env)
         ret <- spread_id
-    } else 
+    }
     ret
 }
 
+#' @rdname buildSpread
+#' @export
+buildBasket <- buildSpread
+
+
 #' Calculate prices of a spread from 2 instruments.
 #'
 #' Given 2 products, calculate spread values for as many columns as practicable 

Modified: pkg/FinancialInstrument/R/load.instruments.R
===================================================================
--- pkg/FinancialInstrument/R/load.instruments.R	2011-08-10 20:45:51 UTC (rev 726)
+++ pkg/FinancialInstrument/R/load.instruments.R	2011-08-11 19:11:53 UTC (rev 727)
@@ -50,7 +50,7 @@
         if (file.exists(file)){
             filedata<-read.csv(file,stringsAsFactors=FALSE, ...=...)
         } else {
-            stop("The specified file",file,"does not seem to exist, maybe specify the full path?")
+            stop("The specified file ",file," does not seem to exist, maybe specify the full path?")
         }        
     } else {
         filedata<-metadata
@@ -65,7 +65,7 @@
         set_primary<-FALSE
     }
     if(!any(grepl('type',colnames(filedata)))) {
-        warning("metadata does not appear to contain instrument type, using",default_type,". This may produce incorrect valuations.")
+        warning("metadata does not appear to contain instrument type, using ",default_type,". This may produce incorrect valuations.")
         filedata$type<-rep(default_type,nrow(filedata))
     }
     dotargs<-list('...')
@@ -115,7 +115,7 @@
 				try(do.call("instrument",arg))
 			}
         } else {   
-            warning(filedata[rn,id_col],"already exists in the .instrument environment")
+            warning(filedata[rn,id_col]," already exists in the .instrument environment")
         } # end instrument check
     } # end loop on rows
 }

Modified: pkg/FinancialInstrument/R/synthetic.R
===================================================================
--- pkg/FinancialInstrument/R/synthetic.R	2011-08-10 20:45:51 UTC (rev 726)
+++ pkg/FinancialInstrument/R/synthetic.R	2011-08-11 19:11:53 UTC (rev 727)
@@ -15,7 +15,7 @@
 #' @rdname synthetic.instrument
 synthetic <- function(primary_id , currency , multiplier=1, identifiers = NULL, ..., members=NULL, type=c("synthetic", "instrument"))
 {
-    synthetic_temp = instrument(primary_id=primary_id , currency=currency , multiplier=multiplier , identifiers = identifiers, ...=..., type=type, members=members, assign_i=TRUE )    
+    instrument(primary_id=primary_id , currency=currency , multiplier=multiplier , identifiers = identifiers, ...=..., type=type, members=members, assign_i=TRUE )    
 }
 
 #' constructors for synthetic instruments
@@ -104,7 +104,7 @@
 #' @param members vector of primary_ids of member instruments
 #' @param memberratio vector of weights for each leg. negative numbers for selling.
 #' @param \dots any other passthrough parameters
-#' @param multiplier multiplier of the spread
+#' @param multiplier multiplier of the spread (1 / divisor for price weighted baskets)
 #' @param tick_size minimum price change of the spread
 #' @param identifiers identifiers
 #' @param type type of instrument; wrappers do not require this.

Modified: pkg/FinancialInstrument/man/buildSpread.Rd
===================================================================
--- pkg/FinancialInstrument/man/buildSpread.Rd	2011-08-10 20:45:51 UTC (rev 726)
+++ pkg/FinancialInstrument/man/buildSpread.Rd	2011-08-11 19:11:53 UTC (rev 727)
@@ -1,9 +1,13 @@
 \name{buildSpread}
+\alias{buildBasket}
 \alias{buildSpread}
 \title{construct a price/level series for pre-defined multi-leg spread instrument}
 \usage{
   buildSpread(spread_id, Dates = NULL, onelot = TRUE,
   prefer = NULL, auto.assign = TRUE, env = .GlobalEnv)
+
+  buildBasket(spread_id, Dates = NULL, onelot = TRUE,
+  prefer = NULL, auto.assign = TRUE, env = .GlobalEnv)
 }
 \arguments{
   \item{spread_id}{The name of the instrument that contains
@@ -41,6 +45,8 @@
   calendars, butterflies, condors, etc. However, the
   returned series will be univariate. It does not build Bid
   Ask Mid data like fn_SpreadBuilder does.
+
+  TODO: allow for multiplier (divisor) that is a vector.
 }
 \note{
   this could also be used to build a basket or a strip by
@@ -56,6 +62,7 @@
 spread("SPYDIA", "USD", c("SPY","DIA"),c(1,-1)) #define it.
 buildSpread('SPYDIA') #build it.
 head(SPYDIA)
+
 }
 }
 \author{

Modified: pkg/FinancialInstrument/man/synthetic.instrument.Rd
===================================================================
--- pkg/FinancialInstrument/man/synthetic.instrument.Rd	2011-08-10 20:45:51 UTC (rev 726)
+++ pkg/FinancialInstrument/man/synthetic.instrument.Rd	2011-08-11 19:11:53 UTC (rev 727)
@@ -41,7 +41,8 @@
 
   \item{\dots}{any other passthrough parameters}
 
-  \item{multiplier}{multiplier of the spread}
+  \item{multiplier}{multiplier of the spread (1 / divisor
+  for price weighted baskets)}
 
   \item{tick_size}{minimum price change of the spread}
 

Added: pkg/FinancialInstrument/sandbox/DJIA.index.R
===================================================================
--- pkg/FinancialInstrument/sandbox/DJIA.index.R	                        (rev 0)
+++ pkg/FinancialInstrument/sandbox/DJIA.index.R	2011-08-11 19:11:53 UTC (rev 727)
@@ -0,0 +1,34 @@
+#' get the components of the Dow Jones Industrial Average
+#'
+#' download a data.frame of the 30 Dow Jones components.
+#' @return 30 by 5 data.frame with columns \sQuote{Symbol}, \sQuote{Name}, \sQuote{Last.Trade}, \sQuote{Change}, \sQuote{Volume}
+#' @references \url{'http://finance.yahoo.com/q/cp?s=^DJI+Components'}
+DJIcomponents <- function() {
+    if (!("package:XML" %in% search() || require("XML",quietly=TRUE))) {
+        stop("Please install the XML package before using this function.")
+    }
+    djicomp <- readHTMLTable('http://finance.yahoo.com/q/cp?s=^DJI+Components')
+    data.frame(djicomp[[10]])
+}
+
+#' fetch the current divisor for the Dow Jones Industrial Average from Barrons
+#' @return numeric
+#' @references \url{'http://online.barrons.com/mdc/public/page/9_3022-djiahourly.html?mod=mdc_h_usshl'}
+dow.divisor <- function() {
+    wp <- readLines('http://online.barrons.com/mdc/public/page/9_3022-djiahourly.html?mod=mdc_h_usshl')
+    #wp2 <- wp[grep("30 INDUSTRIALS:",wp)]
+    #as.numeric(gsub(')</td>','',strsplit(wp2, 'divisor: ')[[1]][2]))
+    as.numeric(gsub(')</td>','',strsplit(wp[grep("30 INDUSTRIALS:",wp)], 'divisor: ')[[1]][2]))
+}
+
+currency('USD')
+DJIA.members <- sapply(DJIcomponents()$Symbol, stock, currency="USD", member.of='DJIA')
+getSymbols(DJIA.members) # <-- getting data first is not required, but may be preferable
+synthetic.instrument("DJIA","USD", members=DJIA.members, memberratio=rep(1,length(DJIA.members)), 
+                     multiplier=1/dow.divisor(), tick_size=0.01, description='Dow Jones Industrial Average')
+buildBasket('DJIA') #theoretical index
+tail(DJIA)
+
+getSymbols("^DJI") #acual index
+tail(DJI)
+



More information about the Blotter-commits mailing list