Created
March 13, 2012 12:52
-
-
Save oxbowlakes/2028575 to your computer and use it in GitHub Desktop.
FX Rate example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Currency | |
object Fx { | |
type CcyPair = (Currency, Currency) | |
case class FxRate(from: Currency, to: Currency, rate: BigDecimal) { | |
def pair: CcyPair = from → to | |
def unary_~ = FxRate(to, from, 1 / rate) | |
def *(that: FxRate): FxRate = { | |
require(this.to == that.from) | |
FxRate(this.from, that.to, this.rate * that.rate) | |
} | |
} | |
trait MarketEnv { | |
def rate: Currency ⇒ Currency ⇒ Option[FxRate] | |
} | |
case class SimpleEnv(rates: Map[CcyPair, FxRate]) extends MarketEnv { | |
def rate = from => to => { | |
def attemptDirectly(c1: Currency, c2: Currency) = { | |
rates get (c1 → c2) orElse (rates get (c2 → c1) map (~_)) | |
} | |
def viaUsd = { | |
val Usd = Currency.getInstance("USD") | |
for { | |
f2u <- attemptDirectly(from, Usd) | |
u2t <- attemptDirectly(Usd, to) | |
} yield f2u * u2t | |
} | |
attemptDirectly(from, to) orElse viaUsd | |
} | |
} | |
def main(args: Array[String]) { | |
val Gbp = Currency.getInstance("GBP") | |
val Usd = Currency.getInstance("USD") | |
val Eur = Currency.getInstance("EUR") | |
val Jpy = Currency.getInstance("JPY") | |
val rates = FxRate(Gbp, Usd, 1.57) :: FxRate(Eur, Usd, 1.31) :: Nil | |
val env = SimpleEnv((rates map (r => r.pair → r)).toMap) | |
println( env.rate(Eur)(Gbp) ) | |
val vGbp = env.rate(Gbp) | |
println(vGbp(Eur)) | |
println(vGbp(Usd)) | |
println(vGbp(Jpy)) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment