Showing posts with label quantstrat. Show all posts
Showing posts with label quantstrat. Show all posts

Monday, September 26, 2011

ttrTests: Its Great Thesis and Incredible Potential

I stumbled on the ttrTests R package as mentioned in my post ttrTests Experimentation.  I did not recognize its potential until I spent much more time absorbing the basis of the package—David St. John’s thesis Technical Analysis Based on Moving Average Convergence and Divergence.  Since the title specifically addresses MACD, which I have had little luck implementing, I dismissed much of the content.  However, the power of the thesis extends well beyond MACD to all systematic methods and describes tests to ensure luck is not the source of a system’s returns.  In the package documentation, there is a summary of the 5 main tests:

“Contains five major tests supported by other functions: Did the TTR strategy outperform a benchmark in the past data? Is the excess return significant, using bootstrapping to construct a confidence interval? Is the excess return explained by data snooping? Is the ’good’ choice of parameters robust across sub-samples? Is this robustness significant, using bootstrapping to construct a confidence interval?”

The tests expose luck, data snooping, trading costs, and parameter persistence across both degrees of freedom and subperiods.  I look forward to documenting its power in my blog and also potentially working with the author to include in other R packages such as quantstrat.

Since I am running out of time, I first want to apply each of the tests to MACD in the same style as the package documentation and the thesis paper, but this time on a xts DJI object gathered through getSymbols rather than the spData provided with the package.

The output from the tests is very cumbersome, but I hope this set of examples will help provide a flavor for the package and its powerful tests.  In my next couple of posts, I will run each test in much further detail on my basic custom CUD indicator and try to get the cumbersome output in a far more digestible and graphical format.

R code (click to download from Google Docs):

require(ttrTests)
require(quantmod)   #get Dow Jones Industrials from Yahoo! Finance
getSymbols("^DJI",from="1896-01-01",to=Sys.Date())
#convert closing price to vector format which works best with ttrTests
DJI.vector <- as.vector(DJI[,4])   #using the defaults as mentioned in the thesis paper on MACD
#show each of the tests in order of their mention   #quotes are from ttrTests package documentation
#"compares the performance of the TTR with some benchmark"
returnStats(DJI.vector)   #"constructs a confidence interval for this performance"
#"and gives a p-value for the excess return observed in (1)."
nullModel(DJI.vector)   #"constructs a p-value for the ’best’ choice"
#"of parameters within a given domain"
dataSnoop(DJI.vector,bSamples=3,test="RC")
dataSnoop(DJI.vector,bSamples=3,test="SPA")   #"asks whether or not good choices of parameters"
#"were robust across different time periods"
#chose 8 since data is from 1928 will approximate by decade
subperiods(DJI.vector, periods=8)   #and my favorite of all
#"tests if the persistence measure from subperiods()"
#"is statistically significant"
#this takes the longest (about 10 minutes on my i7 laptop)
paramPersist(DJI.vector)

Created by Pretty R at inside-R.org

Tuesday, July 5, 2011

A Quantstrat to Build On Part 6

THIS IS NOT INVESTMENT ADVICE.  ACTING ON THIS MAY LOSE LOTS OF MONEY.

In A Quantstrat to Build on Part 5, I promised some performance reporting on quantstrat portfolios, but then in REIT Momentum in Quantstrat, I discovered it is not nearly as easy as I thought.  With some help from experts (please tell me if you would like me to mention you by name), I found a couple of ways to accomplish this crucial component of systems development.  We’ll compare the original simple CUD system with buy and hold but this time using the osFUN option in our entry rule to buy an amount equal to the proceeds from the previous trade.  Minimizing drawdown on the way down allows potentially larger trade quantities on the way back up.

From TimelyPortfolio
From TimelyPortfolio
From TimelyPortfolio
From TimelyPortfolio
From TimelyPortfolio
From TimelyPortfolio

R code (click to download):

#thanks so much to the developers of quantstrat
#99% of this code comes from the demos in the quantstrat package   #in this I use osFun to size orders to ending equity
#for a more appropriate comparison to buy hold   #takes longer than I would like but is acceptable
#another way to accomplish testing and reporting
#is use 1 for orderqty and then generate return series
#with this as signal   #however despite extra time I like to see growth in order size
#with performance
#makes a very valid point for drawdown reduction     require(quantstrat)
require(PerformanceAnalytics)   #now let's define our silly countupdown function
CUD <- function(price,n) {
#CUD takes the n-period sum of 1 (up days) and -1 (down days)
temp <- runSum(ifelse(ROC(price,1,type="discrete") > 0,1,-1),n)
colnames(temp) <- "CUD"
temp
}   BuyHold <- function(price,periodtobuy) {
#just enter true (1) the period specified as buy and hold
#for the remainder
temp <- as.xts(rep(0,NROW(price)),order.by=index(price))
colnames(temp) <- "BuyHold"
temp[periodtobuy,1]<-1
temp
}   osFillErUp <- function (data, timestamp, orderqty, ordertype, orderside, portfolio, symbol, ruletype, ..., orderprice)
{   #get date in usable xts format
datePos <- format(timestamp,"%Y-%m-%d")
#update the portfolio to date of trade rule
updatePortf(Portfolio=portfolio,Symbol=symbol,Dates=paste('::',datePos,sep=''))
portf <- getPortfolio(portfolio)
#get price of symbol for the date of trade rule
price <- getPrice(get(symbol))[datePos]
#get amount generated from the last trade
#best way for me to overcome lack of cumulative p/l for portfolio by symbol
#all this logic is at the account level
trades <- getOrderBook(portfolio)[[portfolio]][[symbol]]
#if first trade, just use order quantity specified
#if not get order quantity equal to
#last trade proceeds divided by price of symbol at trade date
if(NROW(trades)>1) {
trades <- trades[NROW(trades)]
endEq <- as.numeric(trades$Order.Qty) * as.numeric(trades$Order.Price)
# orderqty <- abs(endEq/price)
orderqty <- abs(floor(endEq/price))
}
#return the new orderqty
osFillErUp <- orderqty
}     try(rm("order_book.CUD",pos=.strategy),silent=TRUE)
try(rm("order_book.BuyHold",pos=.strategy),silent=TRUE)
try(rm("account.CUD","portfolio.CUD",pos=.blotter),silent=TRUE)
try(rm("account.BuyHold","portfolio.BuyHold",pos=.blotter),silent=TRUE)
try(rm("port.st","symbols","symbol","stratCUD","initDate","initEq",
'start_t','end_t','num_periods'),silent=TRUE)   #specify this for the rolling periods to use for our signal
num_periods=50   # Initialize a strategy object
stratCUD <- strategy("CUD")   # Add an indicator
stratCUD <- add.indicator(strategy = stratCUD, name = "CUD",
arguments = list(price = quote(Cl(mktdata)),n=num_periods),
label="CUD")   # enter when CUD > 0
stratCUD <- add.signal(strategy = stratCUD, name="sigThreshold",
arguments = list(threshold=0, column="CUD",relationship="gte", cross=TRUE),
label="CUD.gte.0")
# exit when CUD < 0
stratCUD <- add.signal(strategy = stratCUD, name="sigThreshold",
arguments = list(threshold=0, column="CUD",relationship="lt",cross=TRUE),
label="CUD.lt.0")   stratCUD <- add.rule(strategy = stratCUD, name='ruleSignal',
arguments = list(sigcol="CUD.gte.0", sigval=TRUE, orderqty=100, ordertype='market',
orderside='long', pricemethod='market', replace=FALSE, osFUN='osFillErUp'), type='enter', path.dep=TRUE)
stratCUD <- add.rule(strategy = stratCUD, name='ruleSignal',
arguments = list(sigcol="CUD.lt.0", sigval=TRUE, orderqty='all',
ordertype='market', orderside='long', pricemethod='market', replace=FALSE),
type='exit', path.dep=TRUE)   #Initialize a buy/hold strategy object
stratBuyHold <- strategy("BuyHold")
stratBuyHold <- add.indicator(strategy = stratBuyHold, name = "BuyHold",
arguments = list(price = quote(Cl(mktdata)),periodtobuy=num_periods),
label = "BuyHold")
stratBuyHold <- add.rule(strategy=stratBuyHold, name='ruleSignal',
arguments = list(sigcol="BuyHold",sigval=TRUE,orderqty=100,ordertype='market',
orderside='long', pricemethod='market', replace=FALSE), type='enter', path.dep=TRUE)     currency("USD")
symbols = c("GSPC","GDAXI")
for (symbol in symbols) {
stock(symbol, currency="USD",multiplier=1)
#use paste with ^ to get index data
getSymbols(paste("^",symbol,sep=""),adjust=T,from="1900-12-31")
assign(symbol,to.weekly(get(symbol)))
}   initDate='1949-12-31'
initEq=1000000
port.st<-'CUD' #use a string here for easier changing of parameters and re-trying
port.buyhold <- 'BuyHold'   initPortf(port.st, symbols=symbols, initDate=initDate)
initAcct(port.st, portfolios=port.st, initDate=initDate, initEq=initEq)
initOrders(portfolio=port.st, initDate=initDate)   initPortf(port.buyhold, symbols=symbols, initDate=initDate)
initAcct(port.buyhold, portfolios=port.buyhold, initDate=initDate,, initEq=initEq)
initOrders(portfolio=port.buyhold, initDate=initDate)   print("setup completed")   # Process the indicators and generate trades
start_t<-Sys.time()
out<-try(applyStrategy(strategy=stratCUD , portfolios=port.st ) )
end_t<-Sys.time()
print("Strategy Loop:")
print(end_t-start_t)   # Process buy and hold strategy
start_t<-Sys.time()
out<-try(applyStrategy(strategy=stratBuyHold , portfolios=port.buyhold ) )
end_t<-Sys.time()
print("Strategy Loop:")
print(end_t-start_t)   start_t<-Sys.time()
updatePortf(Portfolio=port.st,Dates=paste('::',as.Date(Sys.time()),sep=''))
updatePortf(Portfolio=port.buyhold,Dates=paste('::',as.Date(Sys.time()),sep=''))
end_t<-Sys.time()
print("trade blotter portfolio update:")
print(end_t-start_t)   # hack for new quantmod graphics, remove later
themelist<-chart_theme()
themelist$col$up.col<-'lightgreen'
themelist$col$dn.col<-'pink'   for(symbol in symbols){
#dev.new()
#chart.Posn(Portfolio=port.st,Symbol=symbol,theme=themelist)
#add the CUD indicator to the bottom of the chart
#jpeg(filename=paste(symbol," Reconcile.jpg",sep=""),quality=100,
# width=6.5, height = 6.5, units="in",res=96)
chart.Reconcile(port.buyhold,port.st,symbol)
plot(add_TA(CUD(get(symbol)[,4],n=num_periods)))
#dev.off()
}   #tradeStats(port.st)   #backwards way to get returns
#again to bypass account p/l logic
port <- getPortfolio(port.st)
for(symbol in symbols) {
#get posPL for the symbol in the portfolio
posPLTable <- port$symbols[[symbol]][["posPL"]]
#easier this way to get ROC for each day when position is held (Pos.Qty > 0)
#rets <- lag(ifelse(posPLTable$Pos.Qty>0,1,0),k=1)*ROC(get(symbol)[,4],type="discrete",n=1)
#the previous commented method is not exactly correct
#since we can only hold integer positions
#to account for this difference we can get
rets <- posPLTable$Gross.Trading.PL/lag(posPLTable$Pos.Value,k=1)
rets[is.na(rets)] <- 0
rets[which(rets[,1]==Inf)] <- 0
rets[which(rets[,1]==-Inf)] <- 0
retCompare <- merge(rets,ROC(get(symbol)[,4],type="discrete",n=1))
colnames(retCompare) <- c(paste(symbol," CUD System",sep=""),symbol)
#jpeg(filename=paste(symbol," Performance.jpeg",sep=""),quality=100,width=6.5, height = 6.5,
# units="in",res=96)
charts.PerformanceSummary(retCompare,ylog=TRUE,
colorset=c("black","gray70"),
main = paste(symbol," CUD System and Index
Performance Summary"
,sep=""))
#dev.off()
#jpeg(filename=paste(symbol," Capture.jpeg",sep=""),quality=100,width=6.5, height = 6.5,
# units="in",res=96)
chart.CaptureRatios(retCompare[,1],retCompare[,2],
main = paste(symbol," CUD System and Index
Capture Ratios"
,sep=""))
#dev.off()
}

Created by Pretty R at inside-R.org

Tuesday, June 14, 2011

REIT Momentum in Quantstrat

I took a short break from quantstrat to do some REIT analysis REITs for Everybody Might Now Mean REITs for Nobody.  Now let’s link the two by incorporating The Aleph Blog momentum bucket strategy in quantstrat.

From TimelyPortfolio

In all this, I have discovered significant weaknesses in my understanding of position sizing in quantstrat.  For testing, I would like to be able to size my position at entry to be (Account Equity at entry)/(Price of symbol).  However, it appears that the account equity calculation for each period is not made until after order entry.  Please let me know if I am missing something.  Here is my hacked workaround for some performance reporting and analysis.

From TimelyPortfolio

R code (click to download):

require(quantstrat)
require(PerformanceAnalytics)   # clear out evironment
# much cleaner thanks to Guy Yollin
rm(list=ls())
try(rm(list=ls(pos=.blotter),pos=.blotter),silent=TRUE)
try(rm(list=ls(pos=.strategy),pos=.strategy),silent=TRUE)
try(rm(list=ls(pos=.instrument),pos=.instrument),silent=TRUE)   #set up bucketing function to generate signal
bucket_signal <- function(price,nbuckets,nper) {
momscore <- price/runMean(price,n=nper)-1
breaks <- quantile(momscore, probs = seq(0, 1, 1/nbuckets),na.rm=TRUE)
buckets <- cut(momscore, breaks=breaks, labels=FALSE)
signal <- as.xts(buckets,order.by=index(price))
colnames(signal) <- "bucket_signal"
signal[is.na(signal),1] <- 0
signal
}   #get NAREIT data
#I like NAREIT since I get back to 1971
#see how to get it in previous post
#http://timelyportfolio.blogspot.com/2011/06/reits-for-everybody-might-now-mean.html
#much easier though to get Wilshire REIT since 1977 from FRED
#also it is daily instead of monthly
#i'll use this for simplicity
stock.str <- "WILLREITIND"
getSymbols(stock.str,src="FRED")
#get OHLC all filled with monthly closes
assign(stock.str,to.monthly(get(stock.str)))
index(WILLREITIND) <- as.Date(index(WILLREITIND))
#set up currency and stock
currency('USD')
stock(stock.str,currency='USD',multiplier=1)
initDate='1976-12-31'
initEq=coredata(get(stock.str)[1,4])
tradeSize = 1   #name strategy, account, and portfolio same
name_all <- "momBuckets"
#set up strategy
strat <- strategy(name_all)   #set up portfolio and account
initPortf(name=name_all,symbols=stock.str,initDate=initDate)
initAcct(name=name_all,portfolios=name_all,initDate=initDate,initEq=initEq)
initOrders(portfolio=name_all,initDate=initDate)   #set up indicator
#do bucket indicator
strat <- add.indicator(strategy = strat, name = "bucket_signal",
arguments=list(price=quote(Cl(mktdata)),nbuckets=5,nper=10),
label="bucket_signal")
#set up signal
strat <- add.signal(strategy = strat, name="sigThreshold",
arguments = list(threshold=3,column="bucket_signal",
relationship="gte",cross=TRUE),
label="bucket.gte.3")
strat <- add.signal(strategy = strat, name="sigThreshold",
arguments = list(threshold=3,column="bucket_signal",
relationship="lt",cross=TRUE),
label="bucket.lt.3")
#set up rule
strat <- add.rule(strategy=strat,name="ruleSignal",
arguments = list(sigcol="bucket.gte.3", sigval=TRUE,
ordertype='market',orderqty=tradeSize,
orderside='long', pricemethod='market', replace=FALSE),
type='enter', path.dep=TRUE)
strat <- add.rule(strategy=strat,name="ruleSignal",
arguments = list(sigcol="bucket.lt.3", sigval=TRUE,
orderqty="all", ordertype='market',
orderside='long', pricemethod='market', replace=FALSE),
type='exit', path.dep=TRUE)   #run strategy and portfolio
out <- applyStrategy(strategy=strat,portfolios=name_all)
#break up steps of applyStrategy for debugging
#strat.ind <- applyIndicators(strategy=strat,mktdata=get(stock.str))
#strat.sig <- applySignals(strategy=strat,indicators=strat.ind)
#applyRules(strategy=strat,portfolio=name_all,symbol=stock.str,
# indicators=strat.in,Dates=NULL,signals=strat.sig,mktdata=mktdata,path.dep=TRUE)     updatePortf(Portfolio=name_all,Dates=paste('::',as.Date(Sys.time()),sep=''))
#analyze performance
chart.Posn(Portfolio=name_all,Symbol=stock.str)   #unfortunately I do not know yet how to size position
#on each entry to be CurrentEquity/price
#so the compare really is not worthwhile
#this would be the preferred way
#retCompare <- merge(PortfReturns(Account=name_all)/100,
# ROC(get(stock.str)[,4],n=1,type="discrete"))
#charts.PerformanceSummary(retCompare)     #could do buy/hold comparison similar to
#blog post A Quantstrat to Build On Part 4
#but still not really applicable
#so I will hack this way
#but of course this really defeats the purpose of quantstrat
positions <- getPortfolio(name_all)$symbols$WILLREITIND$posPL[,"Pos.Qty"]
#position of 1 will get return and position of 0 will get nothing
ret <- lag(positions,k=1)*ROC(get(stock.str)[,4],n=1,type="discrete")
retCompare <- merge(ret, ROC(get(stock.str)[,4],n=1,type="discrete"))
colnames(retCompare) <- c("Strategy","Wilshire REIT")
charts.PerformanceSummary(retCompare,ylog=TRUE, cex.legend=1.25,
main="Wilshire REIT with Aleph Blog Momentum",
colorset=c("cadetblue","darkolivegreen3"))

Created by Pretty R at inside-R.org

Thursday, June 9, 2011

A Quantstrat to Build on Part 5

Another iteration of the quantstrat system but this time with a sum of standard deviations instead of simple count and then some comparison charts.  Thanks for the comments and I welcome many more.  In my head and it seems like in others based on comments, we should assign higher importance to extreme days, so extreme days should get a stronger vote.  However, after a little experimenting, I found it very difficult to capitalize on that notion.  As usual, simpler is better as suggested in all my experience and also this recent Science News article.

From TimelyPortfolio
From TimelyPortfolio

Unfortunately I ran out of time to add all the system comparison stats and charts, so to get a post out today, I will stop here and resume with that tomorrow.

R code (click to download):

#thanks so much to the developers of quantstrat
#99% of this code comes from the demos in the quantstrat package   #in this I add a variation of the CUD portfolio
#with standard deviations and compare the CUD
#and the new CUDsd   require(quantstrat)   #now let's define our silly countupdown function
CUD <- function(price,n) {
#CUD takes the n-period sum of 1 (up days) and -1 (down days)
temp <- runSum(ifelse(ROC(price,1,type="discrete") > 0,1,-1),n)
colnames(temp) <- "CUD"
temp
}   #since I've had some very prescient comments
#about standard deviations I'll go ahead and try an sd sum system
CUDsd <- function(price,nsd,nsum) {
#CUDsd takes the n-period sum of standard deviations
#feel free to substitute runMAD with runSD if you would like
temp <- ROC(price,1,type="discrete")/runMAD(ROC(price,1,type="discrete"),n=nsd)
#bollinger band style sum - uncomment next line
#temp <- (price-runMedian(price,n=10)-1)/runMAD(ROC(price,1,type="discrete"),n=nsd)
#doesn't help but if you want to experiment with summing only a n*sd move
#uncomment and mess with the numbers
#temp <- ifelse(abs(temp)>1,temp,0)
temp <- runSum(temp,n=nsum)
colnames(temp) <- "CUDsd"
temp
}   #I added this BuyHold as an example; see previous post
#quantstrat version 4 for details
#here is the remnant function
#BuyHold <- function(price,periodtobuy) {
# #just enter true (1) the period specified as buy and hold
# #for the remainder
# temp <- as.xts(rep(0,NROW(price)),order.by=index(price))
# colnames(temp) <- "BuyHold"
# temp[periodtobuy,1]<-1
# temp
#}   try(rm("order_book.CUD",pos=.strategy),silent=TRUE)
try(rm("order_book.CUDsd",pos=.strategy),silent=TRUE)
try(rm("account.CUD","portfolio.CUD",pos=.blotter),silent=TRUE)
try(rm("account.CUDsd","portfolio.CUDsd",pos=.blotter),silent=TRUE)
try(rm("port.st","port.stsd","symbols","symbol","stratCUD","stratCUDsd",
"initDate","initEq",'start_t','end_t','num_periods'),silent=TRUE)   #specify this for the rolling periods to use for our signal
num_periods=50
#specify these for the CUDsd function
#I separated the sd period from the sum period
#if anyone wants to fool around with the degrees of freedom
num_periods_sd=50
num_periods_sum=50   # Initialize a strategy object
stratCUD <- strategy("CUD")
# Add an indicator
stratCUD <- add.indicator(strategy = stratCUD, name = "CUD",
arguments = list(price = quote(Cl(mktdata)),n=num_periods),
label="CUD")
# enter when CUD > 0
stratCUD <- add.signal(strategy = stratCUD, name="sigThreshold",
arguments = list(threshold=0, column="CUD",relationship="gte", cross=TRUE),
label="CUD.gte.0")
# exit when CUD < 0
stratCUD <- add.signal(strategy = stratCUD, name="sigThreshold",
arguments = list(threshold=0, column="CUD",relationship="lt",cross=TRUE),
label="CUD.lt.0")
stratCUD <- add.rule(strategy = stratCUD, name='ruleSignal',
arguments = list(sigcol="CUD.gte.0", sigval=TRUE, orderqty=1000, ordertype='market',
orderside='long', pricemethod='market', replace=FALSE), type='enter', path.dep=TRUE)
stratCUD <- add.rule(strategy = stratCUD, name='ruleSignal',
arguments = list(sigcol="CUD.lt.0", sigval=TRUE, orderqty='all',
ordertype='market', orderside='long', pricemethod='market', replace=FALSE),
type='exit', path.dep=TRUE)   # Initialize a strategy object for the new CUDsd
stratCUDsd <- strategy("CUDsd")
# Add an indicator
stratCUDsd <- add.indicator(strategy = stratCUDsd, name = "CUDsd",
arguments = list(price = quote(Cl(mktdata)),nsd=num_periods_sd,nsum=num_periods_sum),
label="CUDsd")
# enter when CUDsd > 0
stratCUDsd <- add.signal(strategy = stratCUDsd, name="sigThreshold",
arguments = list(threshold=0, column="CUDsd",relationship="gte", cross=TRUE),
label="CUDsd.gte.0")
# exit when CUDsd < 0
stratCUDsd <- add.signal(strategy = stratCUDsd, name="sigThreshold",
arguments = list(threshold=0, column="CUDsd",relationship="lt",cross=TRUE),
label="CUDsd.lt.0")
stratCUDsd <- add.rule(strategy = stratCUDsd, name='ruleSignal',
arguments = list(sigcol="CUDsd.gte.0", sigval=TRUE, orderqty=1000, ordertype='market',
orderside='long', pricemethod='market', replace=FALSE), type='enter', path.dep=TRUE)
stratCUDsd <- add.rule(strategy = stratCUDsd, name='ruleSignal',
arguments = list(sigcol="CUDsd.lt.0", sigval=TRUE, orderqty='all',
ordertype='market', orderside='long', pricemethod='market', replace=FALSE),
type='exit', path.dep=TRUE)   currency("USD")
symbols = c("GSPC","GDAXI")
for (symbol in symbols) {
stock(symbol, currency="USD",multiplier=1)
#use paste with ^ to get index data
getSymbols(paste("^",symbol,sep=""),adjust=T,from="1900-12-31")
assign(symbol,to.weekly(get(symbol)))
}   initDate='1949-12-31'
initEq=1000000
port.st<-'CUD' #use a string here for easier changing of parameters and re-trying
port.stsd <- 'CUDsd'   initPortf(port.st, symbols=symbols, initDate=initDate, initEq=initEq)
initAcct(port.st, portfolios=port.st, initDate=initDate, initEq=initEq)
initOrders(portfolio=port.st, initDate=initDate)   initPortf(port.stsd, symbols=symbols, initDate=initDate)
initAcct(port.stsd, portfolios=port.stsd, initDate=initDate,, initEq=initEq)
initOrders(portfolio=port.stsd, initDate=initDate)   print("setup completed")   # Process the indicators and generate trades
start_t<-Sys.time()
out<-try(applyStrategy(strategy=stratCUD , portfolios=port.st ) )
end_t<-Sys.time()
print("Strategy Loop:")
print(end_t-start_t)   # Process buy and hold strategy
start_t<-Sys.time()
out<-try(applyStrategy(strategy=stratCUDsd , portfolios=port.stsd ) )
end_t<-Sys.time()
print("Strategy Loop:")
print(end_t-start_t)   start_t<-Sys.time()
updatePortf(Portfolio=port.st,Dates=paste('::',as.Date(Sys.time()),sep=''))
updatePortf(Portfolio=port.stsd,Dates=paste('::',as.Date(Sys.time()),sep=''))
end_t<-Sys.time()
print("trade blotter portfolio update:")
print(end_t-start_t)   # hack for new quantmod graphics, remove later
themelist<-chart_theme()
themelist$col$up.col<-'lightgreen'
themelist$col$dn.col<-'pink'   for(symbol in symbols){
# dev.new()
# chart.Posn(Portfolio=port.stsd,Symbol=symbol,theme=themelist)
# #add the CUD indicator to the bottom of the chart
# plot(add_TA(CUDsd(get(symbol)[,4],nsd=num_periods_sd,nsum=num_periods_sum)))
# plot(add_TA(CUD(get(symbol)[,4],n=num_periods),on=4,col="red"))
dev.new()
chart.Reconcile(port.stsd,port.st,symbol)
plot(add_TA(CUDsd(get(symbol)[,4],nsd=num_periods_sd,nsum=num_periods_sum)))
plot(add_TA(CUD(get(symbol)[,4],n=num_periods),on=5,col="red"))   }   tradeStats(port.st)
tradeStats(port.stsd)

Created by Pretty R at inside-R.org