[Blotter-commits] r1503 - in pkg: blotter/R quantstrat/R
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Fri Sep 13 23:37:20 CEST 2013
Author: braverock
Date: 2013-09-13 23:37:20 +0200 (Fri, 13 Sep 2013)
New Revision: 1503
Modified:
pkg/blotter/R/calcPortfWgt.R
pkg/blotter/R/chart.Posn.R
pkg/blotter/R/extractTests.R
pkg/blotter/R/getBySymbol.R
pkg/blotter/R/initPortf.R
pkg/blotter/R/perTradeStats.R
pkg/blotter/R/tradeStats.R
pkg/blotter/R/updatePortf.R
pkg/quantstrat/R/applyStrategy.rebalancing.R
pkg/quantstrat/R/orders.R
pkg/quantstrat/R/parameters.R
pkg/quantstrat/R/paramsets.R
pkg/quantstrat/R/rebalance.rules.R
pkg/quantstrat/R/strategy.R
pkg/quantstrat/R/wrapup.R
Log:
- almost all the work to convert the symbols slot in portfolio and each asset into an environment
- thanks to Josh Ulrich for helping conceptualize this, and JR for the suggestion
Modified: pkg/blotter/R/calcPortfWgt.R
===================================================================
--- pkg/blotter/R/calcPortfWgt.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/blotter/R/calcPortfWgt.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -31,7 +31,7 @@
pname<-Portfolio
Portfolio<-getPortfolio(pname) # TODO add Date handling
- if(is.null(Symbols)) Symbols<-names(Portfolio$symbols)
+ if(is.null(Symbols)) Symbols<-ls(Portfolio$symbols)
pos.value = .getBySymbol(Portfolio = Portfolio, Dates = Dates, Attribute = "Pos.Value", Symbols = Symbols)
portf.value = .getByPortf(Account=getAccount(Account),Attribute = denominator[1], Dates = Dates)
Modified: pkg/blotter/R/chart.Posn.R
===================================================================
--- pkg/blotter/R/chart.Posn.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/blotter/R/chart.Posn.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -13,7 +13,7 @@
{ # @author Peter Carl, Brian Peterson
pname<-Portfolio
Portfolio<-getPortfolio(pname)
- if (missing(Symbol)) Symbol <- names(Portfolio$symbols)[[1]]
+ if (missing(Symbol)) Symbol <- ls(Portfolio$symbols)[[1]]
else Symbol <- Symbol[1]
# FUNCTION
Modified: pkg/blotter/R/extractTests.R
===================================================================
--- pkg/blotter/R/extractTests.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/blotter/R/extractTests.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -25,7 +25,7 @@
if(inherits(Portfolio,"try-error"))
stop(paste("Portfolio",pname," not found, use initPortf() to create a new portfolio first"))
out<-NULL
- symbolnames<-names(Portfolio[['symbols']])
+ symbolnames<-ls(Portfolio[['symbols']])
for (Symbol in symbolnames) {
tmpTxns<-Portfolio$symbols[[Symbol]]$txn[-1,]
if (nrow(tmpTxns)>=1){
Modified: pkg/blotter/R/getBySymbol.R
===================================================================
--- pkg/blotter/R/getBySymbol.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/blotter/R/getBySymbol.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -32,7 +32,7 @@
table = NULL
## Need a reference time index
if(is.null(Symbols))
- symbols=names(Portfolio$symbols)
+ symbols=ls(Portfolio$symbols)
else
symbols = Symbols
Modified: pkg/blotter/R/initPortf.R
===================================================================
--- pkg/blotter/R/initPortf.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/blotter/R/initPortf.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -3,7 +3,7 @@
#' Constructs and initializes a portfolio object, which is used to contain transactions, positions, and aggregate level values.
#'
#' Initializes a portfolio object, which is constructed from the following:
-#' $symbols: the identifier used for each instrument contained in the portfolio. Use \code{names(Portfolio$symbols)} to get a list of symbols.
+#' $symbols: the identifier used for each instrument contained in the portfolio. Use \code{ls(Portfolio$symbols)} to get a list of symbols.
#' $symbols$[symbol]$txn: irregular xts object of transactions data
#' $symbols$[symbol]$posPL: regular xts object of positions P&L calculated from transactions
#' $symbols$[symbol]$posPL.ccy: regular xts object of positions P&L converted to portfolio currency
@@ -70,13 +70,17 @@
# Thanks to Jeff Ryan and Josh Ulrich for pointers
portfolio = new.env(hash=TRUE)
- portfolio$symbols=vector("list",length=length(symbols))
- names(portfolio$symbols)=symbols
+ #portfolio$symbols=vector("list",length=length(symbols))
+ #names(portfolio$symbols)=symbols
+ portfolio[['symbols']] = new.env(hash=TRUE)
+
if(length(initPosQty)==1)
initPosQty=rep(initPosQty, length(symbols))
if(length(initPosQty)!=length(symbols))
stop("The length of initPosQty is unequal to the number of symbols in the portfolio.")
for(instrument in symbols){
+ portfolio$symbols[[instrument]] = new.env(hash=TRUE)
+ #portfolio$symbols[[instrument]] = list()
i = match(instrument, symbols)
portfolio$symbols[[instrument]]$txn = .initTxn(initDate = initDate, initPosQty = initPosQty[i],...=...)
portfolio$symbols[[instrument]]$posPL = .initPosPL(initDate = initDate, initPosQty = initPosQty[i],...=...)
Modified: pkg/blotter/R/perTradeStats.R
===================================================================
--- pkg/blotter/R/perTradeStats.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/blotter/R/perTradeStats.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -46,7 +46,7 @@
perTradeStats <- function(Portfolio, Symbol, includeOpenTrade=TRUE, ...) {
portf <- getPortfolio(Portfolio)
- if(missing(Symbol)) Symbol <- names(portf$symbols)[[1]]
+ if(missing(Symbol)) Symbol <- ls(portf$symbols)[[1]]
posPL <- portf$symbols[[Symbol]]$posPL
Modified: pkg/blotter/R/tradeStats.R
===================================================================
--- pkg/blotter/R/tradeStats.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/blotter/R/tradeStats.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -104,7 +104,7 @@
## FIXME: need a way to define symbols for each portfolio
- if(missing(Symbols)) symbols <- names(Portfolio$symbols)
+ if(missing(Symbols)) symbols <- ls(Portfolio$symbols)
else symbols <- Symbols
## Trade Statistics
@@ -258,7 +258,7 @@
## FIXME: need a way to define symbols for each portfolio
- if(missing(Symbols)) symbols <- names(Portfolio$symbols)
+ if(missing(Symbols)) symbols <- ls(Portfolio$symbols)
else symbols <- Symbols
## Trade Statistics
@@ -301,7 +301,7 @@
## FIXME: need a way to define symbols for each portfolio
- if(missing(Symbols)) symbols <- names(Portfolio$symbols)
+ if(missing(Symbols)) symbols <- ls(Portfolio$symbols)
else symbols <- Symbols
## Trade Statistics
Modified: pkg/blotter/R/updatePortf.R
===================================================================
--- pkg/blotter/R/updatePortf.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/blotter/R/updatePortf.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -17,91 +17,95 @@
#' @export
updatePortf <- function(Portfolio, Symbols=NULL, Dates=NULL, Prices=NULL, ...)
{ #' @author Peter Carl, Brian Peterson
- pname<-Portfolio
- Portfolio<-getPortfolio(pname) # TODO add Date handling
-
- # FUNCTION
- if(is.null(Symbols)){
- Symbols = names(Portfolio$symbols)
- }
- for(symbol in Symbols){
- tmp_instr<-try(getInstrument(symbol), silent=TRUE)
- .updatePosPL(Portfolio=pname, Symbol=as.character(symbol), Dates=Dates, Prices=Prices, ...=...)
- }
-
- # Calculate and store portfolio summary table
- Portfolio<-getPortfolio(pname) # refresh with an updated object
- if(is.null(Dates)) Dates <- xts:::time.xts(Portfolio$symbols[[1]]$posPL) #not quite right, only using first symbol...
- #Symbols = names(Portfolio$symbols)
- Attributes = c('Long.Value', 'Short.Value', 'Net.Value', 'Gross.Value', 'Period.Realized.PL', 'Period.Unrealized.PL', 'Gross.Trading.PL', 'Txn.Fees', 'Net.Trading.PL')
- summary = NULL
- tmp.attr=NULL
- for(attribute in Attributes) {
- result=NULL
- switch(attribute,
- Net.Value =,
- Gross.Value =,
- Long.Value =,
- Short.Value =,{
- # all these use Pos.Value
- if(is.null(tmp.attr)){
- table = .getBySymbol(Portfolio = Portfolio, Attribute = "Pos.Value", Dates = Dates, Symbols = Symbols)
- tmp.attr="Pos.Value"
- }
- switch(attribute,
- Gross.Value = { result = xts(rowSums(abs(table), na.rm=TRUE), order.by=index(table))},
- Long.Value = { tmat = apply(table,MARGIN=c(1,2),FUN=max,0)# comes out a matrix
- result = xts(rowSums(tmat, na.rm=TRUE), order.by=index(table))
- },
- Short.Value = { tmat = apply(table,MARGIN=c(1,2),FUN=min,0) # comes out a matrix
- result = xts(rowSums(tmat, na.rm=TRUE), order.by=index(table))
- },
- Net.Value = { result = xts(rowSums(table, na.rm=TRUE), order.by=index(table)) }
- )
- },
- Period.Realized.PL =,
- Period.Unrealized.PL =,
- Gross.Trading.PL =,
- Txn.Fees =,
- Net.Trading.PL = {
- table = .getBySymbol(Portfolio = Portfolio, Attribute = attribute, Dates = Dates, Symbols = Symbols)
- tmp.attr = NULL
- result = xts(rowSums(table, na.rm=TRUE), order.by=index(table))
- }
- )
-
- colnames(result) = attribute
- if(is.null(summary)) {summary=result}
- else {summary=cbind(summary,result)}
- }
-
- # get rid of duplicated indices in the summary data,
- # thanks to Guy Yollin for the bug report and Josh Ulrich for the elegant approach to fixing it
- d <- duplicated(.index(summary)) | duplicated(.index(summary), fromLast=TRUE)
- if(any(d)){
- f <- function(x) {
- cLast <- c('Long.Value', 'Short.Value', 'Net.Value', 'Gross.Value')
- cSums <- c('Period.Realized.PL', 'Period.Unrealized.PL', 'Gross.Trading.PL', 'Txn.Fees', 'Net.Trading.PL')
- setNames( merge(last(x[,cLast]), xts(t(colSums(x[,cSums],na.rm=TRUE)),last(index(x)))), colnames(x) )
- }
- summary.dups <- summary[d,]
- ds <- duplicated(.index(summary.dups)) & !duplicated(.index(summary.dups), fromLast=TRUE)
- slist <- period.apply(summary.dups, c(0, which(ds)), f)
- summary <- rbind(summary[!d,], slist) # put it all back together
- }
-
- if(!is.timeBased(Dates)) Dates = xts:::time.xts(Portfolio$symbols[[1]][["posPL"]][Dates])
- startDate = first(xts:::.parseISO8601(Dates))$first.time-.00001
- # trim summary slot to not double count, related to bug 831 on R-Forge, and rbind new summary
- if( as.POSIXct(attr(Portfolio,'initDate'))>=startDate || length(Portfolio$summary)==0 ){
- Portfolio$summary<-summary #changes to subset might not return a empty dimnames set of columns
- }else{
- Portfolio$summary<-rbind(Portfolio$summary[paste('::',startDate,sep='')],summary)
- }
- # assign Portfolio to environment
- assign( paste("portfolio",pname,sep='.'), Portfolio, envir=.blotter )
-
- return(pname) #not sure this is a good idea
+ pname<-Portfolio
+ Portfolio<-getPortfolio(pname) # TODO add Date handling
+
+ # FUNCTION
+ if(is.null(Symbols)){
+ Symbols = ls(Portfolio$symbols)
+ }
+ for(symbol in Symbols){
+ tmp_instr<-try(getInstrument(symbol), silent=TRUE)
+ .updatePosPL(Portfolio=pname, Symbol=as.character(symbol), Dates=Dates, Prices=Prices, ...=...)
+ }
+
+ # Calculate and store portfolio summary table
+ Portfolio<-getPortfolio(pname) # refresh with an updated object
+ #if(is.null(Dates)) Dates <- xts:::time.xts(Portfolio$symbols[[1]]$posPL) #not quite right, only using first symbol...
+ if(is.null(Dates)) Dates <- xts(,do.call(unlist,c(lapply(Portfolio$symbols, function(x) index(x[["posPL"]][Dates]) ))))
+
+ #Symbols = ls(Portfolio$symbols)
+ Attributes = c('Long.Value', 'Short.Value', 'Net.Value', 'Gross.Value', 'Period.Realized.PL', 'Period.Unrealized.PL', 'Gross.Trading.PL', 'Txn.Fees', 'Net.Trading.PL')
+ summary = NULL
+ tmp.attr=NULL
+ for(attribute in Attributes) {
+ result=NULL
+ switch(attribute,
+ Net.Value =,
+ Gross.Value =,
+ Long.Value =,
+ Short.Value =,{
+ # all these use Pos.Value
+ if(is.null(tmp.attr)){
+ table = .getBySymbol(Portfolio = Portfolio, Attribute = "Pos.Value", Dates = Dates, Symbols = Symbols)
+ tmp.attr="Pos.Value"
+ }
+ switch(attribute,
+ Gross.Value = { result = xts(rowSums(abs(table), na.rm=TRUE), order.by=index(table))},
+ Long.Value = { tmat = apply(table,MARGIN=c(1,2),FUN=max,0)# comes out a matrix
+ result = xts(rowSums(tmat, na.rm=TRUE), order.by=index(table))
+ },
+ Short.Value = { tmat = apply(table,MARGIN=c(1,2),FUN=min,0) # comes out a matrix
+ result = xts(rowSums(tmat, na.rm=TRUE), order.by=index(table))
+ },
+ Net.Value = { result = xts(rowSums(table, na.rm=TRUE), order.by=index(table)) }
+ )
+ },
+ Period.Realized.PL =,
+ Period.Unrealized.PL =,
+ Gross.Trading.PL =,
+ Txn.Fees =,
+ Net.Trading.PL = {
+ table = .getBySymbol(Portfolio = Portfolio, Attribute = attribute, Dates = Dates, Symbols = Symbols)
+ tmp.attr = NULL
+ result = xts(rowSums(table, na.rm=TRUE), order.by=index(table))
+ }
+ )
+
+ colnames(result) = attribute
+ if(is.null(summary)) {summary=result}
+ else {summary=cbind(summary,result)}
+ }
+
+ # get rid of duplicated indices in the summary data,
+ # thanks to Guy Yollin for the bug report and Josh Ulrich for the elegant approach to fixing it
+ d <- duplicated(.index(summary)) | duplicated(.index(summary), fromLast=TRUE)
+ if(any(d)){
+ f <- function(x) {
+ cLast <- c('Long.Value', 'Short.Value', 'Net.Value', 'Gross.Value')
+ cSums <- c('Period.Realized.PL', 'Period.Unrealized.PL', 'Gross.Trading.PL', 'Txn.Fees', 'Net.Trading.PL')
+ setNames( merge(last(x[,cLast]), xts(t(colSums(x[,cSums],na.rm=TRUE)),last(index(x)))), colnames(x) )
+ }
+ summary.dups <- summary[d,]
+ ds <- duplicated(.index(summary.dups)) & !duplicated(.index(summary.dups), fromLast=TRUE)
+ slist <- period.apply(summary.dups, c(0, which(ds)), f)
+ summary <- rbind(summary[!d,], slist) # put it all back together
+ }
+
+ # if(!is.timeBased(Dates)) Dates = xts:::time.xts(Portfolio$symbols[[1]][["posPL"]][Dates])
+ #xts(,do.call(unlist,c(lapply(symbols,index),use.names=FALSE)))
+ if(!is.timeBased(Dates)) Dates <- xts(,do.call(unlist,c(lapply(Portfolio$symbols, function(x) index(x[["posPL"]][Dates]) ))))
+ startDate = first(xts:::.parseISO8601(Dates))$first.time-.00001
+ # trim summary slot to not double count, related to bug 831 on R-Forge, and rbind new summary
+ if( as.POSIXct(attr(Portfolio,'initDate'))>=startDate || length(Portfolio$summary)==0 ){
+ Portfolio$summary<-summary #changes to subset might not return a empty dimnames set of columns
+ }else{
+ Portfolio$summary<-rbind(Portfolio$summary[paste('::',startDate,sep='')],summary)
+ }
+ # assign Portfolio to environment
+ assign( paste("portfolio",pname,sep='.'), Portfolio, envir=.blotter )
+
+ return(pname) #not sure this is a good idea
}
###############################################################################
Modified: pkg/quantstrat/R/applyStrategy.rebalancing.R
===================================================================
--- pkg/quantstrat/R/applyStrategy.rebalancing.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/quantstrat/R/applyStrategy.rebalancing.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -76,7 +76,7 @@
ret[[portfolio]]<-list() # this is slot [[i]] which we will use later
pobj<-getPortfolio(portfolio)
- symbols<-names(pobj$symbols)
+ symbols<-ls(pobj$symbols)
st<-new.env()
#should be able to use this directly
Modified: pkg/quantstrat/R/orders.R
===================================================================
--- pkg/quantstrat/R/orders.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/quantstrat/R/orders.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -87,7 +87,7 @@
if(is.null(symbols)) {
pfolio<-getPortfolio(portfolio)
- symbols<-names(pfolio$symbols)
+ symbols<-ls(pfolio$symbols)
}
if(!is.null(symbols)){
orders[[portfolio]][symbols] <- list(NULL)
Modified: pkg/quantstrat/R/parameters.R
===================================================================
--- pkg/quantstrat/R/parameters.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/quantstrat/R/parameters.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -398,11 +398,11 @@
#need to create combination of distribution values in each slot of the parameterPool
initialPortf<-getPortfolio(portfolios)
- symbols<-names(initialPortf$symbols)
+ symbols<-ls(initialPortf$symbols)
initDate<-time(first(initialPortf$symbols[[1]]$posPL))
limits<-list()
- for(symbol in names(initialPortf$symbols))
+ for(symbol in ls(initialPortf$symbols))
limits[[symbol]]<-initialPortf$symbols[[symbol]]$PosLimit
tmp_strategy<-strategy
Modified: pkg/quantstrat/R/paramsets.R
===================================================================
--- pkg/quantstrat/R/paramsets.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/quantstrat/R/paramsets.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -11,7 +11,7 @@
#
###############################################################################
#
-# Authors: Yu Chen, Jan Humme
+# Authors: Jan Humme, Brian Peterson
#
# This code is a based on earlier work by Yu Chen
#
@@ -51,7 +51,7 @@
if(strip.history==TRUE)
{
- for(symbol in names(portfolio$symbols))
+ for(symbol in ls(portfolio$symbols))
{
portfolio$symbols[[symbol]]$txn <- portfolio$symbols[[symbol]]$txn[1,]
Modified: pkg/quantstrat/R/rebalance.rules.R
===================================================================
--- pkg/quantstrat/R/rebalance.rules.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/quantstrat/R/rebalance.rules.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -1,118 +1,118 @@
-#' rule to base trade size on a percentage of available equity.
-#'
-#' This rule works with \code{\link{applyStrategy.rebalancing}} to set the
-#' maximum trade size by calling \code{\link{addPosLimit}}.
-#'
-#' To use it, you need to specify it as (part of) a rule of type 'rebalance'.
-#' note that \code{\link{applyStrategy.rebalancing}} will expect a
-#' 'rebalance_on' argument to be included in the \code{arguments=list(...)}
-#' of the rule definition.
-#'
-#'
-#'
-#' @param trade.percent max percentage of equity to allow the strategy to trade in this symbol
-#' @param longlevels numeric number of levels
-#' @param shortlevels numeric number of short levels, default longlevels
-#' @param digits if not NULL(the default), will call \code{\link{round}} with specified number of digits
-#' @param refprice if not NULL(the default), will divide the calculated tra
-#' @param portfolio text name of the portfolio to place orders in, typically set automatically
-#' @param symbol identifier of the instrument to cancel orders for, typically set automatically
-#' @param timestamp timestamp coercible to POSIXct that will be the time the order will be inserted on, typically set automatically
-#' @param \dots any other passthrough parameters
-#' @seealso \code{\link{osMaxPos}} ,
-#' \code{\link{applyStrategy.rebalancing}},
-#' \code{\link{addPosLimit}},
-#' \code{\link{add.rule}}
-#'
-#' @examples
-#' # example rule definition
-#' \dontrun{
-#' add.rule(strategy.name, 'rulePctEquity',
-#' arguments=list(rebalance_on='months',
-#' trade.percent=.02,
-#' refprice=quote(last(getPrice(mktdata)[paste('::',timestamp,sep='')])),
-#' digits=0
-#' ),
-#' type='rebalance',
-#' label='rebalance')
-#' }
-#' @export
-rulePctEquity <- function (trade.percent=.02,
- ...,
- longlevels=1,
- shortlevels=1,
- digits=NULL,
- refprice=NULL,
- portfolio,
- symbol,
- timestamp)
-{
- dummy <- updatePortf(Portfolio=portfolio,
- Dates=paste('::',timestamp,sep=''))
- trading.pl <- sum(getPortfolio(portfolio)$summary$Net.Trading.PL)
- total.equity <- initEq+trading.pl
- tradeSize <- total.equity * trade.percent
- if(!is.null(refprice)) tradeSize <- tradeSize/refprice
- if(!is.null(digits)) tradeSize<-round(tradeSize,digits)
- addPosLimit(portfolio = portfolio,
- symbol = symbol,
- timestamp = timestamp,
- maxpos = tradeSize,
- longlevels = longlevels,
- minpos = -tradeSize,
- shortlevels = shortlevels)
-}
-
-ruleWeights <- function (weights=NULL,
- ...,
- longlevels=1,
- shortlevels=1,
- digits=NULL,
- portfolio,
- symbol,
- account=NULL,
- timestamp)
-{
- #update portfolio
- dummy <- updatePortf(Portfolio=portfolio,
- Dates=paste('::',timestamp,sep=''))
-
- #get total account equity
- if(!is.null(account)){
- dummy <- updateAcct(Account=account,
- Dates=paste('::',timestamp,sep=''))
- dummy <- updateEndEq(Account=account,
- Dates=paste('::',timestamp,sep=''))
- total.equity<-getEndEq(account)
- } else {
- trading.pl <- sum(getPortfolio(portfolio)$summary$Net.Trading.PL)
- total.equity <- initEq+trading.pl
- }
-
- if(!is.null(digits)) tradeSize<-round(tradeSize,digits)
- addPosLimit(portfolio = portfolio,
- symbol = symbol,
- timestamp = timestamp,
- maxpos = tradeSize,
- longlevels = longlevels,
- minpos = -tradeSize,
- shortlevels = shortlevels)
-}
-
-#TODO weights rule that takes or calculates max position based on weights
-#TODO active weights rule that moved from current positions to target positions
-#TODO PortfolioAnalytics sizing
-#TODO LSPM sizing
-
-###############################################################################
-# R (http://r-project.org/) Quantitative Strategy Model Framework
-#
-# Copyright (c) 2009-2012
-# Peter Carl, Dirk Eddelbuettel, Brian G. Peterson, Jeffrey Ryan, and Joshua Ulrich
-#
-# This library is distributed under the terms of the GNU Public License (GPL)
-# for full details see the file COPYING
-#
-# $Id$
-#
-###############################################################################
+#' rule to base trade size on a percentage of available equity.
+#'
+#' This rule works with \code{\link{applyStrategy.rebalancing}} to set the
+#' maximum trade size by calling \code{\link{addPosLimit}}.
+#'
+#' To use it, you need to specify it as (part of) a rule of type 'rebalance'.
+#' note that \code{\link{applyStrategy.rebalancing}} will expect a
+#' 'rebalance_on' argument to be included in the \code{arguments=list(...)}
+#' of the rule definition.
+#'
+#'
+#'
+#' @param trade.percent max percentage of equity to allow the strategy to trade in this symbol
+#' @param longlevels numeric number of levels
+#' @param shortlevels numeric number of short levels, default longlevels
+#' @param digits if not NULL(the default), will call \code{\link{round}} with specified number of digits
+#' @param refprice if not NULL(the default), will divide the calculated tra
+#' @param portfolio text name of the portfolio to place orders in, typically set automatically
+#' @param symbol identifier of the instrument to cancel orders for, typically set automatically
+#' @param timestamp timestamp coercible to POSIXct that will be the time the order will be inserted on, typically set automatically
+#' @param \dots any other passthrough parameters
+#' @seealso \code{\link{osMaxPos}} ,
+#' \code{\link{applyStrategy.rebalancing}},
+#' \code{\link{addPosLimit}},
+#' \code{\link{add.rule}}
+#'
+#' @examples
+#' # example rule definition
+#' \dontrun{
+#' add.rule(strategy.name, 'rulePctEquity',
+#' arguments=list(rebalance_on='months',
+#' trade.percent=.02,
+#' refprice=quote(last(getPrice(mktdata)[paste('::',timestamp,sep='')])),
+#' digits=0
+#' ),
+#' type='rebalance',
+#' label='rebalance')
+#' }
+#' @export
+rulePctEquity <- function (trade.percent=.02,
+ ...,
+ longlevels=1,
+ shortlevels=1,
+ digits=NULL,
+ refprice=NULL,
+ portfolio,
+ symbol,
+ timestamp)
+{
+ dummy <- updatePortf(Portfolio=portfolio,
+ Dates=paste('::',timestamp,sep=''))
+ trading.pl <- sum(getPortfolio(portfolio)$summary$Net.Trading.PL)
+ total.equity <- initEq+trading.pl
+ tradeSize <- total.equity * trade.percent
+ if(!is.null(refprice)) tradeSize <- tradeSize/refprice
+ if(!is.null(digits)) tradeSize<-round(tradeSize,digits)
+ addPosLimit(portfolio = portfolio,
+ symbol = symbol,
+ timestamp = timestamp,
+ maxpos = tradeSize,
+ longlevels = longlevels,
+ minpos = -tradeSize,
+ shortlevels = shortlevels)
+}
+
+ruleWeights <- function (weights=NULL,
+ ...,
+ longlevels=1,
+ shortlevels=1,
+ digits=NULL,
+ portfolio,
+ symbol,
+ account=NULL,
+ timestamp)
+{
+ #update portfolio
+ dummy <- updatePortf(Portfolio=portfolio,
+ Dates=paste('::',timestamp,sep=''))
+
+ #get total account equity
+ if(!is.null(account)){
+ dummy <- updateAcct(name=account,
+ Dates=paste('::',timestamp,sep=''))
+ dummy <- updateEndEq(Account=account,
+ Dates=paste('::',timestamp,sep=''))
+ total.equity<-getEndEq(account)
+ } else {
+ trading.pl <- sum(getPortfolio(portfolio)$summary$Net.Trading.PL)
+ total.equity <- initEq+trading.pl
+ }
+
+ if(!is.null(digits)) tradeSize<-round(tradeSize,digits)
+ addPosLimit(portfolio = portfolio,
+ symbol = symbol,
+ timestamp = timestamp,
+ maxpos = tradeSize,
+ longlevels = longlevels,
+ minpos = -tradeSize,
+ shortlevels = shortlevels)
+}
+
+#TODO weights rule that takes or calculates max position based on weights
+#TODO active weights rule that moved from current positions to target positions
+#TODO PortfolioAnalytics sizing
+#TODO LSPM sizing
+
+###############################################################################
+# R (http://r-project.org/) Quantitative Strategy Model Framework
+#
+# Copyright (c) 2009-2012
+# Peter Carl, Dirk Eddelbuettel, Brian G. Peterson, Jeffrey Ryan, and Joshua Ulrich
+#
+# This library is distributed under the terms of the GNU Public License (GPL)
+# for full details see the file COPYING
+#
+# $Id$
+#
+###############################################################################
Modified: pkg/quantstrat/R/strategy.R
===================================================================
--- pkg/quantstrat/R/strategy.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/quantstrat/R/strategy.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -121,7 +121,7 @@
ret[[portfolio]]<-list() # this is slot [[i]] which we will use later
pobj<-getPortfolio(portfolio)
- symbols<-names(pobj$symbols)
+ symbols<- ls(pobj$symbols)
sret<-list()
for (symbol in symbols){
if(isTRUE(load.mktdata)) mktdata <- get(symbol)
Modified: pkg/quantstrat/R/wrapup.R
===================================================================
--- pkg/quantstrat/R/wrapup.R 2013-09-13 17:13:10 UTC (rev 1502)
+++ pkg/quantstrat/R/wrapup.R 2013-09-13 21:37:20 UTC (rev 1503)
@@ -153,7 +153,7 @@
if(showEq) cat('Ending Account Equity: ', getEndEq(Account=account,Date=Sys.time()), '\n')
}
if(isTRUE(chart)){
- for (symbol in names(getPortfolio(portfolio)$symbols) ){
+ for (symbol in ls(getPortfolio(portfolio)$symbols) ){
dev.new()
chart.Posn(Portfolio=portfolio, Symbol=symbol,...=...)
}
More information about the Blotter-commits
mailing list