/
classConstructor.R
1708 lines (1393 loc) · 63.5 KB
/
classConstructor.R
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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#' @include common.R
#' @name classconstructor
#' @title dsws
#'
#' @description An R5/RC object for accessing the LSEG Datastream
#' DSWS service.
#'
#' @details Creates an R5/RC4 object for accessing the LSEG
#' Datastream DSWS service
#'
#'
#' @field tokenList fieldDescription
#' @field tokenSource fieldDescription
#' @field serverURL fieldDescription
#' @field username fieldDescription
#' @field password fieldDescription
#' @field initialised fieldDescription
#' @field errorlist fieldDescription
#' @field requestList fieldDescription
#' @field jsonResponseSaveFile fieldDescription
#' @field jsonResponseLoadFile fieldDescription
#' @field dataResponse fieldDescription
#' @field symbolList fieldDescription
#' @field myValues fieldDescription
#' @field myTypes fieldDescription
#' @field logging fieldDescription
#' @field numDatatype fieldDescription
#' @field numInstrument fieldDescription
#' @field numRequests fieldDescription
#' @field numChunks fieldDescription
#' @field chunkLimit fieldDescription
#' @field requestStringLimit fieldDescription
#' @field logFileFolder fieldDescription
#'
#' @examples
#' \dontrun{
#'
#'
#' mydsws <- dsws$new()
#' # Snapshot requests
#'
#'
#' myData <- mydsws$snapshotRequest(instrument = c("ABF","RIO","WPP"),
#' datatype = "P",
#' requestDate = "0D")
#'
#' myData <- mydsws$snapshotRequest(instrument = c("ABF","RIO","WPP"),
#' expression = "PCH#(XXXX,3M)",
#' requestDate = "0D")
#' myData <- mydsws$listRequest(instrument = "LFTSE100", datatype = "P", requestDate = "0D")
#'
#' mydsws$snapshotRequest(instrument = c("SWCNB10","UKEUSCCIR"),
#' datatype = c("MNEM","UPDATE"),
#' requestDate = "0D")
#' mydsws$snapshotRequest(instrument = c("VOD", "HSBA"),
#' datatype="QTEALL",
#' requestDate = Sys.Date())
#' mydsws$snapshotRequest(instrument = "STATS",
#' datatype = "DS.USERSTATS",
#' requestDate = Sys.Date())
#'
#'
#' # Timeseries requests
#'
#'
#' xtsData <- mydsws$timeSeriesRequest(instrument = "MKS",
#' datatype = "MV",
#' startDate = "-30D",
#' endDate = "-0D",
#' frequency = "D")
#'
#' xtsData <- mydsws$timeSeriesListRequest(instrument = "LFTSE100",
#' datatype = "MV",
#' startDate = "-30D",
#' endDate = "-0D",
#' frequency = "D")
#'}
#' @import methods
#' @export dsws
#'
dsws <- setRefClass(Class = "dsws",
fields = list(tokenList = "ANY",
tokenSource = "ANY",
serverURL = "character",
username = "character",
password = "character",
initialised = "logical",
errorlist = "ANY",
requestList = "ANY",
jsonResponseSaveFile = "ANY",
jsonResponseLoadFile = "ANY",
dataResponse = "ANY",
symbolList = "ANY",
myValues = "ANY",
myTypes = "ANY",
logging = "numeric",
numDatatype = "numeric",
numInstrument = "numeric",
numRequests = "numeric",
numChunks = "numeric",
chunkLimit = "numeric",
requestStringLimit = "integer",
logFileFolder = "character"))
#-----Accessors----------------------------------------------------------------
dsws$accessors(c("tokenList",
"tokenSource",
"serverURL",
"username",
"password",
"logging",
"errorlist",
"requestList",
"dataResponse",
"symbolList"))
#------Initialisation-----------------------------------------------------------------------
dsws$methods(initialize = function(dsws.serverURL = "",
getTokenFunction = NULL,
token = NULL,
username = "",
password = "",
connect = TRUE) {
"
initialises the class.
Unless noConnect is TRUE also connects to the
Datastream dsws server.
Authentication can be set in three ways:
1) If getTokenFunction is not null then that function is called. It is expected to
return a list with items 'TokenValue' and 'TokenExpiry'.
2) An access token can also be passed into the class on initialisation, so that it can be shared between sessions.
'token' is expected to be a list with items 'TokenValue' and 'TokenExpiry'.
3) A username and password that are used to fetch a token from the DSWS server. If the username and password are not
provided, then they are sourced from system enviroment variables (ie Sys.getenv)
'DatastreamUsername' and 'DatastreamPassword'
or alternatively (not preferred) then from
\\code{options()$Datastream.Username} and
\\code{options()$Datastream.Password}
This allows the password to be stored in .Renviron or .RProfile rather
than in the source code.
There different accounts have different limits according to their licence. Most users are limited to 50 items while
enterprise users have a limit of 2000L. The chunk limit
can be controlled by setting the chunkLimit parameter of the dsws object. If \\code{options()$Datastream.ChunkLimit} is
set then the value is taken from there.
"
.self$initialised <- FALSE
.self$errorlist <- NULL
if (is.null(options()$Datastream.ChunkLimit)) {
.self$chunkLimit <- 2000L # Max number of items that can be in a single request. Set by Datastream
} else {
.self$chunkLimit <- as.integer(options()$Datastream.ChunkLimit)
}
.self$numChunks <- 0L
.self$numRequests <- 0L
.self$requestStringLimit <- 2000L # Max character length of an http request.
.self$logging <- 0L
.self$logFileFolder <- Sys.getenv("R_USER")
.self$jsonResponseLoadFile <- NULL # By default is to hit the server
.self$jsonResponseSaveFile <- NULL # Default is not to save JSON response
if (dsws.serverURL == "") {
# 07/4/2016 - due to issue with Datastream's load balancers, using a different URL. This will
# be changed back when the issue is resolved.
.self$serverURL <- "https://product.datastream.com/DSWSClient/V1/DSService.svc/rest/"
} else {
.self$serverURL <- dsws.serverURL
}
# Authenticate and get token
# Set default value of Null for tokenList
.self$tokenList <- list(TokenValue = NULL,
TokenExpiry = NULL)
# Use the token function if provided
if (!is.null(getTokenFunction) && is.function(getTokenFunction)) {
.self$initialised <- TRUE
.self$tokenSource <- getTokenFunction
.self$tokenList <- .self$tokenSource()
return(invisible(.self))
}
# Next option use the token that has been passed
if (!is.null(token) && is.list(token)) {
if (FALSE %in% (c("TokenValue", "TokenExpiry") %in% names(token)))
stop("Token must contain items TokenValue and TokenExpiry")
if (!xts::is.timeBased(token$TokenExpiry))
stop("Token$TokenExpiry must be a time based object")
.self$tokenList <- list(TokenValue = token$TokenValue,
TokenExpiry = token$TokenExpiry)
.self$initialised <- TRUE
.self$tokenSource <- "Provided"
return(invisible(.self))
}
# If we are passed the username and password then use them, otherwise the system environment
# defaults before getting the token from the DSWS server
if (username != "") {
.self$username <- username
} else if (Sys.getenv("DatastreamUsername") != "") {
.self$username <- Sys.getenv("DatastreamUsername")
} else if (!is.null(options()$Datastream.Username)) {
.self$username <- options()$Datastream.Username
} else {
stop("Either username must be specified or it must be set via options(\"Datastream.Username\", \"Myusername\"")
}
if (password != "") {
.self$password <- password
} else if (Sys.getenv("DatastreamPassword") != "") {
.self$password <- Sys.getenv("DatastreamPassword")
} else if (!is.null(options()$Datastream.Password)) {
.self$password <- options()$Datastream.Password
} else {
stop("Either username must be specified or it must be set via options(\"Datastream.Password\", \"Mypassword\"")
}
.self$tokenList <- list(TokenValue = NULL,
TokenExpiry = NULL)
.self$tokenSource <- "DSWS"
.self$initialised <- TRUE
if (connect) {
.self$.loadToken()
}
return(invisible(.self))
})
#-----getToken---------------------------
dsws$methods(.loadToken = function() {
"Internal function:
Choses whether to get token from internal function or from DSWS"
if (.self$.tokenExpired()) {
if (is.function(.self$tokenSource)) {
.self$tokenList <- .self$tokenSource()
} else if (.self$tokenSource == "DSWS") {
.self$tokenList <- .self$.requestToken()
} else {
stop("No token reloading method is available.")
}
}
tv <- .self$tokenList$TokenValue
return(tv)
})
#------.requestToken-----------------------------------------------------------------------
#' @importFrom httr GET status_code http_error http_status parsed_content timeout
#'
dsws$methods(.requestToken = function() {
"Internal function:
Returns a Token from the the dsws server that
gives permission to access data."
if (!.self$initialised) {
message("dsws has not been properly initialised. Check serverURL, username and password")
return(NULL)
}
ts <- .self$tokenList
if (is.null(ts$TokenValue) || is.null(ts$TokenExpiry) || Sys.time() > ts$TokenExpiry ) {
# Either we do not already have a token, or it has expired, so we need to request one
myTokenURL <- paste0(.self$serverURL, "Token",
"?username=", .self$username ,
"&password=", .self$password )
# We are going to handle timeouts by
# waiting incrementally up to 16 sec and repeating the request
maxLoop <- 4L
waitTimeBase <- 2
nLoop <- 0
.self$errorlist <- NULL
myTokenResponse <- httr::RETRY(
"GET",
url = myTokenURL,
encode = "json",
config = httr::timeout(60)
)
if (is.null(myTokenResponse)) {
.self$tokenList <- list(TokenValue = NULL,
TokenExpiry = NULL)
stop("Could not request access Token - response from server was NULL")
}
if (inherits(myTokenResponse, "error")) {
.self$tokenList <- list(TokenValue = NULL,
TokenExpiry = NULL)
stop(paste0("Error requesting access Token. Error message was:\n",
myTokenResponse$message))
}
if (httr::http_error(myTokenResponse)) {
.self$tokenList <- list(TokenValue = NULL,
TokenExpiry = NULL)
stop(paste0("Error requesting access Token. HTTP message was: ",
paste0(httr::http_status(myTokenResponse), collapse = " : ")))
}
myTokenList <- httr::content(myTokenResponse, as = "parsed")
#Error check response
if (is.null(myTokenList$TokenValue) || is.null(myTokenList$TokenExpiry)) {
.self$tokenList <- list(TokenValue = NULL,
TokenExpiry = NULL)
stop(paste0("Error requesting access Token. Valid fields were not returned: ",
paste0(myTokenList, collapse = " : ")))
} else {
.self$tokenList <- list(TokenValue = myTokenList$TokenValue,
TokenExpiry = .convert_JSON_Datetime(myTokenList$TokenExpiry))
}
}
return(invisible(.self$tokenList))
})
#-------validToken----------------------------------------------------------------------
dsws$methods(.tokenExpired = function(thisToken = NULL, myTime = Sys.time()) {
"Checks whether the given or saved token has not expired.
Returns true if it has, false otherwise"
if (is.null(thisToken)) {
thisToken <- .self$tokenList
}
thisTokenExpiry <- thisToken$TokenExpiry
if (is.null(thisTokenExpiry)) return(TRUE)
# We want the token to have at least one minute before expiry
return( (thisTokenExpiry - myTime) < as.difftime(60, units = "secs") )
})
#-----------------------------------------------------------------------------
#' @importFrom jsonlite fromJSON toJSON
#' @importFrom httr POST status_code http_error http_type parsed_content timeout
dsws$methods(.makeRequest = function(bundle = FALSE) {
"Internal function: make a request from the DSWS server.
The request (in a R list form) is taken from .self$requestList,
parsed into JSON and sent to the DSWS server. The JSON response is
parsed and saved in .self$dataResponse"
# This option is for testing purposes. The response is loaded
# from a specified JSON file, rather than the DSWS server
if (!is.null(.self$jsonResponseLoadFile)) {
if (file.exists(.self$jsonResponseLoadFile)) {
.self$dataResponse <- rjson::fromJSON(file = .self$jsonResponseLoadFile)
return(TRUE)
} else {
stop("File specified by dsws$jsonResponseLoadFile does not exist")
}
}
if (bundle) {
myDataURL <- paste0(.self$serverURL , "GetDataBundle")
}else{
myDataURL <- paste0(.self$serverURL , "GetData")
}
if (.self$logging >= 5) {
message("JSON request to DSWS server is:\n")
message(jsonlite::toJSON(.self$requestList))
message("--------------------------------------------------")
}
maxLoop <- 4L
waitTimeBase <- 2
nLoop <- 0
.self$errorlist <- NULL
.self$numRequests <- .self$numRequests + 1
myDataResponse <- httr::RETRY(
"POST",
url = myDataURL,
body = .self$requestList,
encode = "json",
config = httr::timeout(60)
)
if (is.null(myDataResponse)) {
.self$dataResponse <- NULL
mm <- "Response is not able to be parsed: response from server was NULL"
.self$setErrorlist(c(.self$getErrorlist(),
list(message = mm)))
message(mm)
return(FALSE)
}
if (inherits(myDataResponse, "error")) {
.self$dataResponse <- NULL
mm <- paste0("Response is not able to be parsed: Error message was:\n",
myDataResponse$message)
.self$setErrorlist(c(.self$getErrorlist(),
list(message = mm)))
message(mm)
return(FALSE)
}
if (inherits(myDataResponse, "list")) {
.self$dataResponse <- NULL
mm <- "Response is not able to be parsed: response is a list"
.self$setErrorlist(c(.self$getErrorlist(),
list(message = mm)))
message(mm)
return(FALSE)
}
if (httr::http_error(myDataResponse)) {
.self$dataResponse <- NULL
mm <- paste0("Error requesting data. HTTP message was: ",
paste0(httr::http_status(myDataResponse), collapse = " : "))
.self$setErrorlist(c(.self$getErrorlist(),
list(message = mm)))
message(mm)
return(FALSE)
}
if (httr::http_type(myDataResponse) != "application/json") {
.self$dataResponse <- NULL
mm <- "Response is not able to be parsed: response is not json"
.self$setErrorlist(c(.self$getErrorlist(),
list(message = mm)))
message(mm)
return(FALSE)
}
if (!is.null(.self$jsonResponseSaveFile)) {
if (!is.null(myDataResponse)) {
writeChar(object = httr::content(myDataResponse, as = "text", encoding = "UTF-8"), con = .self$jsonResponseSaveFile)
}
}
.self$dataResponse <- tryCatch(httr::content(myDataResponse, as = "parsed"),
error = function(e) e)
if (inherits(.self$dataResponse, "error")) {
mm <- paste0("Error parsing response: ", .self$dataResponse$message)
.self$setErrorlist(c(.self$getErrorlist(),
list(message = mm)))
message(mm)
message("Class of response", class(myDataResponse))
message(paste0("JSON returned by DSWS server response is:\n", myDataResponse), "\n")
message("------------------")
.self$dataResponse <- NULL
return(FALSE)
}
if (.self$logging >= 4 ) {
message(paste0("JSON returned by DSWS server response is:\n", .self$dataResponse, "\n"))
}
return(TRUE)
})
#----------------------------------------------------------------------------
dsws$methods(listRequest = function(instrument,
datatype = "",
expression = "",
requestDate) {
"
Make a listRequest from Datastream DSWS.
This is the equivalent to
the Excel static request for a list.\n
Parameters are: \\describe{
\\item{instrument}{should contain a list mnemonic, such as 'LFTSE100'
Can be a user created list or index. The UCL can contain
expressions}
\\item{datatype}{array of datatypes eg NAME, MNEM, P, PE etc}
\\item{expression}{if datatype is null or '' then an expression
eg PCH#(XXXX,3M)}
\\item{requestDate}{either a Date or a string with a datastream
relative date eg '-3M'}
}
Returns a data.frame with the requested data.\n
Examples:\n
\\preformatted{
mydsws$listRequest(instrument = \"LFTSE100\",
datatype = c(\"NAME\",\"P\"), \nrequestDate = \"-0D\")
}
\\preformatted{
mydsws$listRequest(instrument = \"LFTSE100\",
expression = \"PCH#(XXXX,3M)\", requestDate = Sys.Date())
}
"
.self$numChunks <- 0
.self$numRequests <- 0
return(.self$.basicRequest(instrument = instrument,
datatype = datatype,
expression = expression,
isList = TRUE,
startDate = requestDate,
endDate = requestDate,
frequency = "D",
kind = 0,
format = "SnapshotList"))
})
#-----------------------------------------------------------------------------
dsws$methods(snapshotRequest = function(instrument,
datatype = "",
expression = "",
requestDate) {
"
Make a snapshotRequest from Datastream DSWS.
This is the equivalent
to the Excel static request for an array of instruments.\n
Parameters are: \\describe{
\\item{instrument}{should one or more instruments eg \"MKS\" or
c(\"MKS\",\"@AAPL\"). The array can contain
Economics codes and Expressions. }
\\item{datatype}{array of datatypes eg NAME, MNEM, P, PE etc}
\\item{expression}{if datatype is null or '' then an expression
eg PCH#(XXXX,3M)}
\\item{requestDate}{either a Date or a string with a datastream relative
date eg '-3M'}
}
Returns a data.frame with the requested data.\n
Examples:\n
\\preformatted{
mydsws$snapshotRequest(instrument = c(\"MKS\",\"@AAPL\"), \n
datatype = c(\"NAME\",\"P\"), requestDate = \"-0D\")
}
\\preformatted{
mydsws$snapshotRequest(instrument = c(\"MKS\",\"@AAPL\"), \n
expression = \"PCH#(XXXX,3M)\", requestDate = \"-0D\")
}
"
.self$numChunks <- 0
.self$numRequests <- 0
return(.self$.basicRequest(instrument = instrument,
datatype = datatype,
expression = expression,
isList = FALSE,
startDate = requestDate,
endDate = requestDate,
frequency = "D",
kind = 0,
format = "Snapshot"))
})
#-----------------------------------------------------------------------------
dsws$methods(timeSeriesRequest = function(instrument,
datatype = "",
expression = "",
startDate,
endDate,
frequency = "D",
format = "ByInstrument") {
"
Return a timeSeriesRequest from Datastream dsws.
Should request either
a datatype or an expression
not both. If a datatype is provided then anythink in Expression
will be ignored
Make a timeSeriesRequest from Datastream DSWS. This is the equivalent
to the Excel timeseries request for an array of instruments.\n
Parameters are: \\describe{
\\item{instrument}{should one or more instruments eg \"MKS\" or
c(\"MKS\",\"@AAPL\"). The array can contain Economics codes and
Expressions. }
\\item{datatype}{array of datatypes eg P, PE etc}
\\item{expression}{if datatype is null or '' then an expression
eg PCH#(XXXX,3M)}
\\item{startDate}{either a Date or a string with a datastream relative
date eg '-3M'}
\\item{endDate}{either a Date or a string with a datastream relative
date eg '-0D'}
\\item{frequency}{one of the standard Datastream
frequencies - D, W, M, Q, or Y}
\\item{format}{can be either \"ByInstrument\" or \"ByDatatype\".}
}
Returns either a single xts or a list of xts a data.frame with
the requested data. If \"ByInstrument\" then
the data is returned as one or more (ie a list) wide xts with one
column per instrument. If \"ByDatatype\"
then the data is returned as one or more (ie a list) of wide xts with
one column per Datatype. This format
is more compatible with the quantmod package.
Examples:\n
\\preformatted{
mydsws$timeSeriesRequest(instrument = c(\"MKS\",\"@AAPL\"),\n
datatype = \"P\", startDate = \"-30D\",\n
endDate = \"-0D\", frequency = \"D\")
}
\\preformatted{
mydsws$timeSeriesRequest(instrument = c(\"MKS\"), \n
expression = \"PCH#(XXXX,3M)\", startDate = \"-30D\",\n
endDate = \"-0D\", frequency = \"D\")
}
\\preformatted{
mydsws$timeSeriesRequest(instrument = c(\"MKS\",\"@AAPL\"), \n
datatype = (\"P\",\"UP\"), startDate = \"-30D\",\n
endDate = \"-0D\", frequency = \"D\", format = \"ByDatatype\")
}
"
.self$numChunks <- 0
.self$numRequests <- 0
myData <- .self$.basicRequest(instrument = instrument,
datatype = datatype,
expression = expression,
isList = FALSE,
startDate = startDate,
endDate = endDate,
frequency = frequency,
kind = 1,
format = format)
return(myData)
})
#-----------------------------------------------------------------------------
dsws$methods(timeSeriesListRequest = function(instrument,
datatype = "",
expression = "",
startDate,
endDate,
frequency = "D",
format = "ByInstrument") {
"
Make a timeSeriesListRequest from Datastream DSWS.
This is the
equivalent to the Excel timeseries request for an array of instruments.
Should request either a datatype or an expression not both. If a
datatype is provided then anything in Expression will be ignored.\n
Parameters are: \\describe{
\\item{instrument}{should contain a list mnemonic, such as \"LFTSE100\"\n.
Can be a user created list or index. The UCL can contain expressions.}
\\item{datatype}{array of datatypes eg P, PE etc}
\\item{expression}{if datatype is null or '' then an expression \n
eg PCH#(XXXX,3M)}
\\item{startDate}{either a Date or a string with a datastream relative date\n
eg '-3M'}
\\item{endDate}{either a Date or a string with a datastream relative date \n
eg '-0D'}
\\item{frequency}{one of the standard Datastream frequencies - D, W, M, Q, or Y }
\\item{format}{can be either \"ByInstrument\" or \"ByDatatype\". }
}
Returns either a single xts or a list of xts a data.frame with
the requested data. If \"ByInstrument\" then the data is returned as
one or more (ie a list) wide xts with one column per instrument.
If \"ByDatatype\" then the data is returned as one or more (ie a list)
of wide xts with one column per Datatype. This format is more compatible
with the quantmod package.
Examples:\n
\\preformatted{
mydsws$timeSeriesListRequest(instrument = \"LFTSE100\",\n
datatype = \"P\", startDate = \"-30D\",\n
endDate = \"-0D\", frequency = \"D\")
}
\\preformatted{
mydsws$timeSeriesListRequest(instrument = \"LFTSE100\", \n
expression = \"PCH#(XXXX,3M)\", \n
startDate = \"-30D\",\n
endDate = \"-0D\", \n
frequency = \"D\")
}
\\preformatted{
mydsws$timeSeriesListRequest(instrument = \"LFTSE100\", \n
datatype = (\"P\",\"UP\"), startDate = \"-30D\",\n
endDate = \"-0D\", \n
frequency = \"D\", format = \"ByDatatype\")
}
"
# First return a list of mnemonics
.self$numChunks <- 0
.self$numRequests <- 0
.self$symbolList <- .self$.basicRequest(instrument = instrument,
datatype = "MNEM",
expression = "",
isList = TRUE,
startDate = "",
endDate = endDate,
frequency = frequency,
kind = 0,
format = "SnapshotList")
return(.self$.basicRequest(instrument = .self$symbolList[,1],
datatype = datatype,
expression = expression,
isList = FALSE,
startDate = startDate,
endDate = endDate,
frequency = frequency,
kind = 1,
format = format))
})
#-----------------------------------------------------------------------------
dsws$methods(.basicRequest = function(instrument,
datatype = "",
expression = "",
isList = FALSE,
startDate,
endDate,
frequency = "D",
kind = 0,
format = "ByInstrument") {
"
Internal method.
This is not intended to be called directly.
Return a request from Datastream dsws.
Should request either a datatype or an expression not both.
If a datatype is provided then anything
in Expression will be ignored.
Datatype can be a vector with length > 1, but expression should
only be of length 1.
This method will chunk the requests to dsws if necessary.
"
# expression has to be atomic and not an array
if (length(expression) > 1) expression <- expression[1]
.self$setErrorlist(list())
# We have to have at least one instrument
numCodes <- length(instrument)
numDatatypes <- length(datatype)
if (numCodes == 0) {
stop("instruments is empty and has length zero")
}
# Setting a limit on the number of datatypes means that we will always split instrument up into chunks
# simplifying the chunking and stitching process.
if (length(datatype) >= .self$chunkLimit) {
stop(paste0("The number of datatypes request must be less than the limit of ", .self$chunkLimit))
}
# names of can upset the format of the json request
names(instrument) <- NULL
names(datatype) <- NULL
names(expression) <- NULL
if (format == "Snapshot") {
# Set the holder for the results here
# Process the response into a dataframe, one row per instrument, with a column for each datatype
.self$myValues <- data.frame(matrix(NA, nrow = length(instrument), ncol = numDatatypes + 1))
} else if (format == "ByInstrument") {
xtsValues <- as.list(rep(NA, length.out = numDatatypes))
}
# Holder for the type (ie Date, string) for each of the datatypes
.self$myTypes <- rep(NA, length.out = numDatatypes)
doChunk <- FALSE
if (datatype[1] != "") {
# If we are not using a expression, we will just apply the rule that
# number of instruments * number of datatypes has to be less tha the chunk limit
doChunk <- (numCodes * numDatatypes >= .self$chunkLimit)
} else {
# There appears to be a maximum character limit for a request (or response)
# We will need to chunk the request if we are using an expression and when we expand the expression
# it is over this limit.
expandedInstrument <- paste0(.self$.expandExpression(instrument, expression), collapse = ",")
if ((nchar(expandedInstrument) >= .self$requestStringLimit) |
(numCodes * numDatatypes >= .self$chunkLimit)) {
doChunk <- TRUE
}
}
# if we are using expressions then length(datatype) will be 1L and so will not affect the test
if (!doChunk) {
# Chunking not required so just pass through the request
.self$numChunks <- 1
if (format == "Snapshot" | format == "SnapshotList") {
return(.self$.basicRequestSnapshotChunk(instrument = instrument,
datatype = datatype,
expression = expression,
isList = isList,
startDate = startDate,
endDate = endDate,
frequency = frequency,
kind = kind,
format = format,
chunkNumber = 1,
isChunked = FALSE))
} else {
return(.self$.basicRequestTSChunk(instrument = instrument,
datatype = datatype,
expression = expression,
isList = isList,
startDate = startDate,
endDate = endDate,
frequency = frequency,
kind = kind,
format = format,
chunkNumber = 1,
isChunked = FALSE))
}
}
# Chunking required which will to split instrument into chunks
# Work out the number of chunks and the size of each request
if (datatype[1] != "") {
numInstrChunk <- floor(.self$chunkLimit / numDatatypes)
nChunks <- ceiling(numCodes / numInstrChunk )
} else {
# If we are using expressions then we have to choose our number of chunks as the larger
# of the number defined by the limit on the number of instruments and the number
# defined by the limit of the request string length
numChunksInst <- ceiling(numCodes / .self$chunkLimit )
expandedInstrument <- paste0(.self$.expandExpression(instrument, expression), collapse = ",")
numChunksString <- ceiling(nchar(expandedInstrument) / .self$requestStringLimit)
numInstrChunk <- floor(numCodes / max(numChunksInst, numChunksString))
nChunks <- ceiling(numCodes / numInstrChunk )
}
for (i in 1:nChunks) {
# get the the list of instruments for each request
startIndex <- ((i - 1) * numInstrChunk) + 1
endIndex <- ifelse((i * numInstrChunk) < numCodes, (i * numInstrChunk), numCodes )
chunkInstrument <- instrument[startIndex:endIndex]
resRows <- seq(from = startIndex, to = endIndex)
.self$numChunks <- .self$numChunks + 1
# make a request for the chunk of instruments
if (format == "Snapshot" | format == "SnapshotList") {
ret <- .self$.basicRequestSnapshotChunk(instrument = chunkInstrument,
datatype = datatype,
expression = expression,
isList = isList,
startDate = startDate,
endDate = endDate,
frequency = frequency,
kind = kind,
format = format,
isChunked = TRUE,
chunkNumber = i,
chunkItems = resRows)
} else {
ret <- .self$.basicRequestTSChunk(instrument = chunkInstrument,
datatype = datatype,
expression = expression,
isList = isList,
startDate = startDate,
endDate = endDate,
frequency = frequency,
kind = kind,
format = format,
isChunked = TRUE,
chunkNumber = i,
chunkItems = resRows)
}
# How we join the results together depends of the nature of the format
if (format[1] == "ByInstrument") {
# If the format is by instrument then we have a wide xts, one for each datatype.
# each of these individual xts will need to be merged with the master
if (is.null(ret)) {
.self$setErrorlist(c(.self$getErrorlist(),
list(message = paste0("Chunk number ", i, " returned a null response"))))
next
}
if (length(datatype) == 1) {
# If we have only one datatype then merging is simple
if (i == 1 || is.null(xtsValues)) {
xtsValues <- ret
} else {
xtsValues <- cbindRobust(xtsValues, ret)
}
} else {
# If multiple datatypes then the xts for each datatype has to be merged individually
for (j in 1:numDatatypes) {
if (i == 1 || is.null(xtsValues[[j]]) || isTRUE(is.na(xtsValues[[j]]))) {
# First run
xtsValues[[j]] <- ret[[j]]
} else {
xtsValues[[j]] <- cbindRobust(xtsValues[[j]], ret[[j]])
}
}
}
} else if (format == "ByDatatype") {
# ByDatatype might be a simple implementation unless we have too many datatypes.
# should simply set a limit on the number of datatypes of less than chunk limit.
stop("chunking of ByDatatype not implemented")
} else if (format == "Snapshot" | format == "SnapshotList") {
# Nothing to do :-)
} else (
stop("Unknown format type")
)
}
#Finished the chunking loop, so need to return according to the request type
if (format[1] == "ByInstrument" | format == "ByDatatype") {
return(xtsValues)
} else if (format == "Snapshot" | format == "SnapshotList") {
return(.self$myValues)
}
# should not get here
return(NULL)
})
#-----------------------------------------------------------------------------
#' @importFrom xts xts
dsws$methods(.basicRequestTSChunk = function(instrument,
datatype = "",
expression = "",
isList = FALSE,
startDate,
endDate,
frequency = "D",
kind = 0,
format = "ByInstrument",
isChunked = FALSE,
chunkNumber = 0,
chunkItems = NULL) {
"
Return a timeSeriesRequest from Datastream dsws. Should request
either a datatype or an expression not both. If a datatype is provided
then anything in Expression will be ignored.