3. Higher order functions in automating buy or sell orders
In the financial markets, AI is widely used in automating trading decisions. Intelligent algorithms monitor the levels of price and risk, automatically placing buy and sell orders when certain conditions come together. Different strategies dictate how this is done. In the case of momentum based strategies, investors have an expectation that prices may rally in response to certain types of macroeconomic announcements e.g. a cut in interest rates. Investors who follow mean reversion strategies believe that assets move with a drift and volatility. When the net movement strays too far from an expectation, there may be an increased chance of reverting back to mean.
As different strategies may be effective in different situations, having the ability to easily switch between strategies is desirable. One of the principal attributes of functional programming is that functions are "first class citizens". This means that functions can be passed in the same way as parameters. The following example shows how different types of trading strategies ("mean_reversion" and "momentum") may be encoded as functions and plugged and played in the decision making processes.
def mean(list: List[Double]): Double = {
list.isEmpty match {
case true => 0
case false => list.sum / list.size
}
}
def ascending[A](list: List[A])(implicit ord: Ordering[A]): Boolean = {
(list.size < 2) match {
case true => true
case false => list.sliding(2).forall { case List(a, b) => ord.lteq(a, b) }
}
}
val mean_reversion = (prices: List[Double], threshold:Double) => {
(prices.last - mean(prices)) > threshold
}
val momentum = (prices: List[Double], threshold: Double) => {
ascending(prices) && ((prices.last - prices.head) > threshold)
}
def runStrategy(strategy: (List[Double], Double) => Boolean,
prices:List[Double], threshold:Double) : Boolean = {
strategy(prices, threshold)
}
def main(args: Array[String]) : Unit = {
val prices = List(..)
val threshold = ...
Boolean isTradingOpportunity = runStrategy(mean_reversion, prices, threshold)
// we can plug and play a different strateegy as below
// Boolean isTradingOpportunity = runStrategy(momentum, prices, threshold)
}
Last updated