## A bit of fighting with f# and lambdas

Which way is the best to learn? Of cource, doing something by trial and error. I am now doing some command-line interface with command and so on; here’s a code that describes my commands

type Command =
| Exit of string * string
| Action of string * string * (unit -> unit)
| Params of string * string * (string list -> unit)
let getName cmd =
match cmd with
| Exit(n, d) -> n,d
| Action(n, d, _) -> n,d
| Params(n, d, _) -> n,d
let listCommands commands =
List.iter (fun cmd -> (getName cmd) ||> printfn "%-20s %s") commands


Now the latter line of code is something I’d like to overpower. I want to write it as

    List.iter magic commands


Of course, I could write it like that:

    let magic cmd = (getName cmd) ||> printfn "%-20s %s"
List.iter magic commands


But I want my magic to be inline and curried. Hence it must be like let magic cmd = something cmd

First, what my something type should be? It must be $Command -> unit$.
Next, what operators and types do I have? Let me denote string = s and unit = u. Here are the operations and types:

• <|| ($\alpha$ later on): (s -> s -> u) -> s*s -> u
• printf "%s %s" ($\beta$ later on): s -> s -> u
• getName ($\gamma$ later on): Command -> s*s
• cmd ($q$ later on): Command

So my calculation currently looks like $\alpha(\beta, \gamma(q))$ and I need to convert it to some function $\psi = \psi(q)$. How can I simplify my expression?

First I note that $\alpha(\beta, \gamma(q)) = \alpha$ <| $\beta$ <| $\gamma (q)$
This corresponds to the following code:

 List.iter (fun cmd -> (<||) <| printfn "%-20s %s" <| (getName cmd)) commands 

Next I combine $\alpha$ and $\beta$ into $\delta = \alpha$ <| $\beta$ and calculation becomes $\delta$ <| $\gamma (q)$. It corresponds to the following code:

 List.iter (fun cmd -> ((<||) <| printfn "%-20s %s") <| (getName cmd)) commands 

Now types are:

• $\delta$: s*s -> u
• $\gamma$: Command -> s*s
• $q$: Command

Now I combine $\delta$ and $\gamma$ into $\kappa= \gamma(\delta) = \gamma$ << $\delta$ of type Command -> u

And the code now is
 List.iter (fun cmd -> (getName >> ((<||) <| printfn "%20s %s")) cmd) commands 

And that’s it. I can curry it:
 List.iter (getName >> ((<||) <| printfn "%20s %s")) commands 

Ugly but nice! And after some flipping we can obtain it as follows:

 List.iter ((<||) <| printfn "%20s %s" << getName) commands 

Filed under f#, programming

## FRN calculations guide. Part 1. Price

<disclaimer>
In the text below no credit risk is taken into account
</disclaimer>

Surprisingly there’s very little to read on plain vanilla FRNs. Maybe the reason is that they are generally considered to be covered in swaps section. Indeed, IRS is effictively straight bond + FRN, hence where there are some words on how to handle a floating leg.

Yet, most interesting thing they do is they show that FRN must price at par at issue date, and believe that is is perfectly enough. And no words on FRN yield or even duration.

Hence I did much effort to find comrehensive FRN description. I failed, but yet I have now much data and I will try to aggregate it as follows.

Now, every good boy and girl knows that FRNs must price at par. Why? I have several arguments all leading to same result.

#### Induction

Here’s a picture.

$R_i$ is a one-period interest rate effective at time $t_i$.

• Now, at time $t_{N-1}$ we buy one-period FRN. It’s payments are already known: it is $1 + R_{N-1}$. Hence, its price is $\frac{1 + R_{N-1}}{1 + R_{N-1}} = 1$
• At time $t_{N-2}$ we buy a two period FRN. Here’s a picture:

Proceeds from two-period FRN can be split into proceeds fron two one-period FRN, first is one-period FRN starting immediately, second is one-period FRN starting one period from now. Look at this:

This means, that price of our two-period FRN must also be $1$. Let us see: we invest $1$ in first FRN, and in the end of the first period we obtain $1+R_{N-2}$. From this amount we invest $1$ into second FRN, and in the end of the second period we obtain $1 + R_{N-1}$. This replicates cash flows from two-period FRN. Voila.

#### Just some calculations

Frankly I hate the way of the proof above. It’s all about the words, you know. I love old plain formulas. Today, after having broken two pencils up and tearing twenty sheets of paper apart I have finally obtained my long-awaited Nobel.

$P = \frac{R_0}{1+R_0} + \frac{R_1}{(1+R_0)(1+R_1)} + \dots + \frac{R_{N-2}}{(1+R_0)(1+R_1)\dots(1+R_{N-2})}+ \frac{1+R_{N-1}}{(1+R_0)(1+R_1)\dots(1+R_{N-1})}$

Let me arrange them so that to have a common divisor. The GCD is essentially $(1+R_0)(1+R_1)\dots(1+R_{N-1})$.

Hence, the numerator now is a sum of the following terms:

• First term becomes $R_0 (1+R_1) \dots (1+R_{N-1})$
• Second term becomes $R_1(1+R_2) \dots (1+R_{N-1})$
• Following terms become $\dots$
• $N-2$-th term now is $R_{N-3}(1+R_{N-2})(1+R_{N-1})$
• The last but one term is $R_{N-2}(1+R_{N-1})$
• And the last term doesn’t change and stays $1+R_{N-1}$

Now we start adding terms together from last to first. Summing two last terms we get $(1+R_{N-2})(1+R_{N-1})$.

Next, we add $N-2$-th term. The sum now is $(1+R_{N-3})(1+R_{N-2})(1+R_{N-1})$. Can you see it? Adding all the other terms up we have $(1+R_0)(1+R_1)\dots(1+R_{N-1})$ in numerator, and it is exactly our denominator. All terms cancel out, and we have perfect $1$ without any excessive words.

That’s all for today. Next sessions will be devoted to spreads, durations and yields.

Filed under Quant finance, Uncategorized

## nUnit vs xUnit threading model

I spent half of day trying to figure out why the heck my test doesn’t work. I remeber he was up and running and now… I do not receive events from some freaking COM object I sorely need.

I developed console app which does all the same. It worked fine.

I played with test’s target architecture – no success.

And then! I remembered! That I! Migrated my stupid test from nUnit to xUnit! I reverted to nUnit and the test worked successfully.

Positive outcomes:

• Now I know that there MUST BE some difference in threading models between nUnit and xUnit

Negative outcomes:

• Lost day of work
• Lost couple of tests deleted in outrage
• I hate the world much more than earlier

Conclusion: Mind the differences! Though I don’t know what are they about (15 seconds of googling didn’t help)

Filed under Uncategorized

## First rule of IoC

Do not use it in your own well-known and not-supposed-to-be-changed class hierarchies

Filed under Uncategorized

## Why VB.Net is better than C#?

I’m kidding, it’s not better.
But it does have some options which are less convenient in C#:

• Default properties and auto-implemented properties
• VB.Net has Default keyword, C# requires using attributes.

Class MyClass
' default property
Default Property MyProperty(ByVal index As Integer) As String
...
End Property

' auto property
Public Property Name As String
End Class

[DefaultProperty("MyProperty")]
class MyClass {
// default property
String MyProperty(int index)  {
...
}

// auto property
public string Name { get; set; }
}

• Events and custom events
• In case of events I better like VB’s AddHandler, RemoveHandler and RaiseEvent instead of C# +=, -= and EventName(); The worst thing in C# is that I have to check if EventName != null before raising it, i.e. VB code

Public Event SomethingHappened As Action
Public Sub Notify()
RaiseEvent SomethingHappened()
End Sub


is equivalent to

public event Action SomethingHappened;
public void Notify() {
if (SomethingHappened != null)
SomethingHappened();
}


Semicolon cancer and unnecessary null checking detected.

• Embedded XML
• Just compare

Imports <xmlns="http://www.adventure-works.com">

Dim xmlTree1 As XElement = _
<Root>
<Child1>1</Child1>
<Child2>2</Child2>
<Child3>3</Child3>
<Child4>4</Child4>
<Child5>5</Child5>
<Child6>6</Child6>
</Root>

Dim xmlTree2 As XElement = _
<Root>
<%= From el In xmlTree1.Elements() _
Where el.Value >= 3 And el.Value <= 5 _
Select el %>
</Root>

Console.WriteLine(xmlTree2)

XNamespace aw = "http://www.adventure-works.com";
XElement xmlTree1 = new XElement(aw + "Root",
new XElement(aw + "Child1", 1),
new XElement(aw + "Child2", 2),
new XElement(aw + "Child3", 3),
new XElement(aw + "Child4", 4),
new XElement(aw + "Child5", 5),
new XElement(aw + "Child6", 6)
);

XElement xmlTree2 = new XElement(aw + "Root",
from el in xmlTree1.Elements()
where((int)el >= 3 && (int)el <= 5)
select el
);
Console.WriteLine(xmlTree2);

• Braces layouts
• VB.Net has no stupid braces! And in C# I’ve already spent much time teaching R# and VS getting along with each other and put braces in the way I love it. And I’m still fighting

• Or and OrElse, And and AndAlso
• This is much more readable than C# | vs || and & vs &&.

C# beats VB.Net in:

• Extension methods
• Situation is reverse to default properties. Now it is VB who needs using attributes, while C# employs this keyword.
Not sexy:

    <Extension()>
Public Function Belongs(Of T)(ByVal x As T, ByVal whereTo As IEnumerable(Of T)) As Boolean
Return whereTo.Contains(x)
End Function


Sexy:

    public bool Belongs<T>(this T x, IEnumerable<T> whereTo) {
return whereTo.Contains(x)
}

• ?? operator
• R# support
• Resharper is sometimes stupid and glitchy with VB.Net, and it is much smarter in C#. Sometimes, when transforming LINQ exressions in VB.Net, it even crushed VS.

• Lambdas
• x => x + 2


looks better than

Function(x) x + 2


and

(x, y) => {
return Math.Sin(x+y);
}


is better than

Function(x,y)
Return Math.Sin(x+y)
End Function


Amen.

Filed under Uncategorized

## Black-Scholes Formula for Exchange Option

I reproduce my answer from Quant StackExchange

That’s a great question and it is what I always wanted to try to do.

I guess I found a solution using PDE approach. Change of numeraire would be more intuitive indeed, but I am not very good in stochastic calculus.

The idea is as follows:

1) Let’s consider portfolio $\Pi = V(X,Y,t) - \Delta_X X - \Delta_Y Y$.
I will found $\Delta_X$ and $\Delta_Y$ such that portfolio $\Pi$ would be riskless and earn risk-free rate of return $latexr$: $d\Pi = r\Pi dt$.

Assumption: $dX = \mu_X X dt + \sigma_X X dW^X$, $dY = \mu_Y Y dt + \sigma_Y Y dW^Y$ and $dW^X dW^Y = \rho dt$.

Hence, applying Ito’s lemma I obtain:
$d\Pi = \frac{\partial V}{\partial t} dt + \frac{\partial V}{\partial X} dX + \frac{\partial V}{\partial Y} dY + \frac{1}{2} \sigma_X^2 X^2 \frac{\partial^2 V}{\partial X^2} dt+ \frac{1}{2} \sigma_Y^2 Y^2 \frac{\partial^2 V}{\partial Y^2} dt+ \rho \sigma_X\sigma_Y XY \frac{\partial^2 V}{\partial X\partial Y} dt - \Delta_X dX - \Delta_Y dY =$

$\left( \frac{\partial V}{\partial t} + \frac{1}{2} \sigma_X^2 X^2 \frac{\partial^2 V}{\partial X^2}+ \frac{1}{2} \sigma_Y^2 Y^2 \frac{\partial^2 V}{\partial Y^2} + \rho \sigma_X\sigma_Y XY \frac{\partial^2 V}{\partial X\partial Y} \right)dt + \left(\frac{\partial V}{\partial X} - \Delta_X \right) dX + \left(\frac{\partial V}{\partial Y} - \Delta_Y \right) dY$.

And all this is equal to $d\Pi = r\Pi dt = r\left(V - \Delta_X X - \Delta_Y Y\right)dt$

Now, set $\frac{\partial V}{\partial Y} = \Delta_Y$ and $\frac{\partial V}{\partial X} = \Delta_X$.

Left-hand side becomes $\left(\frac{\partial V}{\partial t} + \frac{1}{2} \sigma_X^2 X^2 \frac{\partial^2 V}{\partial X^2}+ \frac{1}{2} \sigma_Y^2 Y^2 \frac{\partial^2 V}{\partial Y^2} + \rho \sigma_X\sigma_Y XY \frac{\partial^2 V}{\partial X\partial Y}\right) dt$

Right-hand side is now $r\left(V - \frac{\partial V}{\partial X} X - \frac{\partial V}{\partial Y} Y\right)dt$

The PDE is now $\frac{\partial V}{\partial t} + \frac{1}{2} \sigma_X^2 X^2 \frac{\partial^2 V}{\partial X^2}+ \frac{1}{2} \sigma_Y^2 Y^2 \frac{\partial^2 V}{\partial Y^2} + \rho \sigma_X\sigma_Y XY \frac{\partial^2 V}{\partial X\partial Y} = r\left(V - \frac{\partial V}{\partial X} X - \frac{\partial V}{\partial Y} Y\right)$, or

$\frac{\partial V}{\partial t} + \frac{1}{2} \sigma_X^2 X^2 \frac{\partial^2 V}{\partial X^2}+ \frac{1}{2} \sigma_Y^2 Y^2 \frac{\partial^2 V}{\partial Y^2} + \rho \sigma_X\sigma_Y XY \frac{\partial^2 V}{\partial X\partial Y} + r\frac{\partial V}{\partial X} X + r \frac{\partial V}{\partial Y} Y = rV$

I forgot: the boundary condition is $V(X, Y, T) = (X - Y)^+$

2) Now, in order to solve this crazy PDE i will use substitution:
$Z = \frac{X}{Y}$ and $V(X,Y,t) = G(Z, t)$.

Thanks to [Wolfram Alpha][1], I have:

$\frac{\partial V}{\partial X} = \frac{1}{Y} \frac{\partial G}{\partial Z}$

$\frac{\partial V}{\partial Y} = -\frac{X}{Y} \frac{\partial G}{\partial Z}$

$\frac{\partial^2 V}{\partial X^2} = -\frac{1}{Y^2} \frac{\partial^2 G}{\partial Z^2}$

$\frac{\partial^2 V}{\partial Y^2} = \frac{X\left(2Y\frac{\partial G}{\partial Z}+X\frac{\partial^2 G}{\partial Z^2}\right)}{Y^4}$

$\frac{\partial^2 V}{\partial XY} = -\frac{Y\frac{\partial G}{\partial Z}+X\frac{\partial^2 G}{\partial Z^2}}{Y^3}$

Substituting into previous equation and cancelling the terms out we obtain:

$\dot{G} + [\sigma_X^2-\rho \sigma_X \sigma_Y]ZG' + \frac{1}{2}[\sigma_X^2-2\rho \sigma_X \sigma_Y + \sigma_Y^2]Z^2G'' = rG$, or

$\dot{G} + \mu_GZG' + \frac{1}{2}\sigma_G^2 Z^2G'' = rG$, where

$\dot{G} = \frac{dG}{dt}$, $G' = \frac{dG}{dZ}$

$\mu_G = \sigma_X^2-\rho \sigma_X \sigma_Y$, $\sigma_G = \sqrt{\sigma_X^2-2\rho \sigma_X \sigma_Y + \sigma_Y^2}$

And the boundary condition is $G(Z,T) = Y(Z - 1)^+$

3) Now the question is what to do with that $Y$ in the equation above? I employ next change of variables: $G(Z) = YF(Z)$.

Thanks to paper and pencil, I have:

$G' = (YF)' = Y\left(F' - \frac{F}{Z}\right)$ and $G'' = \left((YF)'\right)' = \text{after some calculations} = YF''$

Plugging this into $Z$‘s PDE we obtain:

$\dot{F} + \mu_G Z F' + \frac{1}{2} \sigma_G^2 Z^2 F'' = (r+ \mu_G)F$
with boundary condition $F(Z,T) = (Z-1)^+$

Now denote $r^* = r+ \mu_G$ and equation becomes: $\dot{F} + (r^* - r) Z F' + \frac{1}{2} \sigma_G^2 Z^2 F'' = r^* F$

4) Now $r^*$ works like new risk-free rate and $r$ is like $Z$‘s dividend yield and we can apply well-known formula for option on asset with continiously paid dividends:

$F(Z, T) = e^{-r^*T} N(d_1) Z_0 - e^{-rT} N(d_2)$, where
$d_{1,2} = \frac{1}{\sigma_G\sqrt{T}}\left[\ln\left(Z_0\right)+\left(r^* - r \pm\frac{\sigma_G^2}{2}\right)T\right] =\frac{1}{\sigma_G\sqrt{T}}\left[\ln\left(Z_0\right)+\left(\mu_G \pm\frac{\sigma_G^2}{2}\right)T\right]$.

5) Now $V = e^{-r^*T} N(d_1) X_0 - e^{-rT} N(d_2) Y_0$, where
$d_{1,2} =\frac{1}{\sigma_G\sqrt{T}}\left[\ln\left(\frac{X_0}{Y_0}\right)+\left(\mu_G \pm\frac{\sigma_G^2}{2}\right)T\right]$, where

$r^* = r+ \mu_G$

$\mu_G = \sigma_X^2-\rho \sigma_X \sigma_Y$

$\sigma_G = \sqrt{\sigma_X^2-2\rho \sigma_X \sigma_Y + \sigma_Y^2}$

Hope I was correct.

I also hope somebody would be able to propose any better solution, maybe using martingale approach.

Filed under Uncategorized

## Binomial tree calibrated to yield curve and volatility structure in C#

In case anyone finds it useful, here it is. I employed backward induction, which means $O(N^2)$ calibration time, and my solver is disgustingly primitive, but it is simple and it works. And it uses $O(N)$ memory.
Usecase is:

        public void Calculate() {
var tree = new BinomialTree(
new[] {0.0608, 0.0611, 0.0621, 0.0631, 0.0655},
new[] {0.00, 0.17, 0.16, 0.15, 0.13});
// now you can use tree.TreeRate(i,j) function to find rates in tree nodes
}


And the code is:

public class Solver {
public double? Solve(Func<double, double> what, double from, double to) {
Debug.Assert(Math.Sign(what(from))!= Math.Sign(what(to)), "Function must be of different signs on borders");
do {
var mid = (to + from)/2;
var valOnTo = what(to);
var valOnMid = what(mid);
if (Math.Sign(valOnTo) != Math.Sign(valOnMid))
from = mid;
else to = mid;
} while (Math.Abs(from-to) > 10e-5);
return (to + from) / 2;
}
}

public class BinomialTree {

/// <summary>
/// Calculates interest rate in (i, j) node in tree
/// </summary>
/// <param name="i">number of time step</param>
/// <param name="j">number of point by vertical axis, j = 0 is the highest, j = i is the lowest</param>
/// <returns>Double value - an interest rate in (i, j) node in tree</returns>
public double TreeRate(int i, int j) {
Debug.Assert(i < _n && j < _n && j <= i, "Requested node is out of the tree");
return _treeRates[i]*Math.Exp(-2*_treeVols[i]*j);
}

public BinomialTree(double[] rates, double[] vols, double[] terms = null) {
Debug.Assert(rates.Length == vols.Length, "Count of rates and volatilities must be equal");

_n = rates.Length;
_treeRates = new double[_n];
_treeVols = vols;
if (terms != null) {
Debug.Assert(terms.Length == vols.Length, "Count of rates and volatilities must be equal");
_treeTerms = terms;
} else {
_treeTerms = new double[_n];
for (var i = 0; i < _n; i++) _treeTerms[i] = i+1;
}
_treeRates[0] = rates[0];

var solver = new Solver();
for (var i = 1; i < _n; i++) {
// 1) calculating price of ZCB with term i and rate r[i]
var price = Math.Exp(-rates[i]*_treeTerms[i]);

var num = i; // to avoid using cycle variable in clojure

// 2) finding rate which would make bond price equal to calculated price
var rt = solver.Solve(rate => EvaluatePrice(rate, num + 1) - price, 0.00, 1.00);
if (rt == null) throw new InvalidOperationException("Didn't converge!");

// 3) Saving result
_treeRates[i] = rt.Value;
}
}

private double EvaluatePrice(double rate, int num) {
var oldPrices = new double[num + 1];
var newPrices = new double[num];
for (var i = 0; i < num + 1; i++) oldPrices[i] = 1;

for (var n = num-1; n >= 0; n--) {
for (var k = 0; k <= n; k++) {
var rt = ((n == num - 1) ? rate : _treeRates[n]) * Math.Exp(-2 * _treeVols[n] * k);
newPrices[n - k] = 0.5*(oldPrices[n-k] + oldPrices[n-k+1])*Math.Exp(-rt);
}
if (n > 0) for (var k = 0; k <= n; k++) oldPrices[k] = newPrices[k];
}
return newPrices[0];
}
}