summaryrefslogtreecommitdiff
path: root/src/FundLab.Api/MarketData.fs
blob: 87ef145b45b5a6977472a1008e3280366a7cd3a7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
namespace FundLab.Api

open System
open System.Globalization
open System.Text.Json

type MarketDataInstrument =
    {
        Code: string
        Name: string
        FundType: string option
    }

type MarketDataObservation =
    {
        NavDate: DateOnly
        PublishedAt: DateTimeOffset option
        Nav: decimal
        AccumulatedNav: decimal option
        DailyReturn: decimal option
    }

type MarketDataSearchPayload =
    {
        Source: string
        SourceRevision: string
        CollectedAt: DateTimeOffset
        Instruments: MarketDataInstrument list
    }

type MarketDataNavPayload =
    {
        Source: string
        SourceRevision: string
        CollectedAt: DateTimeOffset
        Code: string
        Observations: MarketDataObservation list
    }

type MarketDataBondQuotePayload =
    {
        Source: string
        SourceRevision: string
        CollectedAt: DateTimeOffset
        Code: string
        Name: string option
        Price: decimal option
        MaturityDate: DateOnly option
    }

type MarketDataStockQuotePayload =
    {
        Source: string
        SourceRevision: string
        CollectedAt: DateTimeOffset
        Code: string
        Name: string option
        Price: decimal option
        Currency: string
    }

type MarketDataInstrumentRecord =
    {
        Code: string
        Name: string
        FundType: string option
        Source: string
        SourceRevision: string
        SourceCollectedAt: DateTimeOffset
        SourcePayloadHash: string
        FirstSeenAt: DateTimeOffset
        LastSeenAt: DateTimeOffset
    }

type MarketDataNavRecord =
    {
        Code: string
        NavDate: DateOnly
        PublishedAt: DateTimeOffset option
        Nav: decimal
        AccumulatedNav: decimal option
        DailyReturn: decimal option
        Source: string
        SourceRevision: string
        SourceCollectedAt: DateTimeOffset
        SourcePayloadHash: string
        FirstSeenAt: DateTimeOffset
        LastSeenAt: DateTimeOffset
    }

module MarketData =
    type private ResultBuilder() =
        member _.Bind(value, binder) = Result.bind binder value
        member _.Return(value) = Ok value
        member _.ReturnFrom(value) = value
        member _.Zero() : Result<unit, string> = Ok ()
        member _.Combine(first: Result<unit, string>, second: unit -> Result<'a, string>) =
            match first with
            | Ok () -> second ()
            | Error message -> Error message
        member _.Delay(generator: unit -> Result<'a, string>) = generator
        member _.Run(generator: unit -> Result<'a, string>) = generator ()

    let private result = ResultBuilder()
    let private invariant = CultureInfo.InvariantCulture

    let private requiredProperty (root: JsonElement) (name: string) =
        let mutable property = Unchecked.defaultof<JsonElement>

        if root.ValueKind <> JsonValueKind.Object then
            Error "payload root must be a JSON object"
        elif root.TryGetProperty(name, &property) then
            Ok property
        else
            Error(sprintf "payload property '%s' is required" name)

    let private requiredString (root: JsonElement) name =
        requiredProperty root name
        |> Result.bind (fun property ->
            if property.ValueKind = JsonValueKind.String then
                let value = property.GetString()

                if String.IsNullOrWhiteSpace value then
                    Error(sprintf "payload property '%s' must not be empty" name)
                else
                    Ok value
            else
                Error(sprintf "payload property '%s' must be a string" name))

    let private optionalString (root: JsonElement) name =
        requiredProperty root name
        |> Result.bind (fun property ->
            if property.ValueKind = JsonValueKind.Null then
                Ok None
            elif property.ValueKind = JsonValueKind.String then
                let value = property.GetString()

                if String.IsNullOrWhiteSpace value then
                    Ok None
                else
                    Ok(Some value)
            else
                Error(sprintf "payload property '%s' must be null or a string" name))

    let private validateEnvelope root operation =
        result {
            let! schemaVersion = requiredString root "schema_version"
            let! actualOperation = requiredString root "operation"
            let! source = requiredString root "source"
            let! sourceRevision = requiredString root "source_revision"
            let! collectedAtText = requiredString root "collected_at"

            if schemaVersion <> "fund-lab.akshare.v1" then
                return! Error(sprintf "unsupported schema_version '%s'" schemaVersion)

            if actualOperation <> operation then
                return! Error(sprintf "payload operation must be '%s'" operation)

            match DateTimeOffset.TryParse(collectedAtText, invariant, DateTimeStyles.RoundtripKind) with
            | true, collectedAt ->
                return source, sourceRevision, collectedAt
            | false, _ ->
                return! Error "collected_at must be an ISO-8601 timestamp"
        }

    let private isFundCode (value: string) =
        value.Length = 6 && value |> Seq.forall Char.IsDigit

    let private parseFundCode root =
        requiredString root "code"
        |> Result.bind (fun code ->
            if isFundCode code then
                Ok code
            else
                Error "fund code must contain exactly six digits")

    let private parseDate text =
        let mutable date = DateOnly.MinValue

        if DateOnly.TryParseExact(text, "yyyy-MM-dd", invariant, DateTimeStyles.None, &date) then
            Ok date
        else
            Error "nav_date must be an ISO date"

    let private parseDecimal label (property: JsonElement) =
        if property.ValueKind <> JsonValueKind.String then
            Error(sprintf "%s must be a decimal string" label)
        else
            let text = property.GetString()

            if not (String.IsNullOrWhiteSpace text) then
                match Decimal.TryParse(text, NumberStyles.AllowLeadingSign ||| NumberStyles.AllowDecimalPoint, invariant) with
                | true, value -> Ok value
                | false, _ -> Error(sprintf "%s must be a decimal string" label)
            else
                Error(sprintf "%s must be a decimal string" label)

    let private optionalDecimal label (property: JsonElement) =
        if property.ValueKind = JsonValueKind.Null then
            Ok None
        else
            parseDecimal label property |> Result.map Some

    let private optionalPublishedAt (property: JsonElement) =
        if property.ValueKind = JsonValueKind.Null then
            Ok None
        elif property.ValueKind <> JsonValueKind.String then
            Error "published_at must be null or an ISO-8601 timestamp"
        else
            let text = property.GetString()

            if String.IsNullOrWhiteSpace text then
                Error "published_at must be null or an ISO-8601 timestamp"
            else
                match DateTimeOffset.TryParse(text, invariant, DateTimeStyles.RoundtripKind) with
                | true, value -> Ok(Some value)
                | false, _ -> Error "published_at must be null or an ISO-8601 timestamp"

    let private parseArray parser (property: JsonElement) =
        if property.ValueKind <> JsonValueKind.Array then
            Error "payload collection must be a JSON array"
        else
            property.EnumerateArray()
            |> Seq.fold
                (fun state item ->
                    match state, parser item with
                    | Ok values, Ok value -> Ok(value :: values)
                    | Error message, _ -> Error message
                    | _, Error message -> Error message)
                (Ok [])
            |> Result.map List.rev

    let private parseSearchInstrument root =
        result {
            let! code = parseFundCode root
            let! name = requiredString root "name"
            let! fundType = optionalString root "fund_type"

            return
                {
                    Code = code
                    Name = name
                    FundType = fundType
                }
        }

    let private parseObservation root =
        result {
            let! navDateText = requiredString root "nav_date"
            let! navDate = parseDate navDateText
            let! publishedAtProperty = requiredProperty root "published_at"
            let! publishedAt = optionalPublishedAt publishedAtProperty
            let! navProperty = requiredProperty root "nav"
            let! nav = parseDecimal "nav" navProperty
            let! accumulatedNavProperty = requiredProperty root "accumulated_nav"
            let! accumulatedNav = optionalDecimal "accumulated_nav" accumulatedNavProperty
            let! dailyReturnProperty = requiredProperty root "daily_return"
            let! dailyReturn = optionalDecimal "daily_return" dailyReturnProperty

            return
                {
                    NavDate = navDate
                    PublishedAt = publishedAt
                    Nav = nav
                    AccumulatedNav = accumulatedNav
                    DailyReturn = dailyReturn
                }
        }

    let parseSearchPayload (json: string) : Result<MarketDataSearchPayload, string> =
        try
            use document = JsonDocument.Parse(json)
            let root = document.RootElement

            result {
                let! source, sourceRevision, collectedAt = validateEnvelope root "search"
                let! instrumentsProperty = requiredProperty root "instruments"
                let! instruments = parseArray parseSearchInstrument instrumentsProperty

                return
                    {
                        Source = source
                        SourceRevision = sourceRevision
                        CollectedAt = collectedAt
                        Instruments = instruments
                    }
            }
        with
        | :? JsonException -> Error "payload must be valid JSON"

    let parseNavPayload (json: string) : Result<MarketDataNavPayload, string> =
        try
            use document = JsonDocument.Parse(json)
            let root = document.RootElement

            result {
                let! source, sourceRevision, collectedAt = validateEnvelope root "nav"
                let! instrumentProperty = requiredProperty root "instrument"
                let! code = parseFundCode instrumentProperty
                let! observationsProperty = requiredProperty root "observations"
                let! observations = parseArray parseObservation observationsProperty

                if List.isEmpty observations then
                    return! Error "observations must not be empty"

                return
                    {
                        Source = source
                        SourceRevision = sourceRevision
                        CollectedAt = collectedAt
                        Code = code
                        Observations = observations
                    }
            }
        with
        | :? JsonException -> Error "payload must be valid JSON"

    let parseBondQuotePayload (json: string) : Result<MarketDataBondQuotePayload, string> =
        let optionalIsoDate label (property: JsonElement) =
            if property.ValueKind = JsonValueKind.Null then
                Ok None
            elif property.ValueKind <> JsonValueKind.String then
                Error(sprintf "%s must be null or an ISO date" label)
            else
                let text = property.GetString()
                let mutable date = DateOnly.MinValue

                if
                    not (String.IsNullOrWhiteSpace text)
                    && DateOnly.TryParseExact(text, "yyyy-MM-dd", invariant, DateTimeStyles.None, &date)
                then
                    Ok(Some date)
                else
                    Error(sprintf "%s must be null or an ISO date" label)

        try
            use document = JsonDocument.Parse(json)
            let root = document.RootElement

            result {
                let! source, sourceRevision, collectedAt = validateEnvelope root "bond-quote"
                let! instrumentProperty = requiredProperty root "instrument"
                let! codeProperty = requiredString instrumentProperty "code"

                if not (isFundCode codeProperty) then
                    return! Error "bond code must contain exactly six digits"

                let! quoteProperty = requiredProperty root "quote"
                let! name = optionalString quoteProperty "name"
                let! priceProperty = requiredProperty quoteProperty "price"
                let! price = optionalDecimal "price" priceProperty
                let! maturityProperty = requiredProperty quoteProperty "maturity_date"
                let! maturityDate = optionalIsoDate "maturity_date" maturityProperty

                return
                    {
                        Source = source
                        SourceRevision = sourceRevision
                        CollectedAt = collectedAt
                        Code = codeProperty
                        Name = name
                        Price = price
                        MaturityDate = maturityDate
                    }
            }
        with
        | :? JsonException -> Error "payload must be valid JSON"

    let parseStockQuotePayload (json: string) : Result<MarketDataStockQuotePayload, string> =
        try
            use document = JsonDocument.Parse(json)
            let root = document.RootElement

            result {
                let! source, sourceRevision, collectedAt = validateEnvelope root "stock-quote"
                let! instrumentProperty = requiredProperty root "instrument"
                let! codeProperty = requiredString instrumentProperty "code"

                if not (isFundCode codeProperty) then
                    return! Error "stock code must contain exactly six digits"

                let! quoteProperty = requiredProperty root "quote"
                let! name = optionalString quoteProperty "name"
                let! priceProperty = requiredProperty quoteProperty "price"
                let! price = optionalDecimal "price" priceProperty
                let! currency = requiredString quoteProperty "currency"

                return
                    {
                        Source = source
                        SourceRevision = sourceRevision
                        CollectedAt = collectedAt
                        Code = codeProperty
                        Name = name
                        Price = price
                        Currency = currency
                    }
            }
        with
        | :? JsonException -> Error "payload must be valid JSON"