<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/reproducible-finance-with-r-the-sharpe-ratio/"></div></div><div><a data-url="https://www.r-bloggers.com/reproducible-finance-with-r-the-sharpe-ratio/" data-counturl="https://www.r-bloggers.com/reproducible-finance-with-r-the-sharpe-ratio/" data-count="horizontal" data-text="Reproducible Finance with R: The Sharpe Ratio" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<div>
(This article was first published on <strong><a href="https://www.rstudio.com/rviews/2016/11/09/reproducible-finance-with-r-the-sharpe-ratio/"> RStudio</a></strong>, and kindly contributed to <a rel="nofollow" href="https://www.r-bloggers.com/">R-bloggers)</a> </div>
<div>

<div>
<p>by Jonathan Regenstein</p>
<p>Financial applications were an early driving force behind the adoption of the R language, but as data science becomes increasingly critical to banks, hedge funds, investment managers, data providers, exchanges, etc., R is becoming even more important to Finance. We are excited and inspired by what the future holds in the brave new world of data-driven financial institutions. In this first post of what we hope will be a regular series about Finance, R and RStudio, we present a classic use case: import stock data, build a portfolio, and calculate the Sharpe Ratio. We use the new RStudio IDE Notebooks tool to emphasize reproducibility.</p>
<p>By way of a brief roadmap, we’ll start with a function that grabs monthly stock returns and saves those monthly returns as an xts object in the global environment. With that function, we will create three xts objects of monthly returns, and merge those three xts objects into one object, before passing that merged object to dygraphs to peek at the individual stocks. Then, we move on to build a portfolio by selecting asset weights and calculating the portfolio monthly returns. Next, we will calculate the growth of a dollar invested in that portfolio (which is what matters to us) over time, and save the results to an xts object. Dygraphs will come in handy again for the portfolio visualizations. Finally, we will calculate the Sharpe Ratio.</p>
<p>Before we get to the fun stuff – the code itself! – I will note that these posts aim to be useful to R coders who either work in the financial industry or want to work in the financial industry. At times the posts will contain ideas or paradigms that are good practice in the institutional context but perhaps not directly relevant to an R user on the lookout for one-off coding tricks. That is a good segue into the structure and content of this Notebook, which could be fit comfortably into one setup chunk and one substantive code chunk, instead of my five chunks.</p>
<p>I chose to use five chunks to demonstrate how this document might fit into the workflow of a team of analysts with varying levels of R knowledge. Team workflow + reproducibility is going to be a recurrent theme in this series, as it is a recurrent theme at financial institutions using the RStudio toolchain.</p>
<p>Five chunks breaks this code into simple steps: build an import function, choose/visualize the stocks, choose portfolio weights/visualize returns, and calculate the Sharpe Ratio. From a team workflow perspective, this structure could be an introductory template for analysts that are just learning R, or it could serve as the starting point for advanced users who want to use the data import and return functions before they add complexity. For example, calculating the Sharpe Ratio is just the beginning of risk-to-volatility analysis, and most shops have their own proprietary algorithms/models to advance the analysis. Beginners or advanced users could start with a common Notebook template like this one, to standardize the data import and basic visualization workflow.</p>
<p>Now, onwards to the setup code chunk, where we load three packages: quantmod to download the data, PerformanceAnalytics to run portfolio calculations, and dygraphs to graph time series objects. We will also create a function to import stock data.</p>
<p><iframe height="420px" width="450px" src="https://beta.rstudioconnect.com/content/2091/Block1.html"></iframe>
<p>The monthly_stock_returns function above takes 2 parameters, a stock symbol and a year. Note that we could have included a third parameter called something like ‘period’ if we wanted the ability to grab periods other than monthly returns. For example, we can envision a desire to look at annual, weekly or daily returns. Here, I force monthly returns because I don’t want to allow different period options. It’s a choice driven by the purpose of this Notebook – which here is focused on monthly returns.</p>
<p>In the next chunk, we choose three stock tickers and a starting year argument for the monthly_stock_returns function. Then, we merge them into one xts object and graph their individual performances over time.</p>
<p><iframe height="870px" width="450px" src="https://beta.rstudioconnect.com/content/2092/Block2.html"></iframe>
<p>Nothing earth-shattering thus far: we have an xts object of three time series and have seen that one of them had weird behavior in April of 2014 (a Google stock split). We’ll ignore that behavior for this example and go on to constructing a portfolio, which means finding the monthly returns of a weighted combination of assets. Unsurprisingly, we start out by choosing those weights. </p>
<p><iframe height="750px" width="450px" src="https://beta.rstudioconnect.com/content/2093/Block3.html"></iframe>
<p>Now, instead of looking at monthly returns, let’s look at how $1 would have grown in this portfolio. </p>
<p><iframe height="650px" width="450px" src="https://beta.rstudioconnect.com/content/2094/Block4.html"></iframe>
<p>A dollar would have grown quite nicely in this portfolio – about 2.5x – fantastic. Now let’s look at the risk/reward of this portfolio by calculating the Sharpe Ratio. Briefly, the Sharpe Ratio is the mean of the excess monthly returns above the risk-free rate, divided by the standard deviation of the excess monthly returns above the risk-free rate. This is the formulation of the Sharpe Ratio as of 1994; if we wished to use the original formulation from 1966 the denominator would be the standard deviation of portfolio monthly returns. Learn more <a target="_blank" rel="nofollow" href="http://web.stanford.edu/~wfsharpe/art/sr/sr.htm">here</a>.</p>
<p>In other words, the Sharpe Ratio measures excess returns per unit of volatility, where we take the standard deviation to represent portfolio volatility. The Sharpe Ratio was brought to us by Bill Sharpe – arguably the most important economist for modern investment management as the creator of the Sharpe Ratio, CAPM and Financial Engines, a forerunner of today’s robo-advisor movement.</p>
<p>In the code chunk below, we’ll calculate the Sharpe Ratio in two ways.</p>
<p>First, we’ll use the Return.excess function from PerformanceAnalytics to calculate a time series of monthly excess returns. Two arguments need to be supplied: the time series of returns and the risk-free rate. The function will return a time series of excess returns, and we’ll take the mean of that time series to get the numerator of the Sharpe Ratio. Then we’ll divide by the standard deviation of the that time series to get the Sharpe Ratio.</p>
<p>Our second method is a bit easier. We’ll use the SharpeRatio function in PerformanceAnalytics, for which we’ll supply two arguments: a time series of monthly returns and risk-free rate.</p>
<p>For both methods I use a risk-free rate of .03% as the approximate mean of the 1-month Treasury bill rate since 2010. I’ll cover a quick way to grab this and other data via Quandl in a future post.</p>
<p><iframe height="240px" width="450px" src="https://beta.rstudioconnect.com/content/2095/Block5.html"></iframe>
<p>Using the Return.excess function and then dividing by the standard deviation of excess returns, the Sharpe Ratio is <code>sharpe_ratio_manual[,1]</code>= 0.2018.</p>
<p>Using the built in SharpeRatio function, the Sharpe Ratio is <code>sharpe_ratio[1,]</code> = 0.2018.</p>
<p>Alright, we have built a portfolio and calculated the Sharpe Ratio – and also set up some nice reusable chunks for data import, portfolio construction and visualization. We haven’t done anything terribly complex but this can serve as a useful paradigm to any collaborators, including our future selves, who want to reproduce this work, learn from this work, or expand upon this work.</p>
<p>In the next post, we will create a Shiny app to let users enter their own stock tickers, starting year, portfolio weights and risk-free rate, and then calculate a portfolio Sharpe Ratio. See you next time!</p>
</div>
</div>
<p><div><div><div><div data-width="55" data-show-faces="false" data-send="true" data-layout="box_count" data-height="62" data-href="https://www.r-bloggers.com/reproducible-finance-with-r-the-sharpe-ratio/"></div></div><div><a data-url="https://www.r-bloggers.com/reproducible-finance-with-r-the-sharpe-ratio/" data-counturl="https://www.r-bloggers.com/reproducible-finance-with-r-the-sharpe-ratio/" data-count="vertical" data-text="Reproducible Finance with R: The Sharpe Ratio" class="twitter-share-button" data-via="rbloggers" href="https://twitter.com/share"></a></div><div></div></div><div></div></div>
<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.rstudio.com/rviews/2016/11/09/reproducible-finance-with-r-the-sharpe-ratio/"> RStudio</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/?s=tutorial">tutorials</a> on topics such as: <a title="Data science" rel="nofollow" href="https://www.r-bloggers.com/?s=data%20science">Data science</a>, <a title="Big Data" rel="nofollow" href="https://www.r-bloggers.com/?s=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/?s=ggplot2">ggplot2</a>, <a title="Boxplots using lattice and ggplot2 tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=boxplot">Boxplots</a>, <a title="Maps and gis" rel="nofollow" href="https://www.r-bloggers.com/?s=map">maps</a>, <a title="Animation in R" rel="nofollow" href="https://www.r-bloggers.com/?s=animation">animation</a>), programming (<a title="RStudio IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=RStudio">RStudio</a>, <a title="Sweave and literate programming" rel="nofollow" href="https://www.r-bloggers.com/?s=sweave">Sweave</a>, <a title="LaTeX in R" rel="nofollow" href="https://www.r-bloggers.com/?s=LaTeX">LaTeX</a>, <a title="SQL and databases" rel="nofollow" href="https://www.r-bloggers.com/?s=SQL">SQL</a>, <a title="Eclipse IDE for R" rel="nofollow" href="https://www.r-bloggers.com/?s=eclipse">Eclipse</a>, <a title="git and github, Version Control System" rel="nofollow" href="https://www.r-bloggers.com/?s=git">git</a>, <a title="Large data in R using Hadoop" rel="nofollow" href="https://www.r-bloggers.com/?s=hadoop">hadoop</a>, <a title="Web Scraping of google, facebook, yahoo, twitter and more using R" rel="nofollow" href="https://www.r-bloggers.com/?s=Web+Scraping">Web Scraping</a>) statistics (<a title="Regressions and ANOVA analysis tutorials" rel="nofollow" href="https://www.r-bloggers.com/?s=regression">regression</a>, <a title="principal component analysis tutorial" rel="nofollow" href="https://www.r-bloggers.com/?s=PCA">PCA</a>, <a title="Time series" rel="nofollow" href="https://www.r-bloggers.com/?s=time+series">time series</a>, <a title="finance trading" rel="nofollow" href="https://www.r-bloggers.com/?s=trading">trading</a>) and more...
<img height="1" alt="" width="1" src="http://feeds.feedburner.com/~r/RBloggers/~4/5qT8QmxzXM4"></a></div>