Conditional Tail Expectation calculation in Scala
It’s as simple as the following code. The Conditional Tail Expectation risk measure tells you how much on average you will lose if your returns are in the bottom X% quantile, based on a bootstrapped projected distribution. It is distribution agnostic – you give it the past returns and it randomly rearranges them (with replacement) to give you a number of projected returns over your required horizon. Not sure yet if the random function distorts that, because you are choosing the returns randomly, but the array indices probably are normally distributed. Can’t think about that right now, may or may not be a problem, but then it’s just a matter of getting a better random function. But I didn’t have to explain this. It is evident from the code. That’s the great thing about functional programming – it is the code, the specification, and the documentation. This took about half an hour to write, including consulting the latest Scala API. Ignoring the main(…) method, it more or less reads in English.
Note that in reality it’ll probably take you a bit more than that – a 5% CTE is useless as it means you’ll lose this much 1.5 times a month, and obvoiously there’s a lot more work in working out past returns, etc, but what I’m trying to say is, it’s way more than what some other programming languages can give you. And may be the returns shouldn’t be added but compounded, not sure about that either, but again, it illustrates the point – if I wanted to compound them, it’s just a change in the foldLeft function in sim.
package com.supplesoftware.finance.cte
object CTE {
def main(args:Array[String]):Unit =
print(calc.cte(Array(-3.0,-7,0,1.0,2.0,3.0,4.0,5.0,7.0), 10, 100))
}
package object calc {
def cte(pastMonthlyReturns:IndexedSeq[Double],
horizonInMonths:Int,
numberOfSims:Int) =
average(quantileMembers(
bootstrap(pastMonthlyReturns, horizonInMonths, numberOfSims)))
def average(distribution:Seq[Double]) =
distribution.foldLeft(0.0)(_+_/distribution.size)
def quantileMembers(distribution:IndexedSeq[Double]) =
distribution.sortWith((a,b)=>a < b).take(5)
def bootstrap(pastMonthlyReturns:IndexedSeq[Double], horizonInMonths:Int, numberOfSims:Int) =
(1 to numberOfSims).map(_=>sim(pastMonthlyReturns, horizonInMonths))
def sim(pastMonthlyReturns:IndexedSeq[Double], horizonInMonths:Int) =
(1 to horizonInMonths)
.map(_=>pastMonthlyReturns(random.nextInt(pastMonthlyReturns.size)))
.foldLeft(0.0)(_+_)
val random = new scala.util.Random
}
Filed under: Uncategorized | Leave a Comment
No Responses Yet to “Conditional Tail Expectation calculation in Scala”