Thursday, August 11, 2011

System Failure-Maybe it Will Help

I hope everyone is enjoying the market.  After a crazy week personally and 6% intraday swings, I remember why I abandoned day trading.

I often wonder if I should share ideas that do not work as well as I would like.  In this case, I know I have generated an acceptable system in a previous life in Excel, but I cannot remember the details.  So far all the testing and various trails in R have not yielded anything exceptional, but I am sure capable readers can find the secret combination.  Please let me know what you discover.

This idea uses linear models to generate slope and correlation.  Then if slope is positive and correlation high, the system enters.  THIS IS NOT INVESTMENT ADVICE.  THIS CAN LOSE LOTS OF MONEY.

From TimelyPortfolio

R code: (click to download)

require(PerformanceAnalytics)
require(quantmod)   #set this up to get either FRED or Yahoo!Finance
#getSymbols("GSPC",src="FRED")
getSymbols("^GSPC",from="1896-01-01",to=Sys.Date())     GSPC <- to.weekly(GSPC)[,4]
#GSPCmean <- runMean(GSPC,n=20)
#index(GSPC) <- as.Date(index(GSPC))   width = 25
for (i in (width+1):NROW(GSPC)) {
linmod <- lm(GSPC[((i-width):i),1]~index(GSPC[((i-width):i)]))
ifelse(i==width+1,signal <- coredata(linmod$residuals[length(linmod$residuals)]),
signal <- rbind(signal,coredata(linmod$residuals[length(linmod$residuals)])))
ifelse(i==width+1,signal2 <- coredata(linmod$coefficients[2]),
signal2 <- rbind(signal2,coredata(linmod$coefficients[2])))
ifelse(i==width+1,signal3 <- cor(linmod$fitted.values,GSPC[((i-width):i),1]),
signal3 <- rbind(signal3,cor(linmod$fitted.values,GSPC[((i-width):i),1])))
}
signal <- as.xts(signal,order.by=index(GSPC[(width+1):NROW(GSPC)]))
signal2 <- as.xts(signal2,order.by=index(GSPC[(width+1):NROW(GSPC)]))
signal3 <- as.xts(signal3,order.by=index(GSPC[(width+1):NROW(GSPC)]))   price_ret_signal <- merge(GSPC,lag(signal,k=1),
lag(signal2,k=1),lag(signal3,k=1),
ROC(GSPC,type="discrete",n=1))
price_ret_signal[,2] <- price_ret_signal[,2]/price_ret_signal[,1]
price_ret_signal[,3] <- price_ret_signal[,3]/price_ret_signal[,1]   #ret <- ifelse((runMin(price_ret_signal[,3],n=10) >= 0 &
# runSum(price_ret_signal[,2],n=30) >= 0.0) |
# (runMin(price_ret_signal[,3],30) < 0 &
# runSum(price_ret_signal[,2],n=50) >= 0.02),
# 1, 0) * price_ret_signal[,5]
#ret <- ifelse(runSum(price_ret_signal[,3],n=10) >= 0, 1, 0) * price_ret_signal[,5]   ret <- ifelse((runMean(price_ret_signal[,3],n=5) > 0 &
runMean(price_ret_signal[,4],n=5) > 0.25),
1, 0) * price_ret_signal[,5]   retCompare <- merge(ret, price_ret_signal[,5])
colnames(retCompare) <- c("Linear System", "BuyHold")
charts.PerformanceSummary(retCompare,ylog=TRUE,cex.legend=1.2,
colorset=c("black","gray70"),main="GSPC System Return Comparison")

Created by Pretty R at inside-R.org

5 comments:

  1. I thought it might be useful to add to your plot a performance table, something like this as I think the plot only takes you so far.
    This table is from one of my files.
    performance.table <- PortfolioStats(summary.window, log.ret = FALSE)
    > performance.table
    SNL GLOBAL System
    Annualized Return 0.062 0.132
    Total return 0.696 1.959
    Annualized Std Dev 0.233 0.155
    Sharpe (Rf=0%) 0.268 0.853
    DVR 0.702 0.650
    Worst Drawdown 0.728 0.314
    Avg Return (in market) 0.002 0.005
    % Time in Market 0.998 0.998
    % Win NA 0.572
    Avg Win NA 0.016
    % Lose NA 0.428
    Avg Lose NA -0.015

    ReplyDelete
  2. Sorry the table never came out so well:(

    ReplyDelete
  3. @Mickson Any chance you can publish your very useful PortfolioStats function? Thanks.

    ReplyDelete
  4. SP I hope this helps, my assistant wrote this code so I am not going to be much help if there are questions:

    PortfolioStats <- function(x, period = 50, log.ret = FALSE, significance = 3) {
    # Table of annualized return, stdev, sharpe DVR, worst drawdown, avg return (in market), time in market (%)
    #
    # Args:
    # x: Required. A matrix or vector of returns with column names.
    # period: Optional. 50 for daily, 12 for monthly, etc.
    # log.ret: Optional. Select log or arithmetic return as input.
    # significance: optional. number of significant digits for the returned value.
    #
    # Returns: A table of portfolio stats for each asset.

    # Get the column names from the input and converts input into a matrix
    colname <- colnames(x)
    xwin <- as.matrix(subset(x[,2], x[,2]>0))
    avgwin = mean(xwin)
    nwin = length(xwin)
    xlose <- as.matrix(subset(x[,2], x[,2]<0))
    avglose = mean(xlose)
    nlose = length(xlose)
    x <- as.matrix(x)
    maxdd <- matrix(0, 1, ncol(x))
    total.zero <- matrix(0, 1, ncol(x))
    total.ret <- matrix(0, 1, ncol(x))

    # Convert arithmetic returns into log returns if necessary
    if (log.ret == FALSE) {
    x <- log(x + 1)
    }

    # Calculate portfolio stats
    cagr <- CAGR(x, period, log.ret = T)
    trsi <- TRSI(x, period, log.ret = T)
    stdev <- Stdev(x, period, log.ret = T)
    drawdown <- Drawdown(x, period, log.ret = T)
    sharpe <- Sharpe(x, period, log.ret = T)
    dvr <- DVR(x, period, log.ret = T)
    zero.ret <- ifelse(x == 0, 1, 0)

    for (i in 1:ncol(x)) {
    maxdd[, i] <- abs(min(drawdown[, i]))
    total.zero[, i] <- sum(zero.ret[, i])
    total.ret[, i] <- exp(sum(x[, i])) - 1
    }

    # time in market
    total.time <- nrow(x)
    time.in.market <- total.time - total.zero
    percent.in.market <- time.in.market / total.time

    # avg return (in market)
    avg.ret <- total.ret / time.in.market

    # Put results in a table
    result <- rbind(cagr, trsi, stdev, sharpe, dvr, maxdd, avg.ret, percent.in.market, nwin/(nwin+nlose),avgwin, nlose/(nwin+nlose),avglose)
    result <- round(result, significance)


    colnames(result) <- c(colname)
    rownames(result) <- c("Annualized Return", "Total return", "Annualized Std Dev", "Sharpe (Rf=0%)", "DVR", "Worst Drawdown", "Avg Return (in market)", "% Time in Market", "% Win", "Avg Win", "% Lose", "Avg Lose")
    result[9,1] = NA
    result[10,1] = NA
    result[11,1] = NA
    result[12,1] = NA
    return(result)
    }

    ReplyDelete
  5. Unfortunately the following functions are not available (missing code):
    CAGR
    TRSI
    Drawdown
    Sharpe
    DVR

    ReplyDelete