## Calculate XIRR in SQL Server

 Author Message vijay.s Old Hand Group: General Forum Members Points: 399 Visits: 359 Hello All,Is there any way to calculate XIRR in SQL server using T-SQL.Kindly suggest.Thankx Eugene Elutin SSChampion Group: General Forum Members Points: 11862 Visits: 5478 That the good one!There are no such thing in SQL! You can code it yourself if you wish and have time to do so (you will need to find good algorithm first).Or use XLeratorDB product from www.westclintech.com, if you really need it and have some money to spend :-) _____________________________________________"The only true wisdom is in knowing you know nothing""O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D(So many miracle inventions provided by MS to us...)How to post your question to get the best and quick help vijay.s Old Hand Group: General Forum Members Points: 399 Visits: 359 can any one give me best algorithm for the same, so i can go ahead with development.If sample code provided then its save my time.Thankx Cory E. SSCommitted Group: General Forum Members Points: 1769 Visits: 10845 a quick google search on XIRR turned up this:http://forums.databasejournal.com/showthread.php?t=46094 -- Cory Eugene Elutin SSChampion Group: General Forum Members Points: 11862 Visits: 5478 OK,Here we are: 1. We create a sample table`create table txns( PmtAmount money ,PmtDate Datetime)insert into txns select -2750,'20080205'union select 1000,'20080705'union select 2000,'20090105'`2. Then we calculate your XIRR as per Excel (almost):`DECLARE @nGuessRate NUMERIC(18,10)SET @nGuessRate = 0.1 -- 10% - as per Excel XIRR defaultDECLARE @dtFirstPmtDate DATETIMEDECLARE @nRateChange NUMERIC(18,10)DECLARE @nResidual NUMERIC(18,10)DECLARE @nPrevResidual NUMERIC(18,10)DECLARE @nXIRR NUMERIC(18,10)SET @nRateChange = 0.1 -- starting point of the rate changeSELECT @dtFirstPmtDate=MIN(PmtDate) FROM txnsSELECT @nResidual = 10 ,@nPrevResidual = 1 ,@nXIRR = @nGuessRateDECLARE @nIteration SMALLINTSET @nIteration = 0 -- 100 is a maximum number of calc. iterations as per Excel XIRRWHILE @nIteration < 100 AND ABS((@nPrevResidual - @nResidual) / @nPrevResidual) > 1.0/POWER(10,8)BEGIN SET @nPrevResidual = @nResidual SET @nResidual = 0 SELECT @nResidual = @nResidual + PmtAmount/ POWER((1.0+@nGuessRate),(DATEDIFF(d,@dtFirstPmtDate,PmtDate)/365.0)) FROM txns SET @nXIRR = @nGuessRate IF @nResidual >= 0 BEGIN SET @nGuessRate = @nGuessRate + @nRateChange END ELSE BEGIN SET @nRateChange = @nRateChange / 2 SET @nGuessRate = @nGuessRate - @nRateChange END SET @nIteration = @nIteration + 1END-- Calculation resultSELECT @nXIRR AS XIRR`Now, you can wrap it into stored proc or sql function. Remember to check that your payment range contains at least one negative and one positive payment, otherwise you should return some error, check Excel XIRR documentation for other error conditions if any.BUT! It may not be what you want. You most likely want XIRR to be an aggregate function. You cannot implement it in T-SQL, but you can do it in .NET as CLR function. Or, buy the product I have told you about in the previous post.I might write some article about it if I have spare time...Good Luck _____________________________________________"The only true wisdom is in knowing you know nothing""O skol'ko nam otkrytiy chudnyh prevnosit microsofta duh!":-D(So many miracle inventions provided by MS to us...)How to post your question to get the best and quick help vijay.s Old Hand Group: General Forum Members Points: 399 Visits: 359 ok Elutin Thanx four your help raka.nandi SSC Rookie Group: General Forum Members Points: 36 Visits: 163 thanx ...but the xirr value is not marching with MS Excel bobthefinancialengineer Grasshopper Group: General Forum Members Points: 17 Visits: 26 An XIRR is just a function name in Excel, it is actually an IRR calculation when the timings for the cash flows are given using a date schedule. This then leads to discounting of the cash flows at the actual time period as opposed to periodic time periods in IRR calculationThere are more than one way to define the XIRR equation and there are scores of ways of finding the roots of this equation that results in one or more IRR valuesMy personal favorite algo to find roots of a given function is the popular Newton-Raphson method that was named after the two mathematicians who independently discovered this method independent of each other about more than two centuries ago. One is the famous inventor of modern day Calculus the English mathematician Sir Isaac Newton (whom it seem was Knighted by the King of England thus the title "Sir" is referenced. The other one is Joseph Raphson, I am not sure of his national origin but it sounds like an American name so who knows I didn't look it upCode may not always return an XIRR in such a case use a Guess rate other than the last one tried. In other case a Division by zero may be encountered when the differential is zero.`CREATE TYPE dbo.MyXirrTable AS TABLE ( theValue DECIMAL(19, 9) NOT NULL, theDate DATETIME NOT NULL )GOCREATE FUNCTION dbo.XIRR(@Sample MyXirrTable READONLY,@Rate DECIMAL(19, 9) = 0.1)RETURNS DECIMAL(38, 9)ASBEGINDECLARE @X DECIMAL(19, 9) = 0.0, @X0 DECIMAL(19, 9) = 0.1, @f DECIMAL(19, 9) = 0.0, @fbar DECIMAL(19, 9) = 0.0, @i TINYINT = 0,IF @Rate IS NULL SET @Rate = 0.1SET @X0 = @RateWHILE @i < 100 BEGIN SELECT @f = 0.0, @fbar = 0.0 SELECT @f = @f + theValue * POWER(1 + @X0, (-theDelta / 365.0E)), @fbar = @fbar - theDelta / 365.0E * theValue * POWER(1 + @X0, (-theDelta / 365.0E - 1)) FROM ( SELECT theValue, DATEDIFF(DAY, MIN(theDate) OVER (), theDate) AS theDelta FROM @Sample ) AS d IF @fbar = 0 RETURN NULL SET @X = @X0 - @f / @fbar If ABS(@X - @X0) < 0.00000001 RETURN @X SET @X0 = @X SET @i += 1 END RETURN NULLENDGO`The above code is based on financial functions found in this JavaScript library tadJS that itself is based upon tadXL dwain.c SSCoach Group: General Forum Members Points: 17063 Visits: 6431 The Newton-Raphson approach to finding roots can also be done in an rCTE:Exploring Recursive CTEs by Example My mantra: No loops! No CURSORs! No RBAR! Hoo-uh!My thought question: Have you ever been told that your query runs too fast?My advice:INDEXing a poor-performing query is like putting sugar on cat food. Yeah, it probably tastes better but are you sure you want to eat it?The path of least resistance can be a slippery slope. Take care that fixing your fixes of fixes doesn't snowball and end up costing you more than fixing the root cause would have in the first place.Need to UNPIVOT? Why not CROSS APPLY VALUES instead?Since random numbers are too important to be left to chance, let's generate some!Learn to understand recursive CTEs by example.Splitting strings based on patterns can be fast!My temporal SQL musings: Calendar Tables, an Easter SQL, Time Slots and Self-maintaining, Contiguous Effective Dates in Temporal Tables kayla_wilde SSC Rookie Group: General Forum Members Points: 32 Visits: 4 I've been using this and it works great but it doesn't work if the XIRR is negative, did you ever modify this code to handle that?