[R-SIG-Finance] loops or other ooerations

Shane Butler shane.butler at gmail.com
Sun Nov 14 02:57:41 CET 2010


You could use logic like this:
<http://blog.fosstrading.com/2009/07/david-varadis-rsi2-alternative.html?showComment=1248458995203#c7802594037487260774>

Shane


On Sat, Nov 13, 2010 at 7:23 AM, Stephen Choularton
<stephen at organicfoodmarkets.com.au> wrote:
>
> Hi
>
>  I am trying to write some code to backtest some spread trading ideas. I
> have got this far:
>
> library(xts)
> library(quantmod)
> library(foreach)
>
>
>
> getCombined <- function(sym1, sym2, dateFilter='::')
> {
>  # Grab historical data for both symbols
>  one <- getSymbols(sym1, auto.assign=FALSE)
>  two <- getSymbols(sym2, auto.assign=FALSE)
>
>  # Give columns more usable names
>  colnames(one) <- c('Open', 'High', 'Low', 'Close', 'Volume', 'Adjusted')
>  colnames(two) <- c('Open', 'High', 'Low', 'Close', 'Volume', 'Adjusted')
>
>  # Build combined object
>  return(merge(one$Close, two$Close, all=FALSE)[dateFilter])
> }
>
>
> sym1 <- 'CBA.AX'
> sym2 <- 'NAB.AX'
>
>
>
> spread <- getCombined(sym1, sym2)
>
> chartSeries(spread, type='line',theme=chartTheme('white'),TA=NULL)
>
> price <- spread$Close - spread$Close.1
>
> m <- rollapply(price, 20, mean)
> sd.2 <- rollapply(price, 20, sd)
> upper.boundary <- m + sd.2
> lower.boundary <- m - sd.2
> spread.data <- merge(price$Close, m$Close, upper.boundary$Close,
> lower.boundary$Close, all=FALSE)
> # Give columns more usable names
> colnames(spread.data) <- c('Close', 'Mean', 'Upper.Boundary',
> 'Lower.Boundary')
>
> so now I have my time series and I want to iterate over it with rules like:
>
> 1. If the price exceeds 2 x standard deviation  and then returns below sell
> the spread
> 2. If I'm short and the price becomes smaller than the average buy the
> spread
> 3. and so on
>
> In other programming languages (except prolog which favors recursion) I
> guess I would write some type of loop and iterate over the data but some of
> these R functions seem to achieve wonderful results so I thought I would
> post this to see if a loop was the way to go or if there was something more
> elegant.
>
> Any help most welcome.
> --
> Stephen Choularton Ph.D., FIoD
>
> _______________________________________________
> R-SIG-Finance at stat.math.ethz.ch mailing list
> https://stat.ethz.ch/mailman/listinfo/r-sig-finance
> -- Subscriber-posting only. If you want to post, subscribe first.
> -- Also note that this is not the r-help list where general R questions
> should go.
>



More information about the R-SIG-Finance mailing list