SlideShare a Scribd company logo
1 of 18
Download to read offline
A Comparison of Returns Yielded from
Algorithmic Trading Strategies
MATH W4071 Final Project
Working Group:
Chen Zhou (cz2384) Max Pasternak Norris (mpn2120)
Yanxi Chen (yc3081) Qianyun Zhang (qz2246)
Yicheng Wang (yw2761)
May 11, 2016
1
1 Data Collection & Preparation
For this project we collected 10 years of historical stock data (April 1, 2006 to April 1, 2016) for 20
stocks from 5 sectors: Auto, Food, Beverage, Electronics and Finance (100 stocks in total). The
data is download through Yahoo Finance website and R package Quantmod (which is also sourced
from Yahoo Finance). In order to compare the strategies at the same condition, we used “closed
price” (fifth column of the data spreadsheet) for all strategies. The following table shows the stock
codes for 100 stocks we used.
Table 1: Historical Stocks Code
Stock Code
STZ TAP WVVI CCU DEO
Beverage VCO SAM BREW BF-B BF-A
FIZZ COT COKE KO FMX
CCE PEP MNST KOF LBIX
PCAR HMC TTM TM AZO
Auto F SEV SUP ALV KMX
ORLY MLR TEN GPC JCI
MGA SPXC THRM BWA HOG
RSYS LFUS OLED SRI AMSC
Electronics NJ AVX CTS ROG IIN
PKE KYO SPA VICR LPTH
NSYS BLDP AUO KEM DAIO
BRKL PBIP PBCT WAFD BKMU
Finance LARK PROV RVSB HFWA WTBA
BYFC HMNF GSBC CFBK BFIN
BANR WAYN NYCB ESBK FCTY
MGPI JBSS CPB K GIS
Food SYY LANC SJM CAG THS
SEB JJSF LNCE HAIN UNFI
FLO TOF BRFS SVU STKL
In terms of the strategies construction and comparison, we used two methods. First we use
100 individual stocks, not to a portfolio as a whole. This method is applied to Moving Average
(MA) Ribbon 1 and Buy & Hold (B & H) strategies. The second method is to construct an equity
portfolio. We hold 100 shares for each of our 100 stocks plus 100,000 Dollars cash as initial asset
for our portfolio. This method is applied to Bollinger Bands (BB), Relative Strength Index (RSI)
1
“Moving Average Ribbon Definition — Investopedia.” Investopedia. 2005. Accessed May 09, 2016.
http://www.investopedia.com/terms/m/movingaverageribbon.asp.
2
2 and Buy & Hold (B & H) strategies.
2 Algorithmic Trading Strategies
2.1 Buy & Hold (B & H)Strategy
Buy & Hold Strategy is a simple investment strategy where an investor buys stock(s) and holds
them for a long time. This is based on the view that in the long run financial markets give a good
rate of return even while taking into account a degree of volatility. In our case, this strategy is used
as a benchmark in comparison with other complicated strategies.
2.2 Moving Average (MA) Ribbon Strategy
The Moving Average Ribbon Strategy is excellent for taking advantage of the market when it is
in long-term upward trends, and in laying off the market during long-term downward trends. A
drawback to the Moving Average Ribbon Strategy is that it is not very responsive to short-term
changes in the market. We construct a MA Ribbon by creating 12 to 16 moving averages. For this
project, we created 16 moving averages: 50-day MA, 60-day MA, 70-day MA, all the way up to 200
day MA, which is said to increase the validity of the upward or downward signal (investopedia.com).
To give all 16 moving averages time to become fully calibrated, with our data back to April 1, 2006,
we began our trading strategies on January17, 2007. Figure 1 shows an example of the strategy.
Figure 1: MA Ribbon Example
2
“Relative Strength Index (RSI).” [ChartSchool]. Accessed May 09, 2016.
http://stockcharts.com/school/doku.php?id=chart school:technical indicators:relative strength index rsi.
3
Additional moving averages may be added to the chart to increase the validity of the signal.
All 16 of our moving averages are 50-day moving averages or above, which are useful in identifying
long-term trends and reversals, but the strategy does not call for any shorter moving averages,
which could be useful in identifying slight price changes. When all 16 of our moving averages are
moving in the same direction, the trend is said to be strong. Reversals are confirmed when the
averages cross over and head in the opposite direction. The strategy we used was to buy and hold
when all 16 moving averages were moving upwardly and to sell when at least one moving average
began moving downwardly.
2.3 Bollinger Bands (BB) Strategy
Bollinger Bands is a technical analysis tool invented by John Bollinger in the 1980s. Having evolved
from the concept of trading bands, Bollinger Bands, the related indicators %b (percent b), and
bandwidth can be used to measure the ”highness” or ”lowness” of the price relative to previous
trades. In our case, we construct the strategy by using these three indicators: the upper band,
lower band and the %b. The bands and %b is calculated in these formulas:
Upper Band = 20 Days-SMA + 2 × σ
Lower Band = 20 × 20 Days-SMA − 2 × σ
%b =
Closed Price − Lower Band Price
Upper Band Price − Lower Band Price
(where SMA abbreviates ”simple moving average”, and σ is the volatility of the closed price in the
specified 20 day period). We used closed price to calculate all the indicators in the above formula.
To be noticed, we multiplied 2 by the volatility. This is a usual default setting in the industry.
The following is our Bollinger Bands strategy:
• Buy the stock(s):When the price passes from above to below through the lower band, and
%b is smaller than zero
• Sell the stock(s): When the price passes from below to above through the upper band, and
%b is bigger than one
4
• Hold the stock(s): Otherwise.
2.4 Relative Strength Index (RSI) Strategy
The Relative Strength Index (RSI), developed by J. Welles Wilder, is a momentum oscillator that
measures the speed and change of price movements. It compares the magnitude of recent gains to
recent losses in an attempt to determine overbought and oversold conditions of an asset. The RSI
oscillates between zero and 100. In our case, we construct the RSI strategy by creating the RSI
indicator:
Relative Strength Factor (RS) =
SMMA Gain
SMMA Loss
Relative Strength Index (RSI) = 100 −
100
1 + RS
Where SMMA represents for Smooth or Modified Moving Average, in detail, the first RS is equal
to first average gain divided by first average loss, which is calculated by:
RSfirst =
Average Gain of 14 days
Average Loss of 14 days
The rest of RS is calculated by:
RSrest =
13×previous average gain+currentgain
14
13×previous average loss+current loss
14
=
13 × previous average gain + current gain
13 × previous average loss + current loss
*which is actually using Exponential Moving Average method
The following is our Relative Strength Index strategy:
• Buy the stock(s):When the RSI is below 30.
• Sell the stock(s): When the RSI is above 70.
5
• Hold the stock(s): Otherwise.
Results & Comparison
We ran the MA Ribbon strategy from January 17, 2006 to April 1, 2016 and compared its percent
returns against the percent returns yielded from a simple Buy & Hold strategy.
Figure 2: Bar Chart
Above in Figure 2, we see that our MA Ribbon strategy only yielded greater returns than our
Buy-and-Hold strategy in 32 out of our 100 stocks. We wondered if possibly this was simply due
to the fact that the MA Ribbon strategy takes on less risk by virtue of not always holding onto the
stock (whenever 1 MA curve is downward sloping we are not invested in the market.) To see how
our MA Strategy compared to the Buy-and-Hold Strategy after adjusting for risk, we calculated
the 100 sharpe ratios for the MA Strategy and the 100 sharpe ratios for the Buy-and-Hold strategy.
Although we did find that the MA Ribbon strategy is significantly less volatile, calculating the
sharpe ratios showed us that the inferior returns of the MA Ribbon strategy were not due to taking
on less risk, but that overall, the MA Ribbon strategy is simply a poor trading strategy.
In only 30 out of our 100 stocks was the sharpe ratio for the MA Ribbon strategy greater than
the sharpe ratio for the Buy-and-Hold strategy. To calculate the sharpe ratio: first we calculated the
the effective risk-free rate from January 17, 2007 to April 1, 2016 using 10-Year Treasure Constant
6
Maturity Rates downloaded from the Board of Governors of the Federal Reserve System (US). We
calculated that the effective risk-free rate over our 2319 trading days was 2.89% or 0.0289.
We found that our MA Ribbon strategy is less risky in the sense that the standard deviations of
its daily returns were always less than the standard deviations of the daily returns for the Buy-and-
Hold strategy. The standard deviations of the daily returns for the Buy-and-Hold strategy ranged
typically from .0125 to .04 (resulting in a multiplier of 25 to 80) whereas the standard deviations
of the daily returns for the MA Ribbon strategy ranged typically from .005 to .02 (resulting in a
multiplier of 50 to 200).
Since the standard deviations of returns associated with the MA Ribbon strategy are so much
lower than the standard deviations of returns for the Buy-and-Hold strategy, on five instances
where both strategies yielded positive returns but the returns from the Buy-and-Hold strategy
were greater than the returns from the MA Ribbon strategy, the sharpe ratio turned our to be
greater for the MA Ribbon strategy than for the Buy-and-Hold strategy. But this had the opposite
effect for stocks that yielded negative returns using both strategies. On seven instances where both
strategies yielded negative returns but the return percentages from the Buy-and-Hold strategy were
even more negative than the return percentages from the MA Ribbon strategy, the sharpe ratio
turned our to be greater for the Buy-and-Hold strategy than for the MA Ribbon strategy. In only
30 out of our 100 stocks was the sharpe ratio for the MA Ribbon strategy greater than the sharpe
ratio for the Buy-and-Hold strategy as shown by 32+5-7 = 30.
Next, let us transition into the segment of our project where we held onto a portfolio of all
100 stocks at once and 10,000 cash and compared the Buy-and-Hold strategy to the Bollinger
Bands and RSI strategies. Below, in Figure 3, is our plot of cumulative returns over time of these
three strategies running on the portfolio. From Tables 2 and 3, the Sharpe Ratio and annualized
return suggest that BB and RSI strategies are both relatively worse than B & H strategy, and RSI
performed better than BB.
7
Figure 3: Cumulative Return under Each Strategy
0
0.5
1
1.5
2
2.5
5/3/06
7/3/06
9/3/06
11/3/06
1/3/07
3/3/07
5/3/07
7/3/07
9/3/07
11/3/07
1/3/08
3/3/08
5/3/08
7/3/08
9/3/08
11/3/08
1/3/09
3/3/09
5/3/09
7/3/09
9/3/09
11/3/09
1/3/10
3/3/10
5/3/10
7/3/10
9/3/10
11/3/10
1/3/11
3/3/11
5/3/11
7/3/11
9/3/11
11/3/11
1/3/12
3/3/12
5/3/12
7/3/12
9/3/12
11/3/12
1/3/13
3/3/13
5/3/13
7/3/13
9/3/13
11/3/13
1/3/14
3/3/14
5/3/14
7/3/14
9/3/14
11/3/14
1/3/15
3/3/15
5/3/15
7/3/15
9/3/15
11/3/15
1/3/16
3/3/16
Return	Strategy	Comparision
B.H_Return_cul BB_Return_cul RSI_Return_cul
Table 2: Sharpe Ratio for Each Strategy
Buy and Hold Bollinger Bands Relative Strength Index
1.971 1.106 1.820
Table 3: Annualized Return in 10 Year Period
Buy and Hold Bollinger Bands Relative Strength Index
5.44% 2.14% 3.59%
Looking at specified sub-periods, we can see that RSI and BB outperformed B & H in certain
sub-periods. We split the timeline to four periods with an attempt to see during each sub-period,
whether we could have some interesting findings in regards to the return. The four sub-periods are
listed below. The first period is before the 2007 subprime mortgage crisis. Then we have the crisis
period. The third period is when the federal reserve announced the Quantitative Easing policy and
the market began to recover. The fourth and final period is when the economy fully recovered:
• Period 1: May 2nd, 2006 to Oct 31th, 2007
• Period 2:Nov 1st, 2007 to Dec 31th, 2009
• Period 3:Jan 4th, 2010 to Dec 31, 2013
• Period 4:Jan 2nd, 2014 to Apr 1st, 2016
8
Table 4: Sharpe Ratio for Each Strategy
Time Buy and Hold Bollinger Bands Relative Strength Index
period 1 -0.0233 -2.1867 0.5938
period 2 -1.3308 -2.1020 -1.0612
period 3 4.0742 4.0628 3.5732
period 4 1.0229 0.8771 0.5369
Table 5: Annualized Return in Each Sub Period
Time Buy and Hold Bollinger Bands Relative Strength Index
period 1 0.30% -8.81% 16.07%
period 2 5.73% -4.36% -9.30%
period 3 10.94% 3.36% 3.71%
period 4 -4.99% 9.50% 1.96%
In Tables 4 and 5, we can check the Sharpe Ratio and annualized return in each sub-period. The
sharpe ratios show that, it would be a wise investment decision to use RSI strategy during our first
two periods, and then to switch to a simple B & H strategy for the second two periods. However
annualized return numbers show a inconsistent pattern comparing to the results from Table 4.
Return in period 3 and period 4 are relatively bigger if we choose B & H and BB respectively. This
inconsistency could be explained by the the definition of Shape Ratio. During periods 1 and 2,
the market faced the world finance crisis. A simple B & H strategy resulted in losses during both
of these periods. From our results, the RSI trading strategy appears to be superior to the B & H
strategy in recessionary markets. As we can see in Table 4, our Sharpe Ratios were greater for the
RSI strategy than for the B & H strategy in both periods 1 and 2. In a similar vein, the percent
returns during period 1 using the RSI strategy were far superior to the percent returns using the
B & H strategy (16.07% as compared to 0.30%).
Conclusion
Looking at 2007 through 2016 as a whole, our strategies did not outperform the B & H strategy.
A main reasons is because the strategies we used are not highly sophisticated, they are relatively
elementary trading strategies, and therefore it is not surprising that for our portfolio, the simple B
& H strategy could outperform MA Ribbon, BB and RSI in many circumstances. Many researchers
9
have argued that passive strategies (i.e. Buy & Hold) can often out-perform active strategies in
the long run. With that said, our RSI trading strategy did outperform the Buy & Hold strategy
during the market’s recession. Our Sharpe Ratios were greater for the RSI strategy than for the
B & H strategy in both periods 1 and 2. Also, the percent return during period 1 using the RSI
strategy was greater than the percent return using the B & H strategy during this first period.
For future improvements during recessionary and non-recessionary periods, more comprehensive
active management strategies could be constructed to outperform the passive Buy & Hold strategy.
For starters, we could combine our three strategies together to make buy and sell decisions and
see how such a strategy using multiple indicators performs. Our group feels as though the MA
Ribbon strategy is not sensitive enough to short-term trends in the market, but the Bollinger
Bands strategy and the RSI, which are both short term indicators, may be overly sensitive to the
short-term trends.
10
3 Appendix: R code
# install.packages("quantmod",dependencies = T)
# install.packages("openxlsx",dependencies=T)
library(quantmod)
library(openxlsx)
stockname <- c("STZ","TAP","WVVI","CCU","DEO",
"VCO","SAM","BREW","BF-B","BF-A",
"FIZZ","COT","COKE","KO","FMX",
"CCE","PEP","MNST","KOF","LBIX")
stockname1 <- c("PCAR","HMC","TTM","TM","AZO",
"F","SEV","SUP","ALV","KMX",
"ORLY","MLR","TEN","GPC","JCI",
"MGA","SPXC","THRM","BWA","HOG")
stockname2 <- c("RSYS","LFUS","OLED","SRI","AMSC",
"NJ","AVX","CTS","ROG","IIN",
"PKE","KYO","SPA","VICR","LPTH",
"NSYS","BLDP","AUO","KEM","DAIO")
stockname3 <- c("BRKL","PBIP","PBCT","WAFD","BKMU",
"LARK","PROV","RVSB","HFWA","WTBA",
"BYFC","HMNF","GSBC","CFBK","BFIN",
"BANR","WAYN","NYCB","ESBK","FCTY")
stockname3 <- c("MGPI","JBSS","CPB","K","GIS",
"SYY","LANC","SJM","CAG","THS",
"SEB","JJSF","LNCE","HAIN","UNFI",
"FLO","TOF","BRFS","SVU","STKL")
getSymbols(stockname,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03"))
getSymbols(stockname1,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03"))
getSymbols(stockname2,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03"))
11
getSymbols(stockname3,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03"))
getSymbols(stockname4,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03"))
stock <- list(STZ,TAP,WVVI,CCU,DEO,
VCO,SAM,BREW,`BF-B`,`BF-A`,
FIZZ,COT,COKE,KO,FMX,
CCE,PEP,MNST,KOF,LBIX)
stock1 <- list(PCAR,HMC,TTM,TM,AZO,
`F`,SEV,SUP,ALV,KMX,
ORLY,MLR,TEN,GPC,JCI,
MGA,SPXC,THRM,BWA,HOG)
stock2 <- list(RSYS,LFUS,OLED,SRI,AMSC,
NJ,AVX,CTS,ROG,IIN,
PKE,KYO,SPA,VICR,LPTH,
NSYS,BLDP,AUO,KEM,DAIO)
stock3 <- list(BRKL,PBIP,PBCT,WAFD,BKMU,
LARK,PROV,RVSB,HFWA,WTBA,
BYFC,HMNF,GSBC,CFBK,BFIN,
BANR,WAYN,NYCB,ESBK,FCTY)
stock4 <- list( MGPI,JBSS,CPB,K,GIS,
SYY,LANC,SJM,CAG,THS,
SEB,JJSF,LNCE,HAIN,UNFI,
FLO,TOF,BRFS,SVU,STKL)
stock.close <-matrix(NA,nrow = 2517,ncol = 20)
stock.volume <-matrix(NA,nrow = 2517,ncol = 20)
for( i in 1:20){
stock.close[,i] <- stock[[i]][,4]
stock.volume[,i] <- stock[[i]][,5]
}
stock.close1 <-matrix(NA,nrow = 2517,ncol = 20)
12
stock.volume1 <-matrix(NA,nrow = 2517,ncol = 20)
for( i in 1:20){
stock.close1[,i] <- stock1[[i]][,4]
stock.volume1[,i] <- stock1[[i]][,5]
}
stock.close2 <-matrix(NA,nrow = 2517,ncol = 20)
stock.volume2 <-matrix(NA,nrow = 2517,ncol = 20)
for( i in 1:20){
stock.close2[,i] <- stock2[[i]][,4]
stock.volume2[,i] <- stock2[[i]][,5]
}
stock.close3 <-matrix(NA,nrow = 2517,ncol = 20)
stock.volume3 <-matrix(NA,nrow = 2517,ncol = 20)
for( i in 1:20){
stock.close3[,i] <- stock3[[i]][,4]
stock.volume3[,i] <- stock3[[i]][,5]
}
stock.close4 <-matrix(NA,nrow = 2517,ncol = 20)
stock.volume4 <-matrix(NA,nrow = 2517,ncol = 20)
for( i in 1:20){
stock.close4[,i] <- stock4[[i]][,4]
stock.volume4[,i] <- stock4[[i]][,5]
}
######function######
change <- function(data,col){
p <- rep(NA,2517)
for(i in 2:2517){
p[i] <- data[i,col]-data[i-1,col]
}
return(p)
}
gain <- function(data,col){
13
tmp <- rep(NA,2516)
tmp[change(data,col)[-1]>=0] <- change(data,col)[-1][change(data,col)[-1]>=0]
tmp[change(data,col)[-1]<0] <- 0
tmp <- c(NA,tmp)
return(tmp)
}
loss <- function(data,col){
tmp <- rep(NA,2516)
tmp[change(data,col)[-1]<=0] <- change(data,col)[-1][change(data,col)[-1]<=0]
tmp[change(data,col)[-1]>0] <- 0
tmp <- c(NA,tmp)
return(tmp)
}
avg.gain <- function(data,col){
tmp <- rep(NA,2503)
tmp[1] <- sum(stock.gain[(1+1):(1+14),col])/14
for(i in 2:2503){
tmp[i] <- (tmp[i-1]*13+stock.gain[(i+14),col])/14
}
tmp <- c(rep(NA,14),tmp)
return(tmp)
}
avg.loss <- function(data,col){
tmp <- rep(NA,2503)
tmp[1] <- sum(stock.loss[(1+1):(1+14),col])/14
for(i in 2:2503){
tmp[i] <- (tmp[i-1]*13+stock.loss[(i+14),col])/14
}
tmp <- c(rep(NA,14),tmp)
return(tmp)
}
rsi <- function(data,col){
tmp <- rep(NA,2517)
14
tmp[is.na(stock.avg.loss[,col])] <- NA
tmp[stock.avg.loss[,col]==0] <- 100
tmp[(stock.avg.loss[,col]!=0)&is.na(stock.avg.loss[,col]!=0)==FALSE] <- 100-100/(1+data[(stock.av
return(tmp)
}
indicator <- function(data,col){
tmp <- rep(NA,2517)
tmp[data[,col]<30] <- 1
tmp[data[,col]>=70] <- -1
tmp[(data[,col]>=30)&(data[,col]<70)] <- 0
return(tmp)
}
account.portfolio <- function(data,col){
tmp <- rep(NA,2498)
tmp[1] <- 100
for(i in 2:2498) {
tmp[i] <- tmp[i-1]+data[i+19,col]
}
return(tmp)
}
value.each <- function(col){
tmp <- rep(NA,2498)
for(i in 1:2498){
tmp[i] <- stock.close[19:2517,col][i]*account[,col][i]
}
return(tmp)
}
cash.change <- function(col){
tmp <- rep(NA,2498)
for(i in 1:2498){
tmp[i] <- -stock.close[20:2517,col][i]*stock.indicator[20:2517,col][i]
}
return(tmp)
}
15
###data preparation####
stock.gain <- matrix(NA,2517,100)
for(i in 1:100){
stock.gain[,i] <- gain(stock.close,i)
}
stock.loss <- matrix(NA,2517,100)
for(i in 1:100){
stock.loss[,i] <- loss(stock.close,i)
}
stock.avg.gain <- matrix(NA,2517,100)
for(i in 1:100){
stock.avg.gain[,i] <- avg.gain(stock.close,i)
}
stock.avg.loss <- matrix(NA,2517,100)
for(i in 1:100){
stock.avg.loss[,i] <-abs( avg.loss(stock.close,i))
}
stock.rs <- rbind(matrix(NA,14,100),stock.avg.gain[15:2517,]/stock.avg.loss[15:2517,])
stock.rsi <- matrix(NA,2517,100)
for(i in 1:100){
stock.rsi[,i] <- rsi(stock.rs,i)
}
stock.indicator <- matrix(NA,2517,100)
for(i in 1:100){
stock.indicator[,i] <- indicator(stock.rsi,i)
}
account <- matrix(NA,2498,100)
16
for(i in 1:100){
account[,i] <- account.portfolio(stock.indicator,i)
}
stock.value <- matrix(NA,2498,100)
for(i in 1:100){
stock.value[,i] <- value.each(i)
}
stock.accum <- apply(stock.value,1,sum)
cash.change.total <- matrix(NA,2498,100)
for(i in 1:100){
cash.change.total[,i] <- cash.change(i)
}
cash.change.total[1,] <- 0
#cash change for each portfolio
cash <- apply(cash.change.total, 1, sum)
cash.accum <- rep(NA,2498)
cash.accum[1] <- 10000
for(i in 2:2498){
cash.accum[i] <- cash.accum[i-1]+cash[i]
}
portfolio.accum <- cash.accum+stock.accum
portfolio.accum <- matrix(portfolio.accum,ncol=1)
openxlsx::write.xlsx(portfolio.accum,"portfoilo 10000.xlsx")
cash.accum <- rep(NA,2498)
cash.accum[1] <- 100000
for(i in 2:2498){
cash.accum[i] <- cash.accum[i-1]+cash[i]
}
17
portfolio.accum <- cash.accum+stock.accum
portfolio.accum <- matrix(portfolio.accum,ncol=1)
openxlsx::write.xlsx(portfolio.accum,"portfoilo 100000.xlsx")
#######################################
18

More Related Content

What's hot

C323-RiskManagementPrinciplesandApplications-AssignmentOne
C323-RiskManagementPrinciplesandApplications-AssignmentOneC323-RiskManagementPrinciplesandApplications-AssignmentOne
C323-RiskManagementPrinciplesandApplications-AssignmentOneMark Heath - BA Hons, MSc, MCIPS
 
understanding margins for cash and derivative markets
understanding margins for  cash and derivative marketsunderstanding margins for  cash and derivative markets
understanding margins for cash and derivative marketskcysrutha
 
Accounting questions
Accounting questionsAccounting questions
Accounting questionsRohit Sethi
 
Parametric perspectives-winter-2010 (1)
Parametric perspectives-winter-2010 (1)Parametric perspectives-winter-2010 (1)
Parametric perspectives-winter-2010 (1)Kola Wade
 
Stock Selection Models
Stock Selection ModelsStock Selection Models
Stock Selection Modelskituni
 

What's hot (6)

Qir 2013q2 us
Qir 2013q2 usQir 2013q2 us
Qir 2013q2 us
 
C323-RiskManagementPrinciplesandApplications-AssignmentOne
C323-RiskManagementPrinciplesandApplications-AssignmentOneC323-RiskManagementPrinciplesandApplications-AssignmentOne
C323-RiskManagementPrinciplesandApplications-AssignmentOne
 
understanding margins for cash and derivative markets
understanding margins for  cash and derivative marketsunderstanding margins for  cash and derivative markets
understanding margins for cash and derivative markets
 
Accounting questions
Accounting questionsAccounting questions
Accounting questions
 
Parametric perspectives-winter-2010 (1)
Parametric perspectives-winter-2010 (1)Parametric perspectives-winter-2010 (1)
Parametric perspectives-winter-2010 (1)
 
Stock Selection Models
Stock Selection ModelsStock Selection Models
Stock Selection Models
 

Similar to 4071

Can we use Mixture Models to Predict Market Bottoms? by Brian Christopher - 2...
Can we use Mixture Models to Predict Market Bottoms? by Brian Christopher - 2...Can we use Mixture Models to Predict Market Bottoms? by Brian Christopher - 2...
Can we use Mixture Models to Predict Market Bottoms? by Brian Christopher - 2...QuantInsti
 
Technical Analysis
Technical AnalysisTechnical Analysis
Technical Analysisluv_sharma
 
The Risk and Return of the Buy Write Strategy On The Russell 2000 Index
The Risk and Return of the Buy Write Strategy On The Russell 2000 IndexThe Risk and Return of the Buy Write Strategy On The Russell 2000 Index
The Risk and Return of the Buy Write Strategy On The Russell 2000 IndexRYAN RENICKER
 
Power hour power point 12.09.2010
Power hour power point 12.09.2010Power hour power point 12.09.2010
Power hour power point 12.09.2010Marcello Ducille
 
Power hour power point 12.09.2010b
Power hour power point 12.09.2010bPower hour power point 12.09.2010b
Power hour power point 12.09.2010bMarcello Ducille
 
Power hour power point 12.09.2010
Power hour power point 12.09.2010Power hour power point 12.09.2010
Power hour power point 12.09.2010Marcello Ducille
 
Power hour power point 12.09.2010b
Power hour power point 12.09.2010bPower hour power point 12.09.2010b
Power hour power point 12.09.2010bMarcello Ducille
 
EAMPartners_2015_Inst
EAMPartners_2015_InstEAMPartners_2015_Inst
EAMPartners_2015_InstDenis Eganov
 
eampartners hedge fund
eampartners hedge fundeampartners hedge fund
eampartners hedge fundDenis Eganov
 
Carry trade strategy - Jean Lemercier Ailing Wang Pei Shu-Wei Kwadwo Okoh
Carry trade strategy - Jean Lemercier Ailing Wang Pei Shu-Wei Kwadwo OkohCarry trade strategy - Jean Lemercier Ailing Wang Pei Shu-Wei Kwadwo Okoh
Carry trade strategy - Jean Lemercier Ailing Wang Pei Shu-Wei Kwadwo OkohJean Lemercier
 
FINANCIAL FORECASTING.pptx
FINANCIAL FORECASTING.pptxFINANCIAL FORECASTING.pptx
FINANCIAL FORECASTING.pptxRiyaSingh536187
 
My simplified ichimoku System
My simplified ichimoku SystemMy simplified ichimoku System
My simplified ichimoku SystemJohn Treadle
 
Dynamic statistical trading strategy
Dynamic statistical trading strategyDynamic statistical trading strategy
Dynamic statistical trading strategyandrejogorevc
 
SBI Dynamic Asset Allocation Fund: An Open-ended Dynamic Asset Allocation Sch...
SBI Dynamic Asset Allocation Fund: An Open-ended Dynamic Asset Allocation Sch...SBI Dynamic Asset Allocation Fund: An Open-ended Dynamic Asset Allocation Sch...
SBI Dynamic Asset Allocation Fund: An Open-ended Dynamic Asset Allocation Sch...SBI Mutual Fund
 
Our investment process
Our investment processOur investment process
Our investment processJeff Diercks
 

Similar to 4071 (20)

Relative strength strategies for investing
Relative strength strategies for investingRelative strength strategies for investing
Relative strength strategies for investing
 
Can we use Mixture Models to Predict Market Bottoms? by Brian Christopher - 2...
Can we use Mixture Models to Predict Market Bottoms? by Brian Christopher - 2...Can we use Mixture Models to Predict Market Bottoms? by Brian Christopher - 2...
Can we use Mixture Models to Predict Market Bottoms? by Brian Christopher - 2...
 
Simple moving averages
Simple moving averagesSimple moving averages
Simple moving averages
 
Technical Analysis
Technical AnalysisTechnical Analysis
Technical Analysis
 
The Risk and Return of the Buy Write Strategy On The Russell 2000 Index
The Risk and Return of the Buy Write Strategy On The Russell 2000 IndexThe Risk and Return of the Buy Write Strategy On The Russell 2000 Index
The Risk and Return of the Buy Write Strategy On The Russell 2000 Index
 
Mathematical indicators
Mathematical indicatorsMathematical indicators
Mathematical indicators
 
Power hour power point 12.09.2010
Power hour power point 12.09.2010Power hour power point 12.09.2010
Power hour power point 12.09.2010
 
Power hour power point 12.09.2010b
Power hour power point 12.09.2010bPower hour power point 12.09.2010b
Power hour power point 12.09.2010b
 
Power hour power point 12.09.2010
Power hour power point 12.09.2010Power hour power point 12.09.2010
Power hour power point 12.09.2010
 
Power hour power point 12.09.2010b
Power hour power point 12.09.2010bPower hour power point 12.09.2010b
Power hour power point 12.09.2010b
 
EAMPartners_2015_Inst
EAMPartners_2015_InstEAMPartners_2015_Inst
EAMPartners_2015_Inst
 
eampartners hedge fund
eampartners hedge fundeampartners hedge fund
eampartners hedge fund
 
Carry trade strategy - Jean Lemercier Ailing Wang Pei Shu-Wei Kwadwo Okoh
Carry trade strategy - Jean Lemercier Ailing Wang Pei Shu-Wei Kwadwo OkohCarry trade strategy - Jean Lemercier Ailing Wang Pei Shu-Wei Kwadwo Okoh
Carry trade strategy - Jean Lemercier Ailing Wang Pei Shu-Wei Kwadwo Okoh
 
FINANCIAL FORECASTING.pptx
FINANCIAL FORECASTING.pptxFINANCIAL FORECASTING.pptx
FINANCIAL FORECASTING.pptx
 
My simplified ichimoku System
My simplified ichimoku SystemMy simplified ichimoku System
My simplified ichimoku System
 
Dynamic statistical trading strategy
Dynamic statistical trading strategyDynamic statistical trading strategy
Dynamic statistical trading strategy
 
muthu.shree
muthu.shreemuthu.shree
muthu.shree
 
Beta
BetaBeta
Beta
 
SBI Dynamic Asset Allocation Fund: An Open-ended Dynamic Asset Allocation Sch...
SBI Dynamic Asset Allocation Fund: An Open-ended Dynamic Asset Allocation Sch...SBI Dynamic Asset Allocation Fund: An Open-ended Dynamic Asset Allocation Sch...
SBI Dynamic Asset Allocation Fund: An Open-ended Dynamic Asset Allocation Sch...
 
Our investment process
Our investment processOur investment process
Our investment process
 

4071

  • 1. A Comparison of Returns Yielded from Algorithmic Trading Strategies MATH W4071 Final Project Working Group: Chen Zhou (cz2384) Max Pasternak Norris (mpn2120) Yanxi Chen (yc3081) Qianyun Zhang (qz2246) Yicheng Wang (yw2761) May 11, 2016 1
  • 2. 1 Data Collection & Preparation For this project we collected 10 years of historical stock data (April 1, 2006 to April 1, 2016) for 20 stocks from 5 sectors: Auto, Food, Beverage, Electronics and Finance (100 stocks in total). The data is download through Yahoo Finance website and R package Quantmod (which is also sourced from Yahoo Finance). In order to compare the strategies at the same condition, we used “closed price” (fifth column of the data spreadsheet) for all strategies. The following table shows the stock codes for 100 stocks we used. Table 1: Historical Stocks Code Stock Code STZ TAP WVVI CCU DEO Beverage VCO SAM BREW BF-B BF-A FIZZ COT COKE KO FMX CCE PEP MNST KOF LBIX PCAR HMC TTM TM AZO Auto F SEV SUP ALV KMX ORLY MLR TEN GPC JCI MGA SPXC THRM BWA HOG RSYS LFUS OLED SRI AMSC Electronics NJ AVX CTS ROG IIN PKE KYO SPA VICR LPTH NSYS BLDP AUO KEM DAIO BRKL PBIP PBCT WAFD BKMU Finance LARK PROV RVSB HFWA WTBA BYFC HMNF GSBC CFBK BFIN BANR WAYN NYCB ESBK FCTY MGPI JBSS CPB K GIS Food SYY LANC SJM CAG THS SEB JJSF LNCE HAIN UNFI FLO TOF BRFS SVU STKL In terms of the strategies construction and comparison, we used two methods. First we use 100 individual stocks, not to a portfolio as a whole. This method is applied to Moving Average (MA) Ribbon 1 and Buy & Hold (B & H) strategies. The second method is to construct an equity portfolio. We hold 100 shares for each of our 100 stocks plus 100,000 Dollars cash as initial asset for our portfolio. This method is applied to Bollinger Bands (BB), Relative Strength Index (RSI) 1 “Moving Average Ribbon Definition — Investopedia.” Investopedia. 2005. Accessed May 09, 2016. http://www.investopedia.com/terms/m/movingaverageribbon.asp. 2
  • 3. 2 and Buy & Hold (B & H) strategies. 2 Algorithmic Trading Strategies 2.1 Buy & Hold (B & H)Strategy Buy & Hold Strategy is a simple investment strategy where an investor buys stock(s) and holds them for a long time. This is based on the view that in the long run financial markets give a good rate of return even while taking into account a degree of volatility. In our case, this strategy is used as a benchmark in comparison with other complicated strategies. 2.2 Moving Average (MA) Ribbon Strategy The Moving Average Ribbon Strategy is excellent for taking advantage of the market when it is in long-term upward trends, and in laying off the market during long-term downward trends. A drawback to the Moving Average Ribbon Strategy is that it is not very responsive to short-term changes in the market. We construct a MA Ribbon by creating 12 to 16 moving averages. For this project, we created 16 moving averages: 50-day MA, 60-day MA, 70-day MA, all the way up to 200 day MA, which is said to increase the validity of the upward or downward signal (investopedia.com). To give all 16 moving averages time to become fully calibrated, with our data back to April 1, 2006, we began our trading strategies on January17, 2007. Figure 1 shows an example of the strategy. Figure 1: MA Ribbon Example 2 “Relative Strength Index (RSI).” [ChartSchool]. Accessed May 09, 2016. http://stockcharts.com/school/doku.php?id=chart school:technical indicators:relative strength index rsi. 3
  • 4. Additional moving averages may be added to the chart to increase the validity of the signal. All 16 of our moving averages are 50-day moving averages or above, which are useful in identifying long-term trends and reversals, but the strategy does not call for any shorter moving averages, which could be useful in identifying slight price changes. When all 16 of our moving averages are moving in the same direction, the trend is said to be strong. Reversals are confirmed when the averages cross over and head in the opposite direction. The strategy we used was to buy and hold when all 16 moving averages were moving upwardly and to sell when at least one moving average began moving downwardly. 2.3 Bollinger Bands (BB) Strategy Bollinger Bands is a technical analysis tool invented by John Bollinger in the 1980s. Having evolved from the concept of trading bands, Bollinger Bands, the related indicators %b (percent b), and bandwidth can be used to measure the ”highness” or ”lowness” of the price relative to previous trades. In our case, we construct the strategy by using these three indicators: the upper band, lower band and the %b. The bands and %b is calculated in these formulas: Upper Band = 20 Days-SMA + 2 × σ Lower Band = 20 × 20 Days-SMA − 2 × σ %b = Closed Price − Lower Band Price Upper Band Price − Lower Band Price (where SMA abbreviates ”simple moving average”, and σ is the volatility of the closed price in the specified 20 day period). We used closed price to calculate all the indicators in the above formula. To be noticed, we multiplied 2 by the volatility. This is a usual default setting in the industry. The following is our Bollinger Bands strategy: • Buy the stock(s):When the price passes from above to below through the lower band, and %b is smaller than zero • Sell the stock(s): When the price passes from below to above through the upper band, and %b is bigger than one 4
  • 5. • Hold the stock(s): Otherwise. 2.4 Relative Strength Index (RSI) Strategy The Relative Strength Index (RSI), developed by J. Welles Wilder, is a momentum oscillator that measures the speed and change of price movements. It compares the magnitude of recent gains to recent losses in an attempt to determine overbought and oversold conditions of an asset. The RSI oscillates between zero and 100. In our case, we construct the RSI strategy by creating the RSI indicator: Relative Strength Factor (RS) = SMMA Gain SMMA Loss Relative Strength Index (RSI) = 100 − 100 1 + RS Where SMMA represents for Smooth or Modified Moving Average, in detail, the first RS is equal to first average gain divided by first average loss, which is calculated by: RSfirst = Average Gain of 14 days Average Loss of 14 days The rest of RS is calculated by: RSrest = 13×previous average gain+currentgain 14 13×previous average loss+current loss 14 = 13 × previous average gain + current gain 13 × previous average loss + current loss *which is actually using Exponential Moving Average method The following is our Relative Strength Index strategy: • Buy the stock(s):When the RSI is below 30. • Sell the stock(s): When the RSI is above 70. 5
  • 6. • Hold the stock(s): Otherwise. Results & Comparison We ran the MA Ribbon strategy from January 17, 2006 to April 1, 2016 and compared its percent returns against the percent returns yielded from a simple Buy & Hold strategy. Figure 2: Bar Chart Above in Figure 2, we see that our MA Ribbon strategy only yielded greater returns than our Buy-and-Hold strategy in 32 out of our 100 stocks. We wondered if possibly this was simply due to the fact that the MA Ribbon strategy takes on less risk by virtue of not always holding onto the stock (whenever 1 MA curve is downward sloping we are not invested in the market.) To see how our MA Strategy compared to the Buy-and-Hold Strategy after adjusting for risk, we calculated the 100 sharpe ratios for the MA Strategy and the 100 sharpe ratios for the Buy-and-Hold strategy. Although we did find that the MA Ribbon strategy is significantly less volatile, calculating the sharpe ratios showed us that the inferior returns of the MA Ribbon strategy were not due to taking on less risk, but that overall, the MA Ribbon strategy is simply a poor trading strategy. In only 30 out of our 100 stocks was the sharpe ratio for the MA Ribbon strategy greater than the sharpe ratio for the Buy-and-Hold strategy. To calculate the sharpe ratio: first we calculated the the effective risk-free rate from January 17, 2007 to April 1, 2016 using 10-Year Treasure Constant 6
  • 7. Maturity Rates downloaded from the Board of Governors of the Federal Reserve System (US). We calculated that the effective risk-free rate over our 2319 trading days was 2.89% or 0.0289. We found that our MA Ribbon strategy is less risky in the sense that the standard deviations of its daily returns were always less than the standard deviations of the daily returns for the Buy-and- Hold strategy. The standard deviations of the daily returns for the Buy-and-Hold strategy ranged typically from .0125 to .04 (resulting in a multiplier of 25 to 80) whereas the standard deviations of the daily returns for the MA Ribbon strategy ranged typically from .005 to .02 (resulting in a multiplier of 50 to 200). Since the standard deviations of returns associated with the MA Ribbon strategy are so much lower than the standard deviations of returns for the Buy-and-Hold strategy, on five instances where both strategies yielded positive returns but the returns from the Buy-and-Hold strategy were greater than the returns from the MA Ribbon strategy, the sharpe ratio turned our to be greater for the MA Ribbon strategy than for the Buy-and-Hold strategy. But this had the opposite effect for stocks that yielded negative returns using both strategies. On seven instances where both strategies yielded negative returns but the return percentages from the Buy-and-Hold strategy were even more negative than the return percentages from the MA Ribbon strategy, the sharpe ratio turned our to be greater for the Buy-and-Hold strategy than for the MA Ribbon strategy. In only 30 out of our 100 stocks was the sharpe ratio for the MA Ribbon strategy greater than the sharpe ratio for the Buy-and-Hold strategy as shown by 32+5-7 = 30. Next, let us transition into the segment of our project where we held onto a portfolio of all 100 stocks at once and 10,000 cash and compared the Buy-and-Hold strategy to the Bollinger Bands and RSI strategies. Below, in Figure 3, is our plot of cumulative returns over time of these three strategies running on the portfolio. From Tables 2 and 3, the Sharpe Ratio and annualized return suggest that BB and RSI strategies are both relatively worse than B & H strategy, and RSI performed better than BB. 7
  • 8. Figure 3: Cumulative Return under Each Strategy 0 0.5 1 1.5 2 2.5 5/3/06 7/3/06 9/3/06 11/3/06 1/3/07 3/3/07 5/3/07 7/3/07 9/3/07 11/3/07 1/3/08 3/3/08 5/3/08 7/3/08 9/3/08 11/3/08 1/3/09 3/3/09 5/3/09 7/3/09 9/3/09 11/3/09 1/3/10 3/3/10 5/3/10 7/3/10 9/3/10 11/3/10 1/3/11 3/3/11 5/3/11 7/3/11 9/3/11 11/3/11 1/3/12 3/3/12 5/3/12 7/3/12 9/3/12 11/3/12 1/3/13 3/3/13 5/3/13 7/3/13 9/3/13 11/3/13 1/3/14 3/3/14 5/3/14 7/3/14 9/3/14 11/3/14 1/3/15 3/3/15 5/3/15 7/3/15 9/3/15 11/3/15 1/3/16 3/3/16 Return Strategy Comparision B.H_Return_cul BB_Return_cul RSI_Return_cul Table 2: Sharpe Ratio for Each Strategy Buy and Hold Bollinger Bands Relative Strength Index 1.971 1.106 1.820 Table 3: Annualized Return in 10 Year Period Buy and Hold Bollinger Bands Relative Strength Index 5.44% 2.14% 3.59% Looking at specified sub-periods, we can see that RSI and BB outperformed B & H in certain sub-periods. We split the timeline to four periods with an attempt to see during each sub-period, whether we could have some interesting findings in regards to the return. The four sub-periods are listed below. The first period is before the 2007 subprime mortgage crisis. Then we have the crisis period. The third period is when the federal reserve announced the Quantitative Easing policy and the market began to recover. The fourth and final period is when the economy fully recovered: • Period 1: May 2nd, 2006 to Oct 31th, 2007 • Period 2:Nov 1st, 2007 to Dec 31th, 2009 • Period 3:Jan 4th, 2010 to Dec 31, 2013 • Period 4:Jan 2nd, 2014 to Apr 1st, 2016 8
  • 9. Table 4: Sharpe Ratio for Each Strategy Time Buy and Hold Bollinger Bands Relative Strength Index period 1 -0.0233 -2.1867 0.5938 period 2 -1.3308 -2.1020 -1.0612 period 3 4.0742 4.0628 3.5732 period 4 1.0229 0.8771 0.5369 Table 5: Annualized Return in Each Sub Period Time Buy and Hold Bollinger Bands Relative Strength Index period 1 0.30% -8.81% 16.07% period 2 5.73% -4.36% -9.30% period 3 10.94% 3.36% 3.71% period 4 -4.99% 9.50% 1.96% In Tables 4 and 5, we can check the Sharpe Ratio and annualized return in each sub-period. The sharpe ratios show that, it would be a wise investment decision to use RSI strategy during our first two periods, and then to switch to a simple B & H strategy for the second two periods. However annualized return numbers show a inconsistent pattern comparing to the results from Table 4. Return in period 3 and period 4 are relatively bigger if we choose B & H and BB respectively. This inconsistency could be explained by the the definition of Shape Ratio. During periods 1 and 2, the market faced the world finance crisis. A simple B & H strategy resulted in losses during both of these periods. From our results, the RSI trading strategy appears to be superior to the B & H strategy in recessionary markets. As we can see in Table 4, our Sharpe Ratios were greater for the RSI strategy than for the B & H strategy in both periods 1 and 2. In a similar vein, the percent returns during period 1 using the RSI strategy were far superior to the percent returns using the B & H strategy (16.07% as compared to 0.30%). Conclusion Looking at 2007 through 2016 as a whole, our strategies did not outperform the B & H strategy. A main reasons is because the strategies we used are not highly sophisticated, they are relatively elementary trading strategies, and therefore it is not surprising that for our portfolio, the simple B & H strategy could outperform MA Ribbon, BB and RSI in many circumstances. Many researchers 9
  • 10. have argued that passive strategies (i.e. Buy & Hold) can often out-perform active strategies in the long run. With that said, our RSI trading strategy did outperform the Buy & Hold strategy during the market’s recession. Our Sharpe Ratios were greater for the RSI strategy than for the B & H strategy in both periods 1 and 2. Also, the percent return during period 1 using the RSI strategy was greater than the percent return using the B & H strategy during this first period. For future improvements during recessionary and non-recessionary periods, more comprehensive active management strategies could be constructed to outperform the passive Buy & Hold strategy. For starters, we could combine our three strategies together to make buy and sell decisions and see how such a strategy using multiple indicators performs. Our group feels as though the MA Ribbon strategy is not sensitive enough to short-term trends in the market, but the Bollinger Bands strategy and the RSI, which are both short term indicators, may be overly sensitive to the short-term trends. 10
  • 11. 3 Appendix: R code # install.packages("quantmod",dependencies = T) # install.packages("openxlsx",dependencies=T) library(quantmod) library(openxlsx) stockname <- c("STZ","TAP","WVVI","CCU","DEO", "VCO","SAM","BREW","BF-B","BF-A", "FIZZ","COT","COKE","KO","FMX", "CCE","PEP","MNST","KOF","LBIX") stockname1 <- c("PCAR","HMC","TTM","TM","AZO", "F","SEV","SUP","ALV","KMX", "ORLY","MLR","TEN","GPC","JCI", "MGA","SPXC","THRM","BWA","HOG") stockname2 <- c("RSYS","LFUS","OLED","SRI","AMSC", "NJ","AVX","CTS","ROG","IIN", "PKE","KYO","SPA","VICR","LPTH", "NSYS","BLDP","AUO","KEM","DAIO") stockname3 <- c("BRKL","PBIP","PBCT","WAFD","BKMU", "LARK","PROV","RVSB","HFWA","WTBA", "BYFC","HMNF","GSBC","CFBK","BFIN", "BANR","WAYN","NYCB","ESBK","FCTY") stockname3 <- c("MGPI","JBSS","CPB","K","GIS", "SYY","LANC","SJM","CAG","THS", "SEB","JJSF","LNCE","HAIN","UNFI", "FLO","TOF","BRFS","SVU","STKL") getSymbols(stockname,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03")) getSymbols(stockname1,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03")) getSymbols(stockname2,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03")) 11
  • 12. getSymbols(stockname3,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03")) getSymbols(stockname4,src="yahoo",from=as.Date("2006-04-03"), to= as.Date("2016-04-03")) stock <- list(STZ,TAP,WVVI,CCU,DEO, VCO,SAM,BREW,`BF-B`,`BF-A`, FIZZ,COT,COKE,KO,FMX, CCE,PEP,MNST,KOF,LBIX) stock1 <- list(PCAR,HMC,TTM,TM,AZO, `F`,SEV,SUP,ALV,KMX, ORLY,MLR,TEN,GPC,JCI, MGA,SPXC,THRM,BWA,HOG) stock2 <- list(RSYS,LFUS,OLED,SRI,AMSC, NJ,AVX,CTS,ROG,IIN, PKE,KYO,SPA,VICR,LPTH, NSYS,BLDP,AUO,KEM,DAIO) stock3 <- list(BRKL,PBIP,PBCT,WAFD,BKMU, LARK,PROV,RVSB,HFWA,WTBA, BYFC,HMNF,GSBC,CFBK,BFIN, BANR,WAYN,NYCB,ESBK,FCTY) stock4 <- list( MGPI,JBSS,CPB,K,GIS, SYY,LANC,SJM,CAG,THS, SEB,JJSF,LNCE,HAIN,UNFI, FLO,TOF,BRFS,SVU,STKL) stock.close <-matrix(NA,nrow = 2517,ncol = 20) stock.volume <-matrix(NA,nrow = 2517,ncol = 20) for( i in 1:20){ stock.close[,i] <- stock[[i]][,4] stock.volume[,i] <- stock[[i]][,5] } stock.close1 <-matrix(NA,nrow = 2517,ncol = 20) 12
  • 13. stock.volume1 <-matrix(NA,nrow = 2517,ncol = 20) for( i in 1:20){ stock.close1[,i] <- stock1[[i]][,4] stock.volume1[,i] <- stock1[[i]][,5] } stock.close2 <-matrix(NA,nrow = 2517,ncol = 20) stock.volume2 <-matrix(NA,nrow = 2517,ncol = 20) for( i in 1:20){ stock.close2[,i] <- stock2[[i]][,4] stock.volume2[,i] <- stock2[[i]][,5] } stock.close3 <-matrix(NA,nrow = 2517,ncol = 20) stock.volume3 <-matrix(NA,nrow = 2517,ncol = 20) for( i in 1:20){ stock.close3[,i] <- stock3[[i]][,4] stock.volume3[,i] <- stock3[[i]][,5] } stock.close4 <-matrix(NA,nrow = 2517,ncol = 20) stock.volume4 <-matrix(NA,nrow = 2517,ncol = 20) for( i in 1:20){ stock.close4[,i] <- stock4[[i]][,4] stock.volume4[,i] <- stock4[[i]][,5] } ######function###### change <- function(data,col){ p <- rep(NA,2517) for(i in 2:2517){ p[i] <- data[i,col]-data[i-1,col] } return(p) } gain <- function(data,col){ 13
  • 14. tmp <- rep(NA,2516) tmp[change(data,col)[-1]>=0] <- change(data,col)[-1][change(data,col)[-1]>=0] tmp[change(data,col)[-1]<0] <- 0 tmp <- c(NA,tmp) return(tmp) } loss <- function(data,col){ tmp <- rep(NA,2516) tmp[change(data,col)[-1]<=0] <- change(data,col)[-1][change(data,col)[-1]<=0] tmp[change(data,col)[-1]>0] <- 0 tmp <- c(NA,tmp) return(tmp) } avg.gain <- function(data,col){ tmp <- rep(NA,2503) tmp[1] <- sum(stock.gain[(1+1):(1+14),col])/14 for(i in 2:2503){ tmp[i] <- (tmp[i-1]*13+stock.gain[(i+14),col])/14 } tmp <- c(rep(NA,14),tmp) return(tmp) } avg.loss <- function(data,col){ tmp <- rep(NA,2503) tmp[1] <- sum(stock.loss[(1+1):(1+14),col])/14 for(i in 2:2503){ tmp[i] <- (tmp[i-1]*13+stock.loss[(i+14),col])/14 } tmp <- c(rep(NA,14),tmp) return(tmp) } rsi <- function(data,col){ tmp <- rep(NA,2517) 14
  • 15. tmp[is.na(stock.avg.loss[,col])] <- NA tmp[stock.avg.loss[,col]==0] <- 100 tmp[(stock.avg.loss[,col]!=0)&is.na(stock.avg.loss[,col]!=0)==FALSE] <- 100-100/(1+data[(stock.av return(tmp) } indicator <- function(data,col){ tmp <- rep(NA,2517) tmp[data[,col]<30] <- 1 tmp[data[,col]>=70] <- -1 tmp[(data[,col]>=30)&(data[,col]<70)] <- 0 return(tmp) } account.portfolio <- function(data,col){ tmp <- rep(NA,2498) tmp[1] <- 100 for(i in 2:2498) { tmp[i] <- tmp[i-1]+data[i+19,col] } return(tmp) } value.each <- function(col){ tmp <- rep(NA,2498) for(i in 1:2498){ tmp[i] <- stock.close[19:2517,col][i]*account[,col][i] } return(tmp) } cash.change <- function(col){ tmp <- rep(NA,2498) for(i in 1:2498){ tmp[i] <- -stock.close[20:2517,col][i]*stock.indicator[20:2517,col][i] } return(tmp) } 15
  • 16. ###data preparation#### stock.gain <- matrix(NA,2517,100) for(i in 1:100){ stock.gain[,i] <- gain(stock.close,i) } stock.loss <- matrix(NA,2517,100) for(i in 1:100){ stock.loss[,i] <- loss(stock.close,i) } stock.avg.gain <- matrix(NA,2517,100) for(i in 1:100){ stock.avg.gain[,i] <- avg.gain(stock.close,i) } stock.avg.loss <- matrix(NA,2517,100) for(i in 1:100){ stock.avg.loss[,i] <-abs( avg.loss(stock.close,i)) } stock.rs <- rbind(matrix(NA,14,100),stock.avg.gain[15:2517,]/stock.avg.loss[15:2517,]) stock.rsi <- matrix(NA,2517,100) for(i in 1:100){ stock.rsi[,i] <- rsi(stock.rs,i) } stock.indicator <- matrix(NA,2517,100) for(i in 1:100){ stock.indicator[,i] <- indicator(stock.rsi,i) } account <- matrix(NA,2498,100) 16
  • 17. for(i in 1:100){ account[,i] <- account.portfolio(stock.indicator,i) } stock.value <- matrix(NA,2498,100) for(i in 1:100){ stock.value[,i] <- value.each(i) } stock.accum <- apply(stock.value,1,sum) cash.change.total <- matrix(NA,2498,100) for(i in 1:100){ cash.change.total[,i] <- cash.change(i) } cash.change.total[1,] <- 0 #cash change for each portfolio cash <- apply(cash.change.total, 1, sum) cash.accum <- rep(NA,2498) cash.accum[1] <- 10000 for(i in 2:2498){ cash.accum[i] <- cash.accum[i-1]+cash[i] } portfolio.accum <- cash.accum+stock.accum portfolio.accum <- matrix(portfolio.accum,ncol=1) openxlsx::write.xlsx(portfolio.accum,"portfoilo 10000.xlsx") cash.accum <- rep(NA,2498) cash.accum[1] <- 100000 for(i in 2:2498){ cash.accum[i] <- cash.accum[i-1]+cash[i] } 17
  • 18. portfolio.accum <- cash.accum+stock.accum portfolio.accum <- matrix(portfolio.accum,ncol=1) openxlsx::write.xlsx(portfolio.accum,"portfoilo 100000.xlsx") ####################################### 18