Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- open System
- open System.Collections.Generic
- module PriceMovingAverage =
- type PriceRecord =
- {
- Timestamp : DateTime
- Price: float
- }
- // queue duration
- let queueDuration = TimeSpan.FromHours(1.)
- // moving average queue
- let private priceQueue = Queue<PriceRecord>()
- // update moving average
- let updateMovingAverage timestamp price =
- // add the new price
- priceQueue.Enqueue({ Timestamp = timestamp; Price = price})
- // remove the items older than the price base period
- let rec dequeueLoop () =
- let p = priceQueue.Peek()
- if p.Timestamp + queueDuration < timestamp then
- priceQueue.Dequeue() |> ignore
- dequeueLoop()
- dequeueLoop()
- // get the moving average
- let getPrice fromTimestamp =
- try
- Some (
- priceQueue
- |> Seq.toList
- |> List.skipWhile (fun t -> t.Timestamp < fromTimestamp)
- |> List.averageBy (fun t -> t.Price)
- |> decimal
- )
- with _ ->
- None
- // add some data
- let mutable price = 100.
- let mutable date = DateTime(2020, 10, 1)
- let r = Random()
- for i in 0..20000 do
- PriceMovingAverage.updateMovingAverage date price
- price <- price + 0.5 - r.NextDouble()
- date <- date.AddSeconds(10. * r.NextDouble())
- // retrieve the data
- let dateFrom = DateTime(2020, 10, 1, 1, 0, 0)
- PriceMovingAverage.getPrice dateFrom
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement