<p><div><div><div><div data-width="100" data-show-faces="false" data-send="true" data-layout="button_count" data-height="21" data-href="https://www.r-bloggers.com/trading-strategy-52-weeks-high-effect-in-stocks/"></div></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.quantinsti.com/blog/trading-strategy-52-weeks-high-effect-in-stocks/"> R programming</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<p><img sizes="(max-width: 1200px) 100vw, 1200px" alt="" class="wp-image-8526" src="https://i1.wp.com/www.quantinsti.com/wp-content/uploads/2017/05/Trading-Strategy-52-Weeks-High-Effect-in-Stocks_2.jpg?w=450&ssl=1" data-recalc-dims="1"></p>
<p>By <a target="_blank" rel="nofollow" href="https://www.linkedin.com/in/milind-paradkar-b37292107/">Milind Paradkar</a></p>
<p>In today’s algorithmic trading having a trading edge is one of the most critical elements. It’s plain simple. If you don’t have an edge, don’t trade! Hence, as a quant, one is always on a look out for good trading ideas. One of the good resources for trading strategies that have been gaining wide popularity is the Quantpedia site. Quantpedia has thousands of financial research papers that can be utilized to create profitable trading strategies.</p>
<p> </p>
<p><img sizes="(max-width: 541px) 100vw, 541px" alt="" class="wp-image-8507" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/05/Quantpedia_1.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>The “Screener” page on Quantpedia categorizes hundreds of trading strategies based on different parameters like Period, Instruments, Markets, Complexity, Performance, Drawdown, Volatility, Sharpe etc.</p>
<p> </p>
<p><img sizes="(max-width: 617px) 100vw, 617px" alt="" class="wp-image-8509" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/05/Quantpedia_2.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>Quantpedia has made some of these trading strategies available for free to their users. In this article, we will explore one such trading strategy listed on their site called the “52-Weeks High Effect in Stocks”.</p>
<h3><strong>52-Weeks High Effect in Stocks</strong></h3>
<p>(<a target="_blank" rel="nofollow" href="http://quantpedia.com/Screener/Details/18">http://quantpedia.com/Screener/Details/18</a>)</p>
<p>The Quantpedia page for this trading strategy provides a detailed description which includes the 52-weeks high effect explanation, source research paper, other related papers, a visualization of the strategy performance and also other related trading strategies.</p>
<h3><strong>What is 52-Weeks High Effect? </strong></h3>
<p>Let us put down the lucid explanation provided on Quantpedia here –</p>
<p><em>The “52-week high effect” states that stocks with prices close to the 52-week highs have better subsequent returns than stocks with prices far from the 52<strong>–</strong>week highs. Investors use the 52-week high as an “anchor” which they value stocks against. When stock prices are near the 52-week high, investors are unwilling to bid the price all the way to the fundamental value. As a result, investors’ under-react when stock prices approach the 52-week high, and this creates the 52-week high effect. </em></p>
<h3><strong>Source Paper</strong></h3>
<p>(<a target="_blank" rel="nofollow" href="http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1787378">http://papers.ssrn.com/sol3/papers.cfm?abstract_id=1787378</a>)</p>
<p>The Source paper, “Industry Information and the 52-Week High Effect” has been authored by Xin Hong, Bradford D. Jordan, and Mark H. Liu.</p>
<p><em>The financial paper says that traders use the 52-week high as a reference point which they evaluate the potential impact of news against. When good news has pushed a stock’s price near or to a new 52-week high, traders are reluctant to bid the price of the stock higher even if the information warrants it. The information eventually prevails and the price moves up, resulting in a continuation. It works similarly for 52-week lows.</em></p>
<p>The trading strategy developed by the authors buys stocks in industries in which stock prices are close to 52-week highs and shorts stocks in industries in which stock prices are far from 52-week highs. They found that the industry 52-week high trading strategy is more profitable than the individual 52-week high trading strategy proposed by George and Hwang (2004).</p>
<h3><strong>Framing our 52-Weeks High Effect Strategy using R programming</strong></h3>
<p>Having understood the 52-weeks High Effect, we will try to backtest a simple trading strategy using R programming. Please note that we are not trying to replicate the exact trading strategy developed by the authors in their research paper.</p>
<p>We test our trading strategy for a 3-year backtest period using daily data on around 140 stocks listed on the National Stock Exchange of India Ltd. (NSE).</p>
<p><strong>Brief about the strategy</strong> – The trading strategy reads the daily historical data for each stock in the list and checks if the price of the stock is near its 52-week high at the start of each month. We have shown how to check for this condition in step 4 of the trading strategy formulation process illustrated below. For all the stocks that pass this condition, we form an equal weighted portfolio for that month. We take a long position in these stocks at the start of the month and square off our position at the start of the next month. We follow this process for every month of our backtest period. Finally, we compute and chart the performance metrics of our trading strategy.</p>
<p>Now, let us understand the process of trading strategy formulation in a step-by-step manner. For reference, we have posted the R code snippets of relevant sections of the trading strategy under its respective step.</p>
<p><strong>Step 1: </strong>First, we set the backtest period, and the upper and lower thresholds values for determining whether a stock is near its 52-week high.</p>
<pre># Setting the lower and upper threshold limits
lower_threshold_limit = 0.90 # (eg.0.90 = 90%)
upper_threshold_limit = 0.95 # (eg.0.95 = 95%)

# Backtesting period (Eg. 1 = 1 year) minimum period selected should be 2 years.
noDays = 4</pre>
<p><strong>Step 2: </strong>In this step, we read the historical stock data using the read.csv function from R. We are using the data from Google finance and it consists of the Open/High/Low/Close (OHLC) &amp; Volume values.</p>
<pre># Run the program for each stock in the list
for(s in 1:length(symbol)){

print(s)

dirPath = paste(getwd(),&quot;/4 Year Historical Data/&quot;,sep=&quot;&quot;) 
fileName = paste(dirPath,symbol[s],&quot;.csv&quot;,sep=&quot;&quot;)
data = as.data.frame(read.csv(fileName))
data$TICKER = symbol[s]

# Merge NIFTY prices with Stock data and select the Close Price
data = merge(data,data_nifty, by = &quot;DATE&quot;) 
data = data[, c(&quot;DATE&quot;, &quot;TICKER&quot;,&quot;CLOSE.x&quot;,&quot;CLOSE.y&quot;)] 
colnames(data) = c(&quot;DATE&quot;,&quot;TICKER&quot;,&quot;CLOSE&quot;,&quot;NIFTY&quot;)
N = nrow(data)</pre>
<p><strong>Step 3: </strong>Since we are using the daily data we need to determine the start date of each month. The start date need not necessarily be the 1<sup>st</sup> of every month because the 1<sup>st</sup> can be a weekend or a holiday for the stock exchange. Hence, we write an R code which will determine the first date of each month.</p>
<pre># Determine the date on which each month of the backtest period starts

data$First_Day = &quot;&quot;

day = format(ymd(data$DATE),format=&quot;%d&quot;)
monthYr = format(ymd(data$DATE),format=&quot;%Y-%m&quot;)
yt = tapply(day,monthYr, min)

first_day = as.Date(paste(row.names(yt),yt,sep=&quot;-&quot;))
frows = match(first_day, ymd(data$DATE))
for (f in frows) {data$First_Day[f] = &quot;First Day of the Month&quot;}

data = data[, c(&quot;TICKER&quot;,&quot;DATE&quot;, &quot;CLOSE&quot;,&quot;NIFTY&quot;,&quot;First_Day&quot;)]</pre>
<p><strong>Step 4: </strong>Check if the stock is near the 52-week high mark. In this part, we first compute the 52-week high price for each stock. We then compute the upper and the lower thresholds using the 52-week high price.</p>
<p><strong>Example:</strong></p>
<p>If the lower threshold = 0.90, upper threshold = 0.95 and the 52-week high = 1200, then the threshold range is given by:</p>
<p>Threshold range = (0.90 * 1200) – (0.95 * 1200)</p>
<p>Threshold range = 1080 to 1140</p>
<p>If the stock price at the start of the month falls in this range, we then consider the stock to be near its 52-week high mark. We have also included one additional condition in the step. This condition checks whether the stock price in the past 30 days had reached the current 52-week high price and whether it is within the threshold range now. Such a stock will not be included in our portfolio as we assume that the stock price is in decline after reaching today’s 52-week high price.</p>
<pre># Check if the stock is near its 52-week high at the start of the each month

data$Near_52_Week_High = &quot;&quot; ; data$Max_52 = numeric(nrow(data)); 
data$Max_Not = numeric(nrow(data));

frows_tp = frows[frows >= 260]
for (fr in frows_tp){
 
   # This will determine the max price in the last 1 year (252 trading days)
   data$Max_52[fr] = max(data$CLOSE[(fr-252):(fr-1)]) 
 
  # This will check whether the max price has occurred in the last &quot;x&quot; days.
  data$Max_Not[fr] = max(data$CLOSE[(fr-no_max):(fr-1)]) 
 
  if ((data$CLOSE[fr] >= lower_threshold_limit * data$Max_52[fr])
      &amp; (data$CLOSE[fr] &lt;= upper_threshold_limit * data$Max_52[fr])
      &amp; (data$Max_Not[fr] != data$Max_52[fr]) == TRUE ){
  data$Near_52_Week_High[fr] = &quot;Near 52-Week High&quot;
  } else {
  data$Near_52_Week_High[fr] = &quot;Not Near 52-Week High&quot;
  }
 
}</pre>
<p><strong>Step 5:</strong> For all the stocks that fulfill the criteria mentioned in the step above, we create a long-only portfolio. The entry price equals the price at the start of the month. We square off our long position at the start of the next month. We consider the close price of the stock for our entry and exit trades.</p>
<pre># Enter into a long position for stocks at each start of month

data = subset(data,select=c(TICKER,DATE,CLOSE,NIFTY,First_Day,Max_52,Near_52_Week_High)
             ,subset=(First_Day==&quot;First Day of the Month&quot;))
data$NEXT_CLOSE = lagpad(data$CLOSE, 1)
colnames(data) = c(&quot;TICKER&quot;,&quot;DATE&quot;,&quot;CLOSE&quot;,&quot;NIFTY&quot;,&quot;First_Day&quot;,&quot;Max_52&quot;,&quot;Near_52_Week_High&quot;,
                   &quot;NEXT_CLOSE&quot;)


data$Profit_Loss = numeric(nrow(data)); data$Nifty_change = numeric(nrow(data));

for (i in 1:length(data$CLOSE)) { 
  if ((data$Near_52_Week_High[i] == &quot;Near 52-Week High&quot;) == TRUE){
  data$Profit_Loss[i] = round(data$CLOSE[i+1] - data$CLOSE[i],2)
  data$Nifty_change[i] = round(Delt(data$NIFTY[i],data$NIFTY[i+1])*100,2)
  } 
}

for (i in 1:length(data$CLOSE)) { 
  if ((data$Near_52_Week_High[i] == &quot;Not Near 52-Week High&quot;) == TRUE){
  data$Profit_Loss[i] = 0
  data$Nifty_change[i] = round(Delt(data$NIFTY[i],data$NIFTY[i+1])*100,2)
  } 
 
}</pre>
<p><strong>Step 6:</strong> In this step, we write an R code which creates a summary sheet of all the trades for each month in the backtest period. A sample summary sheet has been shown below. It also includes the Profit/Loss from every trade undertaken during the month.</p>
<pre># Create a Summary worksheet for all the trades during a particular month

final_data = final_data[-1,]
final_data = subset(final_data,select=c(TICKER,DATE,CLOSE,NEXT_CLOSE,Max_52,
                                        Near_52_Week_High,Profit_Loss,Nifty_change),
                                        subset=(Near_52_Week_High == &quot;Near 52-Week High&quot;))

colnames(final_data) = c(&quot;Ticker&quot;,&quot;Date&quot;,&quot;Close_Price&quot;,&quot;Next_Close_Price&quot;,
                         &quot;Max. 52-Week price&quot;,&quot;Is Stock near 52-Week high&quot;,
                         &quot;Profit_Loss&quot;,&quot;Nifty_Change&quot;)

merged_file = paste(date_values[a],&quot;- Summary.csv&quot;)
write.csv(final_data,merged_file)</pre>
<p><img sizes="(max-width: 731px) 100vw, 731px" alt="Monthly Trades Table" class="wp-image-8548" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/05/Quantpedia_Monthly_Trades_Table.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p><strong>Step 7: </strong>In the final step, we compute the portfolio performance over the entire backtest period and also plot the equity curve using the PerformanceAnalytics package in R. The portfolio performance is saved in a CSV file.</p>
<pre>cum_returns = Return.cumulative(eq_ts, geometric = TRUE)
print(cum_returns)

charts.PerformanceSummary(eq_ts,geometric=TRUE, wealth.index = FALSE)
print(SharpeRatio.annualized(eq_ts, Rf = 0, scale = 12, geometric = TRUE))</pre>
<p>A sample summary of the portfolio performance has been shown below. In this case, the input parameters to our trading strategy were as follows:</p>
<p><img sizes="(max-width: 209px) 100vw, 209px" alt="" class="wp-image-8531" src="https://i2.wp.com/www.quantinsti.com/wp-content/uploads/2017/05/Quantpedia_4.png?resize=209%2C133&ssl=1" data-recalc-dims="1"></p>
<h3><img sizes="(max-width: 731px) 100vw, 731px" alt="" class="wp-image-8545" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/05/Quantpedia_Equity_Table.png?w=450&ssl=1" data-recalc-dims="1"><strong>Plotting the Equity Curve</strong></h3>
<p><img sizes="(max-width: 730px) 100vw, 730px" alt="" class="wp-image-8539" src="https://i0.wp.com/www.quantinsti.com/wp-content/uploads/2017/05/Equity-Curve-52Week.png?w=450&ssl=1" data-recalc-dims="1"></p>
<p>As can be observed from the equity curve, our trading strategy performed well during the initial period and then suffered drawdowns in the middle of the backtest period. The Sharpe ratio for the trading strategy comes to 0.4098.</p>
<pre>Cumulative Return 1.172446

Annualized Sharpe Ratio (Rf=0%) 0.4098261</pre>
<p>This was a simple trading strategy that we developed using the 52-week high effect explanation. One can tweak this trading strategy further to improve its performance and make it more robust or try it out on different markets.</p>
<h3><strong>Next Step</strong></h3>
<p>You can explore other trading strategies listed on the <a target="_blank" rel="nofollow" href="http://quantpedia.com/">Quantpedia</a> site under their screener page and if interested you can <a target="_blank" rel="nofollow" href="http://quantpedia.com/Account/Register">sign up</a> to get access to hundreds of exciting trading strategies.</p>
<p>If you want to learn various aspects of <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/">Algorithmic trading</a> then check out our <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/epat/">Executive Programme in Algorithmic Trading (EPAT™)</a>. The course covers training modules like Statistics &amp; Econometrics, Financial Computing &amp; Technology, and Algorithmic &amp; Quantitative Trading. EPAT™ is designed to equip you with the right skill sets to be a successful trader. <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/epat/">Enroll now</a>!</p>
<p>The post <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/blog/trading-strategy-52-weeks-high-effect-in-stocks/">Trading Strategy: 52-Weeks High Effect in Stocks</a> appeared first on <a target="_blank" rel="nofollow" href="https://www.quantinsti.com/"></a>.</p>
<p>
<div>
<div>To <strong>leave a comment</strong> for the author, please follow the link and comment on their blog: <strong><a href="https://www.quantinsti.com/blog/trading-strategy-52-weeks-high-effect-in-stocks/"> R programming</a></strong>.</div>
<hr>
<a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers.com</a> offers <strong><a rel="nofollow" href="https://feedburner.google.com/fb/a/mailverify?uri=RBloggers">daily e-mail updates</a></strong> about <a title="The R Project for Statistical Computing" rel="nofollow" href="https://www.r-project.org/">R</a> news and <a title="R tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/search/data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/search/Big%20Data">Big Data, <a title="R jobs" rel="nofollow" href="https://www.r-users.com/">R jobs</a>, visualization (<a title="ggplot and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/search/map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/search/animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/search/sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/search/LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/search/SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/search/eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/search/git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/search/hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/search/Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/search/regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/search/PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/search/time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/search/trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/DGD3WWIu-Y0"></a></div>