Advertisement
Guest User

Untitled

a guest
Oct 9th, 2020
131
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.55 KB | None | 0 0
  1. open System
  2. open System.Collections.Generic
  3.  
  4. module PriceMovingAverage =
  5.  
  6. type PriceRecord =
  7. {
  8. Timestamp : DateTime
  9. Price: float
  10. }
  11.  
  12. // queue duration
  13. let queueDuration = TimeSpan.FromHours(1.)
  14.  
  15. // moving average queue
  16. let private priceQueue = Queue<PriceRecord>()
  17.  
  18. // update moving average
  19. let updateMovingAverage timestamp price =
  20.  
  21. // add the new price
  22. priceQueue.Enqueue({ Timestamp = timestamp; Price = price})
  23.  
  24. // remove the items older than the price base period
  25. let rec dequeueLoop () =
  26. let p = priceQueue.Peek()
  27. if p.Timestamp + queueDuration < timestamp then
  28. priceQueue.Dequeue() |> ignore
  29. dequeueLoop()
  30.  
  31. dequeueLoop()
  32.  
  33.  
  34. // get the moving average
  35. let getPrice fromTimestamp =
  36. try
  37. Some (
  38. priceQueue
  39. |> Seq.toList
  40. |> List.skipWhile (fun t -> t.Timestamp < fromTimestamp)
  41. |> List.averageBy (fun t -> t.Price)
  42. |> decimal
  43. )
  44. with _ ->
  45. None
  46.  
  47.  
  48. // add some data
  49. let mutable price = 100.
  50. let mutable date = DateTime(2020, 10, 1)
  51. let r = Random()
  52.  
  53. for i in 0..20000 do
  54. PriceMovingAverage.updateMovingAverage date price
  55.  
  56. price <- price + 0.5 - r.NextDouble()
  57. date <- date.AddSeconds(10. * r.NextDouble())
  58.  
  59. // retrieve the data
  60. let dateFrom = DateTime(2020, 10, 1, 1, 0, 0)
  61. PriceMovingAverage.getPrice dateFrom
  62.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement