[Blotter-commits] r1525 - in pkg/blotter: . R man
noreply at r-forge.r-project.org
noreply at r-forge.r-project.org
Mon Oct 14 18:02:08 CEST 2013
Author: braverock
Date: 2013-10-14 18:02:08 +0200 (Mon, 14 Oct 2013)
New Revision: 1525
Modified:
pkg/blotter/DESCRIPTION
pkg/blotter/NAMESPACE
pkg/blotter/R/AcctReturns.R
pkg/blotter/R/PortfReturns.R
pkg/blotter/R/addAcctTxn.R
pkg/blotter/R/addPortfInstr.R
pkg/blotter/R/addTxn.R
pkg/blotter/R/calcPortfWgt.R
pkg/blotter/R/calcPosAvgCost.R
pkg/blotter/R/calcTxnAvgCost.R
pkg/blotter/R/calcTxnValue.R
pkg/blotter/R/chart.ME.R
pkg/blotter/R/chart.Posn.R
pkg/blotter/R/chart.Reconcile.R
pkg/blotter/R/chart.Spread.R
pkg/blotter/R/extractTests.R
pkg/blotter/R/getAccount.R
pkg/blotter/R/getByPortf.R
pkg/blotter/R/getBySymbol.R
pkg/blotter/R/getEndEq.R
pkg/blotter/R/getPortfAcct.R
pkg/blotter/R/getPortfolio.R
pkg/blotter/R/getPos.R
pkg/blotter/R/getPosAvgCost.R
pkg/blotter/R/getPosQty.R
pkg/blotter/R/getTxn.R
pkg/blotter/R/initAcct.R
pkg/blotter/R/initPortf.R
pkg/blotter/R/initPosPL.R
pkg/blotter/R/initSummary.R
pkg/blotter/R/initTxn.R
pkg/blotter/R/perTradeStats.R
pkg/blotter/R/put.account.R
pkg/blotter/R/put.portfolio.R
pkg/blotter/R/tradeStats.R
pkg/blotter/R/updateAcct.R
pkg/blotter/R/updateEndEq.R
pkg/blotter/R/updatePortf.R
pkg/blotter/R/updatePosPL.R
pkg/blotter/man/getPortfolio.Rd
Log:
- split getPortfolio into public and internal functions to avoid accidental environment damage
- update svn propset on .R files for Date Author Id tags
Modified: pkg/blotter/DESCRIPTION
===================================================================
--- pkg/blotter/DESCRIPTION 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/DESCRIPTION 2013-10-14 16:02:08 UTC (rev 1525)
@@ -2,7 +2,7 @@
Type: Package
Title: Tools for transaction-oriented trading systems
development.
-Version: 0.8.16
+Version: 0.8.17
Date: $Date$
Author: Peter Carl, Brian G. Peterson
Maintainer: Brian G. Peterson <brian at braverock.com>
@@ -10,7 +10,7 @@
instruments, transactions, portfolios and accounts for
trading systems and simulation. Provides portfolio
support for multi-asset class and multi-currency
- portfolios. Still in development.
+ portfolios. Actively maintained and developed.
License: GPL
LazyLoad: yes
Depends:
Modified: pkg/blotter/NAMESPACE
===================================================================
--- pkg/blotter/NAMESPACE 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/NAMESPACE 2013-10-14 16:02:08 UTC (rev 1525)
@@ -1,9 +1,11 @@
-useDynLib(blotter)
+export(.getPortfolio)
+export(AcctReturns)
export(PortfReturns)
+export(addAcctTxn)
export(addDiv)
export(addPortfInstr)
export(addTxn)
-export(addAcctTxn)
+export(addTxns)
export(calcPortfWgt)
export(chart.ME)
export(chart.Posn)
Property changes on: pkg/blotter/R/AcctReturns.R
___________________________________________________________________
Added: svn:keywords
+ Date Author Id
Property changes on: pkg/blotter/R/PortfReturns.R
___________________________________________________________________
Modified: svn:keywords
- Revision Id Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/addAcctTxn.R
___________________________________________________________________
Added: svn:keywords
+ Date Author Id
Modified: pkg/blotter/R/addPortfInstr.R
===================================================================
--- pkg/blotter/R/addPortfInstr.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/addPortfInstr.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -8,19 +8,17 @@
#' @export
addPortfInstr <- function(Portfolio,symbols,...)
{
- pname<-Portfolio
- portfolio<-get(paste("portfolio",pname,sep='.'),envir=.blotter)
- if(inherits(Portfolio,"try-error"))
- stop(paste("Portfolio",pname," not found, use initPortf() to create a new portfolio"))
- initDate <- attr(portfolio, "initDate")
- currency <- attr(portfolio, "currency")
- for(instrument in symbols){
- portfolio$symbols[[instrument]]$txn = .initTxn(initDate = initDate, initPosQty = 0)
- portfolio$symbols[[instrument]]$posPL = .initPosPL(initDate = initDate, initPosQty = 0)
- portfolio$symbols[[instrument]][[paste('posPL',currency,sep='.')]] = portfolio$symbols[[instrument]]$posPL
- }
- #portfolio is already an environment, it's been updated in place
- #assign(paste("portfolio",as.character(pname),sep='.'),portfolio,envir=.blotter)
+ pname<-Portfolio
+ portfolio<-getPortfolio(pname)
+ initDate <- attr(portfolio, "initDate")
+ currency <- attr(portfolio, "currency")
+ for(instrument in symbols){
+ portfolio$symbols[[instrument]]$txn = .initTxn(initDate = initDate, initPosQty = 0)
+ portfolio$symbols[[instrument]]$posPL = .initPosPL(initDate = initDate, initPosQty = 0)
+ portfolio$symbols[[instrument]][[paste('posPL',currency,sep='.')]] = portfolio$symbols[[instrument]]$posPL
+ }
+ #portfolio is already an environment, it's been updated in place
+ #assign(paste("portfolio",as.character(pname),sep='.'),portfolio,envir=.blotter)
}
###############################################################################
Property changes on: pkg/blotter/R/addPortfInstr.R
___________________________________________________________________
Modified: svn:keywords
- Revision Id Date Author
+ Date Author Id
Modified: pkg/blotter/R/addTxn.R
===================================================================
--- pkg/blotter/R/addTxn.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/addTxn.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -53,7 +53,8 @@
#' TODO figure out if we can fully vectorize the addTxns function to make it faster
#' @seealso \code{\link{addTxns}}, \code{\link{pennyPerShare}}, \code{\link{initPortf}}
#' @author Peter Carl, Brian G. Peterson
-#' @export
+#' @export addTxn
+#' @export addTxns
addTxn <- function(Portfolio, Symbol, TxnDate, TxnQty, TxnPrice, ..., TxnFees=0, ConMult=NULL, verbose=TRUE, eps=1e-06)
{
Property changes on: pkg/blotter/R/addTxn.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/calcPortfWgt.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/calcPosAvgCost.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/calcTxnAvgCost.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/calcTxnValue.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/chart.ME.R
___________________________________________________________________
Modified: svn:keywords
- Id Author Date
+ Date Author Id
Property changes on: pkg/blotter/R/chart.Posn.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Modified: pkg/blotter/R/chart.Reconcile.R
===================================================================
--- pkg/blotter/R/chart.Reconcile.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/chart.Reconcile.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -167,6 +167,6 @@
# This library is distributed under the terms of the GNU Public License (GPL)
# for full details see the file COPYING
#
-# $Id: chart.Posn.R 531 2011-01-14 16:42:23Z llevenson $
+# $Id$
#
###############################################################################
Property changes on: pkg/blotter/R/chart.Reconcile.R
___________________________________________________________________
Added: svn:keywords
+ Date Author Id
Property changes on: pkg/blotter/R/chart.Spread.R
___________________________________________________________________
Modified: svn:keywords
- Revision Id Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/extractTests.R
___________________________________________________________________
Modified: svn:keywords
- Revision Id Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/getAccount.R
___________________________________________________________________
Modified: svn:keywords
- Revision Id Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/getByPortf.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/getBySymbol.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/getEndEq.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/getPortfAcct.R
___________________________________________________________________
Modified: svn:keywords
- Revision Id Date Author
+ Date Author Id
Modified: pkg/blotter/R/getPortfolio.R
===================================================================
--- pkg/blotter/R/getPortfolio.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/getPortfolio.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -1,22 +1,49 @@
#' get a portfolio object
+#'
+#' Get a portfolio object conssting of either a nested list (\code{getPortfolio})
+#' or a pointer to the portfolio in the \code{.blotter} environment (\code{.getPortfolio})
+#'
+#' Portfolios in blotter are stored as a set of nested, hashed, environments.
+#'
+#' The \code{getPortfolio} function returns a nested list. If you are unsure, use this function.
+#'
+#' The \code{.getPortfolio} function returns a pointer to the actual environment.
+#' Environments in R are passed by reference, and are not copied by the \code{<-}
+#' assignment operator. Any changes made to the environment returned by
+#' \code{.getPortfolio} are global. You have been warned.
+#'
#' @param Portfolio string identifying portfolio
#' @param Dates dates subset, not yet supported
#' @param envir the environment to retrieve the portfolio from, defaults to .blotter
-#' @export
-getPortfolio <- function(Portfolio, Dates=NULL, envir=.blotter) #should symbol subsets be supported too? probably not.
+#'
+#' @seealso \code{\link{initPortf}}, \code{\link{updatePortf}}
+#' @export getPortfolio
+#' @export .getPortfolio
+getPortfolio <- function(Portfolio, Dates=NULL, envir=.blotter)
+{
+ pname<-Portfolio
+ oport<- .getPortfolio(Portfolio, envir=envir)
+ port <- as.list.environment(oport)
+ port$symbols<-list()
+ port$symbols <- lapply(oport$symbols, as.list.environment)
+
+ if(!is.null(Dates)){
+ message("date subsetting not yet supported")
+ #TODO add date subsetting in getPortfolio
+ }
+
+ return(port)
+}
+
+#' @rdname getPortfolio
+.getPortfolio <- function(Portfolio, envir=.blotter)
{ # @author Brian Peterson
pname<-Portfolio
if(!grepl("portfolio\\.",pname)) Portfolio<-suppressWarnings(try(get(paste("portfolio",pname,sep='.'),envir=envir),silent=TRUE))
else Portfolio<-suppressWarnings(try(get(pname,envir=envir),silent=TRUE))
if(inherits(Portfolio,"try-error"))
stop(paste("Portfolio",pname," not found, use initPortf() to create a new portfolio"))
- if(!inherits(Portfolio,"portfolio")) stop("Portfolio",pname,"passed is not the name of a portfolio object.")
-
- if(!is.null(Dates)){
- message("date subsetting not yet supported")
- #TODO add date subsetting in getPortfolio
- }
-
+ if(!inherits(Portfolio,"portfolio")) stop("Portfolio",pname,"passed is not the name of a portfolio object.")
return(Portfolio)
}
Property changes on: pkg/blotter/R/getPortfolio.R
___________________________________________________________________
Modified: svn:keywords
- Revision Id Date Author
+ Date Author Id
Modified: pkg/blotter/R/getPos.R
===================================================================
--- pkg/blotter/R/getPos.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/getPos.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -10,7 +10,7 @@
#' @export
getPos <- function(Portfolio, Symbol, Date, Columns=c('Pos.Qty','Pos.Avg.Cost'),n=1)
{ # @author Peter Carl
- Portfolio<-getPortfolio(Portfolio)
+ Portfolio<-.getPortfolio(Portfolio)
# FUNCTION
PosData = Portfolio$symbols[[Symbol]]$txn
#toDate = paste('::', Date, sep="")
Property changes on: pkg/blotter/R/getPos.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/getPosAvgCost.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/getPosQty.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/getTxn.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/initAcct.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/initPortf.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/initPosPL.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Modified: pkg/blotter/R/initSummary.R
===================================================================
--- pkg/blotter/R/initSummary.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/initSummary.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -18,6 +18,6 @@
# This library is distributed under the terms of the GNU Public License (GPL)
# for full details see the file COPYING
#
-# $Id: initTxn.R 306 2010-03-26 21:19:51Z peter_carl $
+# $Id$
#
###############################################################################
Property changes on: pkg/blotter/R/initSummary.R
___________________________________________________________________
Added: svn:keywords
+ Date Author Id
Property changes on: pkg/blotter/R/initTxn.R
___________________________________________________________________
Modified: svn:keywords
- Id Revision Date Author
+ Date Author Id
Property changes on: pkg/blotter/R/perTradeStats.R
___________________________________________________________________
Modified: svn:keywords
- Id Author Date
+ Date Author Id
Modified: pkg/blotter/R/put.account.R
===================================================================
--- pkg/blotter/R/put.account.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/put.account.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -19,6 +19,6 @@
# This library is distributed under the terms of the GNU Public License (GPL)
# for full details see the file COPYING
#
-# $Id: getPortfolio.R 742 2011-08-25 21:12:43Z braverock $
+# $Id$
#
###############################################################################
Property changes on: pkg/blotter/R/put.account.R
___________________________________________________________________
Added: svn:keywords
+ Date Author Id
Modified: pkg/blotter/R/put.portfolio.R
===================================================================
--- pkg/blotter/R/put.portfolio.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/put.portfolio.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -19,6 +19,6 @@
# This library is distributed under the terms of the GNU Public License (GPL)
# for full details see the file COPYING
#
-# $Id: getPortfolio.R 742 2011-08-25 21:12:43Z braverock $
+# $Id$
#
###############################################################################
Property changes on: pkg/blotter/R/put.portfolio.R
___________________________________________________________________
Added: svn:keywords
+ Date Author Id
Modified: pkg/blotter/R/tradeStats.R
===================================================================
--- pkg/blotter/R/tradeStats.R 2013-10-11 19:43:26 UTC (rev 1524)
+++ pkg/blotter/R/tradeStats.R 2013-10-14 16:02:08 UTC (rev 1525)
@@ -1,442 +1,432 @@
-
-#' calculate statistics on transactions and P&L for a symbol or symbols in a portfolio or portfolios
-#'
-#' This function calculates trade-level statistics on a symbol or symbols within a portfolio or portfolios.
-#'
-#' Every book on trading, broker report on an analytical trading system,
-#' or blog post seems to have a slightly different idea of what trade statistics
-#' are necessary, and how they should be displayed. We choose not to make
-#' value judgments of this type, aiming rather for inclusiveness with
-#' post-processing for display.
-#'
-#' The output of this function is a \code{\link{data.frame}} with named columns for each statistic.
-#' Each row is a single portfolio+symbol combination. Values are returned in full precision.
-#' It is likely that the output of this function will have more than you wish
-#' to display in all conditions, but it should be suitable for reshaping for display.
-#' Building summary reports from this data.frame may be easily accomplished using
-#' something like \code{textplot} or \code{\link{data.frame}}, with rounding,
-#' fancy formatting, etc. as your needs dictate.
-#'
-#' If you have additional trade statistics you want added here, please share.
-#' We find it unlikely that any transaction-level statistics that can be
-#' calculated independently of strategy rules could be considered proprietary.
-#'
-#' Special Thanks for contributions to this function from:
-#' \describe{
-#' \item{Josh Ulrich}{ for adding multiple-portfolio support, fixing bugs, and improving readability of the code }
-#' \item{Klemen Koselj}{ for median stats, num trades, and win/loss ratios }
-#' \item{Mark Knecht}{ for suggesting Profit Factor and largest winner/largest loser }
-#' }
-#'
-#' WARNING: we're not sure this function is stable/complete yet. If you're using it, please give us feedback!
-#'
-#' @aliases dailyStats
-#' @seealso \code{\link{chart.ME}} for a chart of MAE and MFE derived from trades,
-#' and \code{\link{perTradeStats}} for detailed statistics on a per-trade basis
-#' @param Portfolios portfolio string
-#' @param Symbols character vector of symbol strings, default NULL
-#' @param use for determines whether numbers are calculated from transactions or round-trip trades (for tradeStats) or equity curve (for dailyStats)
-#' @author Lance Levenson, Brian Peterson
-#' @export
-#' @importFrom zoo as.Date
-#' @return
-#' a \code{data.frame} containing:
-#'
-#' \describe{
-#' \item{Portfolio}{ name of the portfolio}
-#' \item{Symbol}{ symbol name }
-#' \item{Num.Txns}{ number of transactions produced by \code{\link{addTxn}} }
-#' \item{Num.Trades}{ number of \emph{flat to flat} trades performed }
-#' \item{Net.Trading.PL}{ }
-#' \item{Avg.Trade.PL}{ mean trading P&L per trade }
-#' \item{Med.Trade.PL}{ median trading P&L per trade}
-#' \item{Largest.Winner}{ largest winning trade }
-#' \item{Largest.Loser}{ largest losing trade }
-#' \item{Gross.Profits}{ gross (pre-fee) trade profits }
-#' \item{Gross.Losses}{ gross trade losses }
-#' \item{Std.Dev.Trade.PL}{ standard deviation of trade P&L }
-#' \item{Percent.Positive}{ percent of trades that end positive }
-#' \item{Percent.Negative}{ percent of trades that end negative }
-#' \item{Profit.Factor}{ absolute value ration of gross profits over gross losses }
-#' \item{Avg.Win.Trade}{ mean P&L of profitabloe trades }
-#' \item{Med.Win.Trade}{ median P&L of profitable trades }
-#' \item{Avg.Losing.Trade}{ mean P&L of losing trades }
-#' \item{Med.Losing.Trade}{ median P&L of losing trades }
-#' \item{Avg.Daily.PL}{mean daily realized P&L on days there were transactions, see \code{\link{dailyStats}} for all days }
-#' \item{Med.Daily.PL}{ median daily P&L }
-#' \item{Std.Dev.Daily.PL}{ standard deviation of daily P&L }
-#' \item{Max.Drawdown}{ max drawdown }
-#' \item{Avg.WinLoss.Ratio}{ ratio of mean winning over mean losing trade }
-#' \item{Med.WinLoss.Ratio}{ ratio of median winning trade over mean losing trade }
-#' \item{Max.Equity}{ maximum account equity }
-#' \item{Min.Equity}{ minimum account equity }
-#' }
-#' @note
-#' TODO document each statistic included in this function, with equations
-#'
-#' TODO add more stats, potentially
-#' PerformanceAnalytics: skewness, kurtosis, upside/downside semidieviation, Sharpe/Sortino
-#'
-#' mean absolute deviation stats
-#'
-#' more Tharpe/Kestner/Tradestation stats, e.g.
-#' K-factor
-#' RINA Index
-#' Percent time in the market
-#' Buy and hold return
-#'
-#' Josh has suggested adding \%-return based stats too
-tradeStats <- function(Portfolios, Symbols,use=c('txns','trades'))
-{
- ret <- NULL
- use <- use[1] #use the first(default) value only if user hasn't specified
- for (Portfolio in Portfolios){
- ## Error Handling Borrowed from getPortfolio
- pname <- Portfolio
- if (!grepl("portfolio\\.", pname))
- Portfolio <- try(get(paste("portfolio", pname, sep = "."), envir = .blotter), silent=TRUE)
- else Portfolio <- try(get(pname, envir = .blotter), silent=TRUE)
- if (inherits(Portfolio, "try-error"))
- stop(paste("Portfolio", pname, " not found, use initPortf() to create a new portfolio"))
- if (!inherits(Portfolio, "portfolio"))
- stop("Portfolio", pname, "passed is not the name of a portfolio object.")
-
-
-
- ## FIXME: need a way to define symbols for each portfolio
- if(missing(Symbols)) symbols <- ls(Portfolio$symbols)
- else symbols <- Symbols
-
- ## Trade Statistics
- for (symbol in symbols){
- txn <- Portfolio$symbols[[symbol]]$txn
- posPL <- Portfolio$symbols[[symbol]]$posPL
- posPL <- posPL[-1,]
-
- PL.gt0 <- txn$Net.Txn.Realized.PL[txn$Net.Txn.Realized.PL > 0]
- PL.lt0 <- txn$Net.Txn.Realized.PL[txn$Net.Txn.Realized.PL < 0]
- PL.ne0 <- txn$Net.Txn.Realized.PL[txn$Net.Txn.Realized.PL != 0]
-
- if(length(PL.ne0) == 0)
- {
- # apply.daily will crash
- next
- }
-
- DailyPL <- apply.daily(PL.ne0,sum)
- AvgDailyPL <- mean(DailyPL)
- MedDailyPL <- median(DailyPL)
- StdDailyPL <- sd(as.numeric(as.vector(DailyPL)))
-
- switch(use,
- txns = {
- #moved above for daily stats for now
- },
- trades = {
- trades <- perTradeStats(pname,symbol)
- PL.gt0 <- trades$Net.Trading.PL[trades$Net.Trading.PL > 0]
- PL.lt0 <- trades$Net.Trading.PL[trades$Net.Trading.PL < 0]
- PL.ne0 <- trades$Net.Trading.PL[trades$Net.Trading.PL != 0]
- }
- )
- if(!length(PL.ne0)>0)next()
-
- GrossProfits <- sum(PL.gt0)
- GrossLosses <- sum(PL.lt0)
- ProfitFactor <- abs(GrossProfits/GrossLosses)
-
- AvgTradePL <- mean(PL.ne0)
- MedTradePL <- median(PL.ne0)
- StdTradePL <- sd(as.numeric(as.vector(PL.ne0)))
-
- NumberOfTxns <- nrow(txn)-1
- NumberOfTrades <- length(PL.ne0)
-
- PercentPositive <- (length(PL.gt0)/length(PL.ne0))*100
- PercentNegative <- (length(PL.lt0)/length(PL.ne0))*100
-
- MaxWin <- max(txn$Net.Txn.Realized.PL)
- MaxLoss <- min(txn$Net.Txn.Realized.PL)
-
- AvgWinTrade <- mean(PL.gt0)
- MedWinTrade <- median(PL.gt0)
- AvgLossTrade <- mean(PL.lt0)
- MedLossTrade <- median(PL.lt0)
-
- AvgWinLoss <- AvgWinTrade/-AvgLossTrade
- MedWinLoss <- MedWinTrade/-MedLossTrade
-
- Equity <- cumsum(posPL$Net.Trading.PL)
- if(!nrow(Equity)){
- warning('No Equity rows for',symbol)
- next()
- }
- TotalNetProfit <- last(Equity)
- if(is.na(TotalNetProfit)) {
- warning('TotalNetProfit NA for',symbol)
- next()
- }
- Equity.max <- cummax(Equity)
- MaxEquity <- max(Equity)
- MinEquity <- min(Equity)
- EndEquity <- last(Equity)
- names(EndEquity) <-'End.Equity'
- if(EndEquity!=TotalNetProfit && last(txn$Pos.Qty)==0) {
- warning('Total Net Profit for',symbol,'from transactions',TotalNetProfit,'and cumulative P&L from the Equity Curve', EndEquity, 'do not match. This can happen in long/short portfolios.')
- message('Total Net Profit for',symbol,'from transactions',TotalNetProfit,'and cumulative P&L from the Equity Curve', EndEquity, 'do not match. This can happen in long/short portfolios.')
-
- }# if we're flat, these numbers should agree
- #TODO we should back out position value if we've got an open position and double check here....
-
- MaxDrawdown <- -max(Equity.max - Equity)
- ProfitToMaxDraw <- -TotalNetProfit / MaxDrawdown
- names(ProfitToMaxDraw) <- 'Profit.To.Max.Draw'
-
- #TODO add skewness, kurtosis, and positive/negative semideviation if PerfA is available.
-
- tmpret <- data.frame(Portfolio=pname,
- Symbol = symbol,
- Num.Txns = NumberOfTxns,
- Num.Trades = NumberOfTrades,
- Total.Net.Profit = TotalNetProfit,
- Avg.Trade.PL = AvgTradePL,
- Med.Trade.PL = MedTradePL,
- Largest.Winner = MaxWin,
- Largest.Loser = MaxLoss,
- Gross.Profits = GrossProfits,
- Gross.Losses = GrossLosses,
- Std.Dev.Trade.PL = StdTradePL,
- Percent.Positive = PercentPositive,
- Percent.Negative = PercentNegative,
- Profit.Factor = ProfitFactor,
- Avg.Win.Trade = AvgWinTrade,
- Med.Win.Trade = MedWinTrade,
- Avg.Losing.Trade = AvgLossTrade,
- Med.Losing.Trade = MedLossTrade,
- Avg.Daily.PL = AvgDailyPL,
- Med.Daily.PL = MedDailyPL,
- Std.Dev.Daily.PL = StdDailyPL,
- Max.Drawdown = MaxDrawdown,
- Profit.To.Max.Draw = ProfitToMaxDraw,
- Avg.WinLoss.Ratio = AvgWinLoss,
- Med.WinLoss.Ratio = MedWinLoss,
- Max.Equity = MaxEquity,
- Min.Equity = MinEquity,
- End.Equity = EndEquity)
- rownames(tmpret) <- symbol
- ret <- rbind(ret,tmpret)
- } # end symbol loop
- } # end portfolio loop
- return(ret)
-}
-
-#' generate daily Transaction Realized or Equity Curve P&L by instrument
-#'
-#' designed to collate information for high frequency portfolios
-#'
-#' @aliases dailyEqPL
-#' @param Portfolios portfolio string
-#' @param Symbols character vector of symbol strings
-#' @param drop.time remove time component of POSIX datestamp (if any), default TRUE
-#' @author Brian G. Peterson
-#' @seealso tradeStats
-#' @export
-dailyTxnPL <- function(Portfolios, Symbols, drop.time=TRUE)
-{
- ret <- NULL
- for (Portfolio in Portfolios){
- ## Error Handling Borrowed from getPortfolio
- pname <- Portfolio
- if (!grepl("portfolio\\.", pname))
- Portfolio <- try(get(paste("portfolio", pname, sep = "."), envir = .blotter), silent=TRUE)
- else Portfolio <- try(get(pname, envir = .blotter), silent=TRUE)
- if (inherits(Portfolio, "try-error"))
- stop(paste("Portfolio", pname, " not found, use initPortf() to create a new portfolio"))
- if (!inherits(Portfolio, "portfolio"))
- stop("Portfolio", pname, "passed is not the name of a portfolio object.")
-
-
-
- ## FIXME: need a way to define symbols for each portfolio
- if(missing(Symbols)) symbols <- ls(Portfolio$symbols)
- else symbols <- Symbols
-
- ## Trade Statistics
- for (symbol in symbols){
- txn <- Portfolio$symbols[[symbol]]$txn
- txn <- txn[-1,] # remove initialization row
-
- PL.ne0 <- txn$Net.Txn.Realized.PL[txn$Net.Txn.Realized.PL != 0]
- if(!nrow(PL.ne0)){
- warning('No P&L rows for',symbol)
- next()
- }
- DailyPL <- apply.daily(PL.ne0,sum)
- colnames(DailyPL) <- paste(symbol,'DailyTxnPL',sep='.')
- if(is.null(ret)) ret=DailyPL else ret<-cbind(ret,DailyPL)
-
- } # end symbol loop
- } # end portfolio loop
- ret <- apply.daily(ret,colSums,na.rm=TRUE)
- if(drop.time) index(ret) <- as.Date(index(ret))
- return(ret)
-}
-
-#' @rdname dailyTxnPL
-#' @export
-dailyEqPL <- function(Portfolios, Symbols, drop.time=TRUE)
-{
- ret <- NULL
- for (Portfolio in Portfolios){
- ## Error Handling Borrowed from getPortfolio
- pname <- Portfolio
- if (!grepl("portfolio\\.", pname))
- Portfolio <- try(get(paste("portfolio", pname, sep = "."), envir = .blotter), silent=TRUE)
- else Portfolio <- try(get(pname, envir = .blotter), silent=TRUE)
- if (inherits(Portfolio, "try-error"))
- stop(paste("Portfolio", pname, " not found, use initPortf() to create a new portfolio"))
- if (!inherits(Portfolio, "portfolio"))
- stop("Portfolio", pname, "passed is not the name of a portfolio object.")
-
-
-
- ## FIXME: need a way to define symbols for each portfolio
- if(missing(Symbols)) symbols <- ls(Portfolio$symbols)
- else symbols <- Symbols
-
- ## Trade Statistics
- for (symbol in symbols){
- posPL <- Portfolio$symbols[[symbol]]$posPL
- posPL <- posPL[-1,] # remove initialization row
-
- Equity <- cumsum(posPL$Net.Trading.PL)
- if(!nrow(Equity)){
- warning('No P&L rows for',symbol)
- next()
- }
-
- #DailyPL <- apply.daily(Equity,last)
- DailyPL <- apply.daily(posPL$Net.Trading.PL,colSums)
- colnames(DailyPL) <- paste(symbol,'DailyEndEq',sep='.')
- if(is.null(ret)) ret=DailyPL else ret<-cbind(ret,DailyPL)
-
- } # end symbol loop
- } # end portfolio loop
- ret <- apply.daily(ret,colSums,na.rm=TRUE)
- if(drop.time) index(ret) <- as.Date(index(ret))
- return(ret)
-}
-
-#' @rdname tradeStats
-#' @export
-dailyStats <- function(Portfolios,use=c('equity','txns'))
-{
- use=use[1] #take the first value if the user didn't specify
- switch (use,
- Eq = , Equity =, cumPL = {
- dailyPL <- dailyEqPL(Portfolios)
- },
- Txns =, Trades = {
- dailyPL <- dailyTxnPL(Portfolios)
- }
- )
-
- dailyFUN <- function (x){
- x<-t(t(x))
- PL.gt0 <- x[x > 0]
- PL.lt0 <- x[x < 0]
- PL.ne0 <- x[x != 0]
-
- TotalNetProfit <- sum(x)
-
- GrossProfits <- sum(PL.gt0)
- GrossLosses <- sum(PL.lt0)
- ProfitFactor <- abs(GrossProfits/GrossLosses)
-
- AvgDayPL <- as.numeric(mean(PL.ne0))
- MedDayPL <- as.numeric(median(PL.ne0))
- StdDayPL <- as.numeric(sd(PL.ne0))
-
- #NumberOfDays <- nrow(txn)
- WinDays <- length(PL.gt0)
- LossDays <- length(PL.lt0)
- PercentPositive <- (length(PL.gt0)/length(PL.ne0))*100
- PercentNegative <- (length(PL.lt0)/length(PL.ne0))*100
-
- MaxWin <- max(x)
- MaxLoss <- min(x)
-
- AvgWinDay <- as.numeric(mean(PL.gt0))
- MedWinDay <- as.numeric(median(PL.gt0))
- AvgLossDay <- as.numeric(mean(PL.lt0))
- MedLossDay <- as.numeric(median(PL.lt0))
-
- AvgWinLoss <- AvgWinDay/-AvgLossDay
- MedWinLoss <- MedWinDay/-MedLossDay
-
- AvgDailyPL <- as.numeric(mean(PL.ne0))
- MedDailyPL <- as.numeric(median(PL.ne0))
- StdDailyPL <- as.numeric(sd(PL.ne0))
-
- Equity <- cumsum(x)
- Equity.max <- cummax(Equity)
- MaxEquity <- max(Equity)
- MinEquity <- min(Equity)
- EndEquity <- as.numeric(last(Equity))
- MaxDrawdown <- -max(Equity.max - Equity)
- ProfitToMaxDraw <- -TotalNetProfit / MaxDrawdown
-
- tmpret <- data.frame(
- Total.Net.Profit = TotalNetProfit,
- Total.Days = WinDays+LossDays,
- Winning.Days = WinDays,
- Losing.Days = LossDays,
- Avg.Day.PL = AvgDayPL,
- Med.Day.PL = MedDayPL,
- Largest.Winner = MaxWin,
- Largest.Loser = MaxLoss,
- Gross.Profits = GrossProfits,
- Gross.Losses = GrossLosses,
- Std.Dev.Daily.PL = StdDayPL,
[TRUNCATED]
To get the complete diff run:
svnlook diff /svnroot/blotter -r 1525
More information about the Blotter-commits
mailing list