Skip to content

Instantly share code, notes, and snippets.

@oxbowlakes
Created March 13, 2012 12:52
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save oxbowlakes/2028575 to your computer and use it in GitHub Desktop.
Save oxbowlakes/2028575 to your computer and use it in GitHub Desktop.
FX Rate example
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