5.3 Loop

We very often want to execute codes multiple times with the same or similar conditions. There are two basic forms of repetition statement in R:

  1. While loop: repeat as long as condition is true,
  2. for loop over integers: repeat for a pre-specific number of times, and
  3. for loop over vector.

5.3.1 While loop

The syntax of while loop is as follows:

while (condition){
  keep doing when condition holds
}

The following example shows how to calculate the sum of all integers from 1 to 10.

n <- 10
i <- 1
sum <- 0
while (i <= n){         # i is the control variable     
  sum <- sum + i        # accumulate i into sum
        i <- i + 1      # increment i by 1
  }

5.3.2 For Loop over integers

Loops that are based on the value of an integer variable. It increases by the same amount each time, and ends when the variable reaches a specified value

The syntax for a for loop is simple.

m <- 1
n <-10
for (i in m:n){
  run as long as condition holds
}

5.3.3 Loop over vectors

We can define a vector and construct a for loop that executes for each element in the vector:

students <- c("Amy", "Tom")
for (student in students){
   cat(student,"\n")
}
## Amy 
## Tom

5.3.4 Example: Technical Indicators

A n-day simple moving avaerage (n-day SMA) is arithmetic average of prices of past n days:

\[ SMA_t(n) = \frac{P_t+\ldots+P_{t-n+1}}{n}\]

The following is an sMA function:

mySMA <- function (price,n){
  sma <- c()
  sma[1:(n-1)] <- NA
  for (i in n:length(price)){
    sma[i]<-mean(price[(i-n+1):i])
  }
  return(sma)
}
mySMA(1:10,5)
##  [1] NA NA NA NA  3  4  5  6  7  8

An n-day exponential moving avaerage (n-day EMA) is exponential average of prices where weighting of more recent prices carry higher weights. The first EMA is similar to SMA and the updating formula is simple.

\[ EMA_t(n) = \beta P_t +(1-\beta) EMA_{t-1}(n)\]

where \(\beta =\frac{2}{n+1}\), \(n\) is number of days and \(P_t\) is price of time \(t\).

This is an EMA function:

myEMA <- function (price,n){
  ema <- c()
  ema[1:(n-1)] <- NA
  ema[n]<- mean(price[1:n])
  beta <- 2/(n+1)
  for (i in (n+1):length(price)){
    ema[i]<-beta * price[i] + 
      (1-beta) * ema[i-1]
  }
  return(ema)
}
myEMA(1:10,5)
##  [1] NA NA NA NA  3  4  5  6  7  8

An n-day relative strenght index (RSI) is normalized n-day relative strength (RS) that is ratio of days of stock price has gone up to the days of stock price have gone down.

This is an RSI function:

myRSI <- function (price,n){
  U <- rep(0,length(price))
  D <- rep(0,length(price))
  rs <- rep(NA,length(price))
  rsi <- rep(NA,length(price))
  for (i in 2:length(price)){
    if (price[i]>price[(i-1)]){
      U[i] <- 1
    } else if (price[i]<price[(i-1)]){
      D[i] <- 1
    }
    if (i>n){
      if (sum(D[(i-n+1):i])==0){
        rsi[i] <- 100
      } else{
        rs[i] <- sum(U[(i-n+1):i])/
          sum(D[(i-n+1):i])
        rsi[i] <- rs[i]/(rs[i]+1)*100
      }
    }
  }
  return(rsi)
}
myRSI(sample(4:10,20,replace=TRUE),6)
##  [1] NA NA NA NA NA NA 40 40 20 40 40 40 50 50 60 60 80 60 40 60

Exercise

  1. Use while loop to calculate the product of all numbers from 50 to 100.

  2. Use for loop to calculate the product of all numbers from 50 to 100.

  3. Write a MACD function that returns both macd and signal line using four inputs:
  • price: price vector
  • S: number of periods for fast moving average
  • L: number of periods for slow moving average
  • K: number of periods for signal moving average