Skip to main content

Proper way to calculate CAGR using T-Sql for SQL Server

After reading (and attempting the solutions offered in some) several articles about SQL and CAGR,  I have reached the conclusion that none of them would stand testing in a real-world environment. For one thing, the SQL queries offered as examples are overly complex or don't use the correct math for calculating proper CAGR. Since most DBAs don't have an MBA or Finance degree, let me help. 

The correct equation for calculating Compound Annual Growth Rate (as a percentage) is: 


Some key points about CAGR: 
  • The compounded annual growth rate (CAGR) is one of the most accurate ways to calculate and determine returns for anything that can rise or fall in value over time.
  • Investors can compare the CAGR of two alternatives to evaluate how well one stock performed against other stocks in a peer group or a market index.
  • The CAGR does not reflect investment risk.
You can read a full article about CAGR here

To calculate the CAGR for an investment in a language like VB is pretty straightforward.

Dim CAGR as Decimal = ((MarketValue / Basis) ^ (1 / (DaysHeld / 365)) - 1). 

The MarketValue is the ending value, and this can be calculated as the number of shares times last share price. Basis is simply the dollar amount paid for the investment. Because the formula is expecting N to be number of years, I use the DATEDIFF function to get the actual number of days I've held the investment, then divide by 365. I do not multiple by 100, because I'll format this result as a Percentage, by using either the FormatPercent function, or the DataFormatString="{0:P2} attribute in the GridView's BoundField.

In a SQL query, you have to use the POWER function to raise the overall return rate to the exponent of 1/n. This can get a little complicated with the use of parenthetical brackets to ensure the correct outcome. 

For this example, there will be two tables, called Stocks and StockPrices. Stocks will have fields named StockID, Symbol, DatePurchased, SharesHeld (among others), and StockPrices will have StockID, QuotedDate, and StockPrice.

Here's how the query works out: 

SELECT s.symbol, s.DatePurchased, sp.stockprice, s.sharesheld,  s.basis,

/* This is the statement for CAGR */
(Power(((sp.stockprice * s.SharesHeld) / s.Basis), 1 / (Cast(DATEDIFF(DAY,s.DatePurchased,getDate()) as float) / 365))-1) as 'CAGR'

FROM tblStocks s, tblStockPrices sp WHERE s.stockid = sp.stockid 
AND sp.quotedate = (select max(quotedate) from tblStockPrices) 
order by s.Symbol

Again, I've omitted the multiplication by 100 because I'll format the result as a percentage when I render it to the web page. 

Comments

Popular posts from this blog

California: A Model for the Rest of the Country, Part 2

Part 1 here . On Leaving the Golden State Guest Post by NicklethroweR . Posted on the Burning Platform. The fabled Ventura Highway is all that separates my artist loft from the beach where surfing first came to the United States. Both my balcony and front patio face the freeway at about eye level and I could easily smack a tennis ball right on to the ever busy 101. Access to the beach and boardwalk is very important to a Tourist Town such as mine and I can see one underpass from my balcony and another underpass from the patio. Further up the street are two pedestrian bridges. Both have been recently remodeled so that people can not use it to kill themselves by leaping down into traffic. The traffic, just like the spice, must flow and the elites that live here do not like to be inconvenienced as they dart about between Malibu and Santa Barbara. Another feature of living where I live would have to be the homeless, the insane and the drug addicts that wander this particular...

Factfulness: Ignorance about global trends. The world is actually getting better.

This newsletter was powered by  Thinkr , a smart reading app for the busy-but-curious. For full access to hundreds of titles — including audio — go premium and download the app today. From the layman to the elite, there is widespread ignorance about global trends. Author and international health professor, Hans Rosling, calls Factfulness  “his very last battle in [his] lifelong mission to fight devastating global ignorance.” After years of trying to convince the world that all development indicators point to vast improvements on a global scale, Rosling digs deeper to explore why people systematically have a negative view of where humanity is heading. He identifies a number of deeply human tendencies that predispose us to believe the worst. For every instinct that he names, he offers some rules of thumb for replacing this overdramatic worldview with a “factful” one. In 2017, 20,000 people across fourteen countries were given a multiple-choice quiz to assess basic global literac...