Skip to content

Instantly share code, notes, and snippets.

@bronumski
Created May 20, 2020 04:37
Show Gist options
  • Save bronumski/13a44aded25c8dee779ff3196f93884c to your computer and use it in GitHub Desktop.
Save bronumski/13a44aded25c8dee779ff3196f93884c to your computer and use it in GitHub Desktop.
Technical test to get the aggregated stock results for a given symbol, originally done in C# but I tried it out in F#
#r @"./packages/fsharp-data/netstandard2.0/Fsharp.Data.dll"
#r @"./packages/newtonsoft.json/netstandard2.0/Newtonsoft.Json.dll"
open System
open FSharp.Data
open Newtonsoft.Json.Linq
let timeSeriesUrl = "https://www.alphavantage.co/query?function=TIME_SERIES_DAILY&symbol=%s&outputsize=full&apikey=A3U8E3F7N3A85K86"
type TimeSeries = FSharp.Data.JsonProvider<"""{
"2. high": "123.4567",
"3. low": "123.4567"
}""">
let renderStockUrl symbol =
sprintf (Printf.StringFormat<string->string>(timeSeriesUrl)) symbol
let queryApi url =
FSharp.Data.Http.RequestString url
let parseStockResponse response =
let json = JObject.Parse response
let timeSeries = json.Item "Time Series (Daily)"
timeSeries.Children()
|> Seq.cast<JToken>
|> Seq.map(fun token -> token.ToObject<JProperty>())
|> Seq.map(fun prop -> prop, TimeSeries.Parse(prop.Value.ToString()))
|> Seq.map(fun (prop, entry) -> DateTime.Parse prop.Name, entry.``2High``, entry.``3Low``)
let aggregateStockTimeSeries timeSeries =
timeSeries
|> Seq.groupBy(fun (date : DateTime, _, _) -> (date.Year, date.Month))
|> Seq.map(fun ((year, month), values) ->
let date = DateTime(year, month, 1)
let minLow = values |> Seq.map(fun (_, _, low) -> low) |> Seq.maxBy(fun low -> low)
let maxHigh = values |> Seq.map(fun (_, high, _) -> high) |> Seq.maxBy(fun high -> high)
date, minLow, maxHigh)
let renderAggrigatedStockResultsFor symbol =
renderStockUrl symbol
|> queryApi
|> parseStockResponse
|> aggregateStockTimeSeries
|> Seq.iter(fun (date, low, high) -> printf "%s %M %M\n" (date.ToString("yyyy-MM")) low high)
renderAggrigatedStockResultsFor "MSFT"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment