In Scala how to compare current values with previous values while processing a stream? -
i new scala not sure how approach problem ? trying find moving average crossovers stream of quotes. not sure how previous values compare them current values ?
if ( fastmovingaverage(n-1) > slowmovingaverage(n-1) && fastmovingaverage(n) < slowmovingaverage(n) ) action package com.example.csv import scala.io.source object fileparser { val timestamp_location = 3 val bid_location = 4 val offer_location = 5 val fast_window_size = 5 val slow_window_size = 10 def main(args: array[string]) = { val records = source.fromfile("sample.csv") .getlines() .drop(1) .map(_.split(",")) .takewhile( _ != null) .sliding(slow_window_size , 1) .foreach(x => movingaverage(x)) } def movingaverage(numbers: seq[array[string]]) = { val listofbids = numbers.map(x => x(bid_location).todouble) val slowaverage = listofbids.reduceleft(_ + _)/numbers.length val fastlistofbids = listofbids.takeright(fast_window_size) val fastaverage = fastlistofbids.reduceleft(_ + _)/fastlistofbids.length println("slow average " + slowaverage + " fast average " + fastaverage) } }
the short answer use zip
operation on slowaverage
, fastaverage
combine lists , find difference of zipped elements. when difference changes negative value positive value indicates fast average has crossed above(greater) slow average.
here's data used , longer example:
price fast average(2) slow average(4) diff 9 8 8.5 7 7.5 6 6.5 7.5 -1 5 5.5 6.5 -1 5 5 5.75 -0.75 6 5.5 5.5 0 7 6.5 5.75 0.75 8 7.5 6.5 1 9 8.5 7.5 1
google docs link: https://docs.google.com/spreadsheet/ccc?key=0alfb-wgy-ztddhdwu2sts0u5zuxtn2cwdwfoewnpzfe&usp=sharing
most recent price last.
let's see in scala:
scala> val prices = list(9,8,7,6,5,5,6,7,8,9) prices: list[int] = list(9, 8, 7, 6, 5, 5, 6, 7, 8, 9) scala> val fastaverage = prices.sliding(2).tolist.map(xs => xs.sum / 2.0) fastaverage: list[double] = list(8.5, 7.5, 6.5, 5.5, 5.0, 5.5, 6.5, 7.5, 8.5) scala> val slowaverage = prices.sliding(4).tolist.map(xs => xs.sum / 4.0) slowaverage: list[double] = list(7.5, 6.5, 5.75, 5.5, 5.75, 6.5, 7.5)
zip fastaverage
, slowaverage
since different sizes take last 7 of fastaverage
takeright
.
scala> val zipped = fastaverage.takeright(7) zip slowaverage zipped: list[(double, double)] = list((6.5,7.5), (5.5,6.5), (5.0,5.75), (5.5,5.5), (6.5,5.75), (7.5,6.5), (8.5,7.5))
take difference of zipped averages. change negative positive(>=0) indicates fast average greater slow average aka bullish moving average crossover.
scala> zipped.map(x => x._1 - x._2) res44: list[double] = list(-1.0, -1.0, -0.75, 0.0, 0.75, 1.0, 1.0)
Comments
Post a Comment