Title: | Datastream API |
---|---|
Description: | Access Datastream content through <https://product.datastream.com/dswsclient/Docs/Default.aspx>., our historical financial database with over 35 million individual instruments or indicators across all major asset classes, including over 19 million active economic indicators. It features 120 years of data, across 175 countries – the information you need to interpret market trends, economic cycles, and the impact of world events. Data spans bond indices, bonds, commodities, convertibles, credit default swaps, derivatives, economics, energy, equities, equity indices, ESG, estimates, exchange rates, fixed income, funds, fundamentals, interest rates, and investment trusts. Unique content includes I/B/E/S Estimates, Worldscope Fundamentals, point-in-time data, and Reuters Polls. Alongside the content, sit a set of powerful analytical tools for exploring relationships between different asset types, with a library of customizable analytical functions. In-house timeseries can also be uploaded using the package to comingle with Datastream maintained datasets, use with these analytical tools and displayed in Datastream’s flexible charting facilities in Microsoft Office. |
Authors: | LSEG (Datastream) [aut, cre] |
Maintainer: | LSEG (Datastream) <[email protected]> |
License: | GPL (>= 3) |
Version: | 2.0.4 |
Built: | 2024-11-10 05:45:34 UTC |
Source: | https://github.com/cran/DatastreamR |
An RC class for accessing Datastream content through Datastream Web services API
DataClient object
DatastreamR::DSConnect
-> DataClient
useNaNforNotANumber
: TRUE by default. NULLs are replaced to NaN (Not a Number)
new()
Initialize method to create Datastream Object
DataClient$new( config = NULL, username = "", password = "", proxys = NULL, sslCer = NULL )
config
: Config path
username
: Your Id
password
: Your Password
proxys
: Proxy details (if any)
sslCer
: ssl Certificates path
Creates Datastream RC object for accessing Datastream content through Datastream Web Services API
DataClient object
\dontrun{ # ds = DataClient$new(NULL, "YourID", "YourPswd") # OR # Login using config file # Config file details provided in DSConnect.R ds = DataClient("Config.ini") # Timeseries requests df = tryCatch ( {ds$getData(tickers="VOD", fields=list("PH","PL"), start='2022-01-12', end='2022-07-13', kind=1)}, error = function(e) { stop (message(e))}) print(df) # Snapshot requests df = tryCatch ( { ds$getData(tickers="VOD", fields=list("PH", "PL"), start='2022-01-12', kind=0)}, error = function(e) { stop (message(e))}) print(df) }
getData()
getData posts the JSON formatted request and the JSON response is then converted to Dataframe, if dataToDF is TRUE.
DataClient$getData( tickers, fields = NULL, start = "", end = "", freq = "D", kind = 1, properties = NULL )
tickers
: Intruments Eg: "VOD,BARC"
fields
: Datatypes Eg: list('PH, 'PL', 'PI')
start
: start date in "YYYY-mm-dd" format Eg: "2019-01-20"
end
: end date in
freq
: Refer DSDateFrequencyNames in DSRequests.R
kind
: 1 - TimeSeries Request (default), 0 - Snapshot Request
properties
: properties
Response Class
getDataframe()
getDataframe posts the JSON formatted request and the JSON response is then converted to Dataframe
DataClient$getDataframe( tickers, fields = NULL, start = "", end = "", freq = "D", kind = 1, properties = NULL )
tickers
: Intruments Eg: "VOD,BARC"
fields
: Datatypes Eg: list('PH, 'PL', 'PI')
start
: start date in "YYYY-mm-dd" format Eg: "2019-01-20"
end
: end date in
freq
: Refer DSDateFrequencyNames in DSRequests.R
kind
: 1 - TimeSeries Request (default), 0 - Snapshot Request
properties
: properties
Dataframe
formatDataRequest()
This method formats the request provided by client (in form of tickers and fields) to the JSON formatted request.
DataClient$formatDataRequest( tickers, fields = NULL, start = "", end = "", freq = "D", kind = 1 )
tickers
: Instruments
fields
: Datatypes
start
: start date
end
: end date
freq
: frequency
kind
: kind = 0 for Snapshot request and Kind = 1 for Timeseries request
JSON formatted data request
getDataBundle()
getData posts the JSON formatted request and the JSON response is then converted to Dataframe, if dataToDF is TRUE.
DataClient$getDataBundle(dataRequests, properties = NULL)
dataRequests
: dataRequests should be formed using formatDataRequest method
properties
: properties
Response Class
toDataframe()
Converts the Class response into a Dataframe which can be further used to plot
DataClient$toDataframe(dataResponse)
dataResponse
: The raw data response that is ingested into Dataframe
Dataframe
clone()
The objects of this class are cloneable with this method.
DataClient$clone(deep = FALSE)
deep
Whether to make a deep clone.
## ------------------------------------------------ ## Method `DataClient$new` ## ------------------------------------------------ ## Not run: # ds = DataClient$new(NULL, "YourID", "YourPswd") # OR # Login using config file # Config file details provided in DSConnect.R ds = DataClient("Config.ini") # Timeseries requests df = tryCatch ( {ds$getData(tickers="VOD", fields=list("PH","PL"), start='2022-01-12', end='2022-07-13', kind=1)}, error = function(e) { stop (message(e))}) print(df) # Snapshot requests df = tryCatch ( { ds$getData(tickers="VOD", fields=list("PH", "PL"), start='2022-01-12', kind=0)}, error = function(e) { stop (message(e))}) print(df) ## End(Not run)
## ------------------------------------------------ ## Method `DataClient$new` ## ------------------------------------------------ ## Not run: # ds = DataClient$new(NULL, "YourID", "YourPswd") # OR # Login using config file # Config file details provided in DSConnect.R ds = DataClient("Config.ini") # Timeseries requests df = tryCatch ( {ds$getData(tickers="VOD", fields=list("PH","PL"), start='2022-01-12', end='2022-07-13', kind=1)}, error = function(e) { stop (message(e))}) print(df) # Snapshot requests df = tryCatch ( { ds$getData(tickers="VOD", fields=list("PH", "PL"), start='2022-01-12', kind=0)}, error = function(e) { stop (message(e))}) print(df) ## End(Not run)
initializer
initializer
Config
: config file path
Username
: Your id
Password
: Your Password
Proxies
: Proxy Server details (if any)
SslCert
: ssl Certifactes file path
Url
: internal parameter set by application
RequestUrl
: internal parameter set up by application
Token
: Token received on successfull logon
TokenExpiry
: Expiry time of the token
Timeout
: Max Timeout set in Configuartion for the process to complete
Version
: Application Version
AppID
: Application Id
new()
DSConnect connects to the Datastream web service on behalf of derived classes and helps to send and retrieve data
DSConnect connects to the Datastream web service on behalf of derived classes
DSConnect$new( config = NULL, username = NA, password = NA, proxies = NULL, sslCert = NULL, service = NULL )
config
: config path
username
: your username
password
: your password
proxies
: proxy url, if any
sslCert
: path to ssl cert file
service
: internally set by the application
user details can be supplied from a config file or passed directly as parameters in the constructor of the derived user object type class.
1) Using ini file (e.g. config.ini) with format [credentials] username=YourID password=YourPwd [proxies] url=Your Proxy Url port=Proxy port username=Proxy Username password=Proxy Password [cert] sslCertFile=YourCertFile #only read if no sslCertFile entry sslCertPath=YourCertPath
getJsonResponse()
This method makes the query against the API service and does some basic error handling
DSConnect$getJsonResponse(requestUrl, request)
requestUrl
: Url used to send the Post request
request
: Raw Datastream request
getToken()
getToken uses you credentials to try and obtain a token to be used in subsequent request for data. The returned token is valid for 24 hours
DSConnect$getToken()
IsValid()
IsValid checks whether the token is valid against the token expiry time
DSConnect$IsValid()
CheckToken()
CheckToken checks whether the token is valid against the token expiry time and generates new token if the token has expired.
DSConnect$CheckToken()
clone()
The objects of this class are cloneable with this method.
DSConnect$clone(deep = FALSE)
deep
Whether to make a deep clone.
This list is a supporting attribute for the CarryIndicator properties of the DSTimeSeriesRequestObject and DSTimeSeriesResponseObjects. When you supply data which contains 'Not A Number' values (NaN) to denote non trading days, this list instructs the mainframe in how to store the values.
DSTimeSeriesCarryIndicator
DSTimeSeriesCarryIndicator
An object of class list
of length 3.
numeric
Yes
Any incoming NaN values are replaced with the last non-NaN value (e.g. 1,2,3,NaN,5,NaN,7,8 will be converted and stored as 1,2,3,3,5,5,7,8).
No
Any incoming NaN values are stored as is and returned as NaN values.
Pad
This is similar to YES, but also pads the final value for any dates your users may request beyond the last
date in your timeseries.
For example, if your timeseries supplies just 3 values 1, NaN and 3, and your user requests a range of dates two days
before and two days after your range, your user will receive the following values:
No: NaN, NaN, 1, NaN, 3, NaN, NaN
Yes: NaN, NaN, 1, 1, 3, NaN, NaN
Pad: NaN, NaN, 1, 1, 3, 3, 3
This class is a supporting attribute for the DateInput property of the DSTimeSeriesRequestObject. It is used to supply the raw data for the timeseries.
DSTimeSeriesDataInput object
StartDate
A datetime value defining the start date for the timeseries.
EndDate
A datetime value defining the end date for the timeseries.
Frequency
The frequency of the timeseries. One of the DSUserObjectFrequency values defined in DSUserDataObjectBase.R
Values
An array of float values. Use NULL to represent NotANumber for non-trading days. Alternatively, if you set the DatastreamUserCreated_TimeSeries property useNaNforNotANumber as True, you can use float NaN values.
new()
DSTimeSeriesDataInput$new( startDate = NULL, endDate = NULL, frequency = DSUserObjectFrequency$Daily, values = NULL )
startDate
A datetime value defining the start date for the timeseries.
endDate
A datetime value defining the end date for the timeseries.
frequency
The frequency of the timeseries.
values
An array of float values
DSTimeSeriesDataInput object
clone()
The objects of this class are cloneable with this method.
DSTimeSeriesDataInput$clone(deep = FALSE)
deep
Whether to make a deep clone.
Datastream takes the StartDate, Frequency and Values properties defined here and creates the timeseries based only on these parameters.The EndDate is not actually used internally other than for logging purposes. The true end date is calculated based on the start date, frequency and the supplied list of values. Supply too few or too many values and the mainframe will accept them and set the end date accordingly based on the given frequency for the item.
This list is a supporting attribute for the DateAlignment properties of the DSTimeSeriesRequestObject and DSTimeSeriesResponseObjects. When you supply monthly, quarterly or annual data, the dates are stored internally as the first day of the given period and always returned to you through this interface as the first date of the given period. However, when your users request data from Datastream, you can specify whether the dates returned to users are returned with dates set as the start, mid or end of the requested period
DSTimeSeriesDateAlignment
DSTimeSeriesDateAlignment
An object of class list
of length 3.
numeric
EndPeriod
This will return dates to your users that represent the last day of the month, quarter or year.
StartPeriod
This will return dates to your users that represent the first day of the month, quarter or year.
MidPeriod
This will return dates to your users that represent the middle of the month (15th day), quarter (15th of the middle month) or year (30th June).
This class is a supporting attribute for the DateInfo property of the DSTimeSeriesResponseObject. It describes the basic range of data for the timeseries.
The DateRange property (DSTimeSeriesDateRange described above) of the DSTimeSeriesResponseObject always returns the dates for a given frequency as the first date in each period (e.g. 2022-01-01, 2020-04-01, etc. for quarterly frequencies). However, The StartDate and EndDate values returned in this class for the DSTimeSeriesResponseObject reflect the start and end dates of the range of dates that would be returned to users requesting the data via Datastream For Office, charting, etc. This depends on the DateAlignment property (DSTimeSeriesDateAlignment) of the timeseries. The start and end dates returned here will be either the start, mid or end dates for the set frequency based on the DateAlignment property (see DSTimeSeriesDateAlignment).
DSTimeSeriesDateInfo object
StartDate
A datetime value defining the start date of the timeseries data
EndDate
A datetime value defining the end date for the timeseries.
Frequency
The frequency of the timeseries. One of the DSUserObjectFrequency values defined in DSUserDataObjectBase.R
new()
DSTimeSeriesDateInfo$new(jsonDict)
jsonDict
JSON dictionary (from JSON Response)
DSTimeSeriesDateInfo object
clone()
The objects of this class are cloneable with this method.
DSTimeSeriesDateInfo$clone(deep = FALSE)
deep
Whether to make a deep clone.
This class is a supporting attribute for the DateRange property of the DSTimeSeriesResponseObject.
It returns the raw data for the timeseries. The DateRange property of the DSTimeSeriesResponseObject always returns
the dates for a given frequency as the first date in each period. (e.g. 2022-01-01, 2020-04-01, etc. for quarterly
frequencies). You specify whether you want your users to receive either the first, mid or end dates in the given
period by setting the DateAlignment property (DSTimeSeriesDateAlignment) of the DSTimeSeriesRequestObject.
When you retrieve a list of all your available timeseries using the GetAllItems method, since this list could contain
many thousand timeseries objects, the Dates and Values lists will always be NULL. Only the ValuesCount field will be
set to reflect the number of datapoints available for each item. You need to request an individual timeseries
(GetItem method) in order to receive a response containing actual data in the Dates and Values properties.
DSTimeSeriesDateRange object
Dates
A list of datetime values specifying the dates for each datapoint.
Values
A list of float values specifying the values for each datapoint.
ValuesCount
A count of the number of datapoints in the timeseries.
new()
DSTimeSeriesDateRange$new(jsonDict, convertNullToNans = FALSE)
jsonDict
JSON dictionary (from JSON Response)
convertNullToNans
FALSE by default, TRUE converts the NULLs in the NaNs (Not a Number)
DSTimeSeriesDateRange object
clone()
The objects of this class are cloneable with this method.
DSTimeSeriesDateRange$clone(deep = FALSE)
deep
Whether to make a deep clone.
DSTimeSeriesDateRangeResponse is the object returned from the timeseries GetTimeseriesDateRange method. This method allows you to determine the supported dates between given start and end dates at a specified frequency.
DSTimeSeriesDateRangeResponse object
Dates
A list of datetime values representing the supported dates between requested start and end dates at a specified frequency.
ResponseStatus
This property will contain a DSUserObjectResponseStatus value. DSUserObjectResponseStatus$UserObjectSuccess represents a successful response.
ErrorMessage
If ResponseStatus is not DSUserObjectResponseStatus$UserObjectSuccess this status string will provide a description of the error condition.
Properties
Not currently used and will currently always return NULL.
new()
DSTimeSeriesDateRangeResponse$new(jsonDict = NULL)
jsonDict
: JSON dictionary (from JSON Response)
DSTimeSeriesDateRangeResponse object
clone()
The objects of this class are cloneable with this method.
DSTimeSeriesDateRangeResponse$clone(deep = FALSE)
deep
Whether to make a deep clone.
This list is a supporting attribute for the FrequencyConversion properties of the DSTimeSeriesRequestObject and DSTimeSeriesResponseObjects. This enumeration specifies how to return values if your end users requests the timeseries at a lower frequency. For example: if your timeseries has daily frequency data, and your user requests monthly or quarterly data, the FrequencyConversion property instructs the mainframe how to return monthly or quarterly data.
DSTimeSeriesFrequencyConversion
DSTimeSeriesFrequencyConversion
An object of class list
of length 4.
numeric
EndValue
The daily value for the end of the requested period will be returned.
AverageValue
The average of all the values for the requested period will be returned.
SumValues
The sum of all the values for the requested period will be returned.
ActualValue
The actual value for the requested start date will be returned for the same given date in the requested period.
This is a subclass of DSTimeSeriesUserObjectBase and is used to create or modify a timeseries. (See DSTimeSeriesUserObjectBase for details of all the superclass properties.)
DSTimeSeriesRequestObject object
DatastreamR::DSUserObjectBase
-> DatastreamR::DSTimeSeriesUserObjectBase
-> DSTimeSeriesRequestObject
Id
A valid TimeSeries Id
DataInput
A DSTimeSeriesDataInput object used to supply the start date, end date, frequency and list of data values. (See DSTimeSeriesDataInput for details.)
new()
DSTimeSeriesRequestObject$new( id = "", startDate = NULL, endDate = NULL, frequency = NULL, values = NULL )
id
A valid TimeSeries Id
startDate
A datetime value defining the start date for the timeseries
endDate
A datetime value defining the end date for the timeseries
frequency
The frequency of the timeseries. DSUserObjectFrequency is defined in DSUserDataObjectBase.R
values
list of float values
DSTimeSeriesRequestObject object
clone()
The objects of this class are cloneable with this method.
DSTimeSeriesRequestObject$clone(deep = FALSE)
deep
Whether to make a deep clone.
This is a subclass of DSTimeSeriesUserObjectBase and is used to return the details for a timeseries. (See DSTimeSeriesUserObjectBase for details of all the superclass properties.)
DSTimeSeriesResponseObject object
DatastreamR::DSUserObjectBase
-> DatastreamR::DSTimeSeriesUserObjectBase
-> DSTimeSeriesResponseObject
DateInfo
A DSTimeSeriesDateInfo object defining the start date, end date and frequency of the timeseries.
DateRange
A DSTimeSeriesDateRange object used to return the dates and values stored in the timeseries. See DSTimeSeriesDateRange for details.
new()
DSTimeSeriesResponseObject$new(jsonDict = NULL, convertNullToNans = FALSE)
jsonDict
: JSON dictionary (from JSON Response)
convertNullToNans
: FALSE by default, TRUE converts the NULLs in the NaNs (Not a Number)
DSTimeSeriesResponseObject object
clone()
The objects of this class are cloneable with this method.
DSTimeSeriesResponseObject$clone(deep = FALSE)
deep
Whether to make a deep clone.
This is the base object for creating or requesting timeseries data. It has two subclasses
DSTimeSeriesRequestObject and DSTimeSeriesResponseObject. It defines the basic attributes for a timeseries.
It subclasses DSUserObjectBase which defines the basic attributes common to all five user created item types
supported by the API.
Specifics of some of the properties of the DSUserObjectBase superclass
———————————————————————-
ID
The ID property is defined in DSUserObjectBase but has a specific format for timeseries. Timeseries IDs must be
8 alphanumeric characters long, start with TS followed by 6 uppercase
alphanumeric characters. For example: TSTEST01, TS123456, TSMYTEST, etc.
Mnemonic
The Mnemonic property is defined in DSUserObjectBase but should always be left empty or set the same as the
ID property for timeseries requests. As a safety measure, this class always ensures it's the same as the ID.
In a response from the API server, the value will always be the same as the ID.
(see DSUserObjectBase for a description of the other properties)
DSTimeSeriesUserObjectBase specific properties
DSTimeSeriesUserObjectBase object
DatastreamR::DSUserObjectBase
-> DSTimeSeriesUserObjectBase
ManagementGroup
This is an optional group name that allows you to organise timeseries into distinct 'folders' displayed in the search category of Navigator. This can be up to 10 uppercase alphanumeric characters. Leave blank for the item to be assigned under the 'GENERAL' group.
Units
This is a optional qualifying unit for your data. For example: tons, U$ millions, index, etc. Maximum 12 characters.
DecimalPlaces
A numeric value between 0 and 8 decimal places specifying how many decimal places to use when storing data. The maximum length including decimals for a value is 10 characters including the decimal point. Boundary case examples are 0.12345678, 1234567890, 123456789.0, etc.
FrequencyConversion
A DSTimeSeriesFrequencyConversion enum value specifying how to return values if a user requests data at a lower frequency than the timeseries data is supplied. See DSTimeSeriesFrequencyConversion for details.
DateAlignment
A DSTimeSeriesDateAlignment enum value specifying whether dates for certain frequencies should be returned as the start, middle or end date of the period. See DSTimeSeriesDateAlignment for details.
CarryIndicator
A DSTimeSeriesCarryIndicator enum value specifying how to treat 'Not A Number' values for non-trading days and how to represent values if users request data after the end of the timeseries range. See DSTimeSeriesCarryIndicator for details.
PrimeCurrencyCode
An optional 2 character currency code for your timeseries.
HasPadding
This property has been replaced with the CarryIndicator property and will always be False
UnderCurrencyCode
This property has been deprecated and will always return NULL
AsPercentage
This This property has been deprecated and will always return False
new()
DSTimeSeriesUserObjectBase$new(jsonDict)
jsonDict
JSON dictionary (from JSON Response)
DSTimeSeriesUserObjectBase object
clone()
The objects of this class are cloneable with this method.
DSTimeSeriesUserObjectBase$clone(deep = FALSE)
deep
Whether to make a deep clone.
All user created objects have a flag specifying if they can be modified by the u All items that have their ShareType property set to DSUserObjectShareTypes. PrivateUserGroup will also have their AccessRight property set to ReadWrite. Global expression objects, not being editable by users, will have the AccessRight property set to Read.
DSUserObjectAccessRights
DSUserObjectAccessRights
An object of class list
of length 2.
numeric
DSUserObjectBase is the base object for all five user object types. It defines the properties common to all the types
DSUserObjectBase object
Id
The object identifier. The format is specific to each object type. See the individual object file for the particular specification
Mnemonic
For all object types bar indices, this is the same as the Id property. For indices, the ID (of the form X#:Xnnnnn where n is a digit) is returned when you create an index and is used to manage the index via the API interface. The Mnemonic property is specified when creating an index and is used to reference the index when using Datastream tools such as Charting, Datastream For Office, etc. A mnemonic has format X#aaaaa where aaaaa is 1 to 6 alphanumeric characters.
DisplayName
A string describing the object. The maximum length varies from object type to
object type.
Expression: Max 30 alphanumeric characters.
Index: Max 60 alphanumeric characters.
List: Max 60 alphanumeric characters.
Regression: Max 50 alphanumeric characters.
Timeseries: Max 64 alphanumeric characters.
Description
Currently this isn't supported. When the API returns an object, the Description property will be the same as the DisplayName property.
Created
a datetime value representing the date when the object was first created.
LastModified
a datetime value representing the date when the object was last updated.
Owner
The parent Datastream ID that owns the object. This will be the parent of your Datastream ID. For global expressions this will always be 'Admin'
ShareType
For all objects except global expressions, this will be DSUserObjectShareTypes. PrivateUserGroup. For global expressions it will be DSUserObjectShareTypes.Global.
AccessRight
For all objects except global expressions, this will be DSUserObjectAccessRights. ReadWrite. For global expressions it will be DSUserObjectAccessRights.Read.
new()
Initialize
DSUserObjectBase$new(jsonResp = NULL)
jsonResp
: json Response
DSUserObjectBase object
SetSafeUpdateParams()
The following parameters are set only in response when we query for user created items. This method is called before Create or Update to ensure safe values set prior to JSON encoding
DSUserObjectBase$SetSafeUpdateParams()
No return value
clone()
The objects of this class are cloneable with this method.
DSUserObjectBase$clone(deep = FALSE)
deep
Whether to make a deep clone.
Regressions and Timeseries objects specify a frequency for the underlying data. DSUserObjectFrequency defines the supported frequencies.
DSUserObjectFrequency
DSUserObjectFrequency
An object of class list
of length 5.
numeric
This is the object returned for the client class' GetAllItems query only.
For GetAllItems queries only, the returned objects will not have all their property fields set.
Specifically for below:
Expression: All property fields are fully populated.
Index: The ConstituentsCount property will correctly specify the number of constituents but the
Constituents property will be NULL.
List: The ConstituentsCount property will correctly specify the number of constituents but the
Constituents property will be NULL.
Regression: All property fields are fully populated.
Timeseries: The ValuesCount field of the DateRange property will specify the number of date value
pairs, but the Dates and Values fields will be NULL.
You need to query for the individual object using the GetItem request to retrieve the full content
for the object.
DSUserObjectGetAllResponse object
UserObjectType
specifies the returned object types. e.g. DSUserObjectTypes.List, DSUserObjectTypes.TimeSeries, etc.
UserObjects
An array of the specified object types such as DSListUserObject, DSRegressionUserObject, etc.
UserObjectsCount
The number of objects returned in the UserObjects property.
ResponseStatus
This property will contain a DSUserObjectResponseStatus value. DSUserObjectResponseStatus.UserObjectSuccess represents a successful response.
ErrorMessage
If ResponseStatus is not DSUserObjectResponseStatus.UserObjectSuccess this status string will provide a description of the error condition.
Properties
Not currently used and will currently always return NULL.
new()
Initialize
DSUserObjectGetAllResponse$new(jsonResp = NULL)
jsonResp
JSON Response
DSUserObjectGetAllResponse object
clone()
The objects of this class are cloneable with this method.
DSUserObjectGetAllResponse$clone(deep = FALSE)
deep
Whether to make a deep clone.
This is the object returned from the client class' GetItem, CreateItem, UpdateItem and DeleteItem requests.
DSUserObjectResponse object
UserObjectId
The ID of the object requested. If the item is deleted, the UserObject property will be NULL but the UserObjectId field will be populated
UserObjectType
specifies the returned object type. e.g. DSUserObjectTypes.List, DSUserObjectTypes.TimeSeries, etc.
UserObject
For all queries bar DeletItem, if the query is successful, this property will contain the user created item requested.
ResponseStatus
This property will contain a DSUserObjectResponseStatus value. DSUserObjectResponseStatus.UserObjectSuccess represents a successful response.
ErrorMessage
If ResponseStatus is not DSUserObjectResponseStatus.UserObjectSuccess this status string will provide a description of the error condition.
Properties
Not currently used and will currently always return NULL.
new()
Initialize
DSUserObjectResponse$new(jsonResp = NULL)
jsonResp
JSON Response
DSUserObjectResponse object
clone()
The objects of this class are cloneable with this method.
DSUserObjectResponse$clone(deep = FALSE)
deep
Whether to make a deep clone.
All client methods to retrieve or modify user created items return a respone object which
includes a ResponseStatus property.The ResponseStatus property specifies success or failure
for the request using a DSUserObjectResponseStatus value
Response Values:
UserObjectSuccess : The request succeeded and the response object's UserObject(s) property
should contain the (updated) object (except for DeleteItem method).
UserObjectPermissions : Users need to be specifically permissioned to create custom objects.
This flag is set if you are not currently permissioned.
UserObjectNotPresent : Returned if the requested ID does not exist.
UserObjectFormatError : Returned if your request object is not in the correct format.
UserObjectTypeError : Returned if your supplied object is not the same as the type specified.
UserObjectError : The generic error flag. This will be set for any error not specified above.
Examples are:
1.Requested object ID is not present
2.You have exceeded the number of custom objects permitted on your account.
DSUserObjectResponseStatus
DSUserObjectResponseStatus
An object of class list
of length 6.
numeric
Five user created types are supported. When the client classes communicate with the API server, a DSUserObjectTypes property is set to specify the object type. Responses from the API server also specify the type of the object being returned.
DSUserObjectTypes
DSUserObjectTypes
An object of class list
of length 6.
numeric
This is the client class that manages the connection to the API server on your behalf. It allows you to query for all your timeseries and to create/modify new timeseries.
Methods Supported
GetAllItems : Allows you to query for all the current timeseries available for your use.
GetItem : Allows you to download the details of a specific timeseries item.
GetTimeseriesDateRange : Allows you to determine the supported timeseries dates between supplied start and
end dates at a specified frequency.
CreateItem : Allows you to create a new timeseries item with up to 130 years of daily data.
UpdateItem : Allows you to update an existing timeseries.
DeleteItem : Allows you to delete an existing timeseries.
TimeSeriesClient object
DatastreamR::DSConnect
-> TimeSeriesClient
useNaNforNotANumber
If Enabled, NaN is appears in output response instead of NULL
TimeseriesResponseType
Response type
new()
User details can be supplied from a config file or passed directly as parameters in the constructor of the derived user object type class. (See the DSConnect superclass for a description of the connection parameters required)
TimeSeriesClient$new( config = NULL, username = NULL, password = NULL, proxies = NULL, sslCer = NULL )
config
Configuration File path
username
Your Datastream Id
password
Your Password
proxies
Proxies if any
sslCer
Path to CA bundle certificates file
Timeseries Properties:
useNaNforNotANumber : Non-trading days are stored as double NaNs on Datastream, JSON protocol permits NaNs as valid numbers.
Thus, all the NULLs in the converted to NaNs in the JSON requests. Responses contain the NULLs, But this should be converted
to Nans for Plotting purposes. If you want to receive NaN float values, set useNaNforNotANumber to TRUE, any NULLs in the returned
array of float values will be converted to NaNs.
TimeSeriesClient object
.checkValidTimeseriesId()
A helper method to check the timeseries Id
TimeSeriesClient$.checkValidTimeseriesId(inputId)
inputId
: Timeseries Id
NULL if Timeseries id is valid else error string
.checkTimeSeriesReqValidity()
A helper method to check some of the mandatory fields of timeseries for its validity
TimeSeriesClient$.checkTimeSeriesReqValidity(tsItem)
tsItem
Timeseries Item
NULL if Timeseries id is valid else error string
.checkKeyTimeseriesProperties()
A helper method to check the Timeseries properties
TimeSeriesClient$.checkKeyTimeseriesProperties(tsItem)
tsItem
Timeseries Item
NULL if Timeseries id is valid else error string
.asGetAllResponse()
A helper method which converts the JSON response to GetAllResponse Object
TimeSeriesClient$.asGetAllResponse(jsonDict)
jsonDict
JSON Response
DSUserObjectGetAllResponse object
.asGetResponse()
A helper method which converts the JSON response to GetResponse Object
TimeSeriesClient$.asGetResponse(jsonDict)
jsonDict
JSON Response
DSUserObjectResponse object
.jsonRequestEncoder()
A helper method that reformats the raw request to JSON format
TimeSeriesClient$.jsonRequestEncoder(request)
request
Raw request
return JSON formatted list
.jsonResponseDecoder()
A helper method that converts JSON Response to a given class response type
TimeSeriesClient$.jsonResponseDecoder(jsonResp, responseType)
jsonResp
JSON Response
responseType
GetResponse or GetAllResponse type
return DSUserObjectGetAllResponse or DSUserObjectGetResponse object
GetAllItems()
This method returns all the current timeseries you can use in Datastream queries.
TimeSeriesClient$GetAllItems()
DSUserObjectGetAllResponse object
GetItem()
GetItem returns the details for an individual timeseries.
TimeSeriesClient$GetItem(itemId)
itemId
: a valid timeseries Id.
DSUserObjectResponse object
CreateItem()
This method attempts to create the given DSTimeSeriesRequestObject via the API service
TimeSeriesClient$CreateItem(newItem, overWrite = FALSE, skipItemReturn = FALSE)
newItem
A DSTimeSeriesRequestObject containing the data used for creating the Timeseries.
overWrite
If the given Timeseries Id already exists on the system, the create call will be rejected. Set overWrite = True to overwrite the existing item with new Timeseries.
skipItemReturn
: Upon successful creation of an item, the server requests the new item from the mainframe and returns it in the response object. For faster processing, set skipItemReturn = True to skip returning the object in the response
DSUserObjectResponse object
UpdateItem()
This method attempts to modify a timeseries item using the given DSTimeSeriesRequestObject via the API service
TimeSeriesClient$UpdateItem(item, skipItemReturn = FALSE)
item
A DSTimeSeriesRequestObject containing the data used for creating the Timeseries.
skipItemReturn
Upon successful creation of an item, the server requests the new item from the mainframe and returns it in the response object. For faster processing, set skipItemReturn = True to skip returning the object in the response.
DSUserObjectResponse object
DeleteItem()
DeleteItem allows you to delete an existing timeseries
TimeSeriesClient$DeleteItem(itemId)
itemId
a valid timeseries Id.
No return value
GetTimeseriesDateRange()
This method allows you to determine the supported dates between supplied start and end dates at a specified frequency.
TimeSeriesClient$GetTimeseriesDateRange( startDate, endDate, frequency = DSUserObjectFrequency$Daily )
startDate
A date specifying the beginning of the date range
endDate
A date specifying the end of the date range
frequency
A DSUserObjectFrequency enumeration defining if the frequency should be daily, weekly, monthly, quarterly or yearly.
DSTimeSeriesDateRangeResponse object
clone()
The objects of this class are cloneable with this method.
TimeSeriesClient$clone(deep = FALSE)
deep
Whether to make a deep clone.
: You need a Datastream ID which is permissioned to access the Datastream APIs. In addition, this ID also needs to be permissioned to access the custom user object service. Attempting to access this service without these permissions will result in a permission denied error response.
: For Daily and Weekly frequencies, if the supplied startDate falls on a weekend or a trading holiday, the returned
starting date will be the first trading day before the given start date. If the supplied endDate falls on a weekend or a
trading holiday, the returned final date will be the last trading day before the given end date. For Weekly frequencies,
this will be the last date which matches the day of the week for the first returned start date.
For Monthly, Quarterly and Yearly frequencies, the returned dates are always the 1st day of each month, quarter or year.
The returned start and end dates are always the 1st days of the requested month, quarter or year that the given start
and end dates fall within.
: For Daily and Weekly frequencies, if the supplied startDate falls on a weekend or a trading holiday, the returned
starting date will be the first trading day before the given start date. If the supplied endDate falls on a weekend or a
trading holiday, the returned final date will be the last trading day before the given end date. For Weekly frequencies,
this will be the last date which matches the day of the week for the first returned start date.
For Monthly, Quarterly and Yearly frequencies, the returned dates are always the 1st day of each month, quarter or year.
The returned start and end dates are always the 1st days of the requested month, quarter or year that the given start
and end dates fall within.
{ # first logon with your credentials. # Creating a TimeSeriesClient instance with your credentials # automatically logs on for you. timeseriesClient = TimeSeriesClient$new(NULL, 'YourID', 'YourPwd') # query for all your current timeseries items itemsResp = timeseriesClient$GetAllItems() if (!is.null(itemsResp)) { if (itemsResp$ResponseStatus != DSUserObjectResponseStatus$UserObjectSuccess) { # Your Datastream Id might not be permissioned for managing # user created items on this API print(paste('GetAllItems failed with error ', names(DSUserObjectResponseStatus)[[itemsResp$ResponseStatus + 1]], ': ', itemsResp$ErrorMessage)) } else if (!is.null(itemsResp$UserObjects) & itemsResp$UserObjectsCount > 0) { # You do have access to some timeseries # Here we just put the timeseries details into a dataframe and list them print(paste('GetAllItems returned', itemsResp$UserObjectsCount, 'timeseries items.')) df = data.frame() for (tsItem in itemsResp$UserObjects) { if (!is.null(tsItem)) { rowdata = list(Id = tsItem$Id, LastModified = tsItem$LastModified, StartDate = ifelse(!is.null(tsItem$DateInfo),as.character(tsItem$DateInfo$StartDate),""), EndDate =ifelse(!is.null(tsItem$DateInfo),as.character(tsItem$DateInfo$EndDate), ""), Frequency = ifelse(!is.null(tsItem$DateInfo), tsItem$DateInfo$Frequency, 0), NoOfValues = ifelse(!is.null(tsItem$DateRange), tsItem$DateRange$ValuesCount , 0), Desc = tsItem$Description) df = rbind(df, rowdata) } } print(df) } } #Example to show how to GetItem # query for a specific timeseries tsName = 'TSZZZ001' tsResponse = timeseriesClient$GetItem(tsName) # You may want to put the timeseries request response handling into a common function. if (!is.null(tsResponse)) { # Any request dealing with a single user created item returns a DSUserObjectResponse. # This has ResponseStatus property that indicates success or failure if (tsResponse$ResponseStatus != DSUserObjectResponseStatus$UserObjectSuccess) { print(paste('Request failed for timeseries', tsName, 'with error', names(DSUserObjectResponseStatus)[[tsResponse$ResponseStatus+1]], ':', tsResponse$ErrorMessage)) } else if (!is.null(tsResponse$UserObject)) { # The timeseries item won't be returned if you set SkipItem true # in CreateItem or UpdateItem # Here we simply display the timeseries data using a dataframe. tsItem = tsResponse$UserObject metadata = c (Id = tsItem$Id, Desc = tsItem$Description, LastModified = as.character(tsItem$LastModified), StartDate = ifelse (!is.null(tsItem$DateInfo), as.character(tsItem$DateInfo$StartDate), NULL), EndDate = ifelse(!is.null(tsItem$DateInfo),as.character(tsItem$DateInfo$EndDate), NULL), Frequency = ifelse(!is.null(tsItem$DateInfo), names(DSUserObjectFrequency)[[tsItem$DateInfo$Frequency + 1]], NULL), NoOfValues = ifelse(!is.null(tsItem$DateRange), tsItem$DateRange$ValuesCount , 0)) df = data.frame(metadata) print(df) if (!is.null(tsItem$DateRange)) { df = data.frame(Dates = sapply(tsItem$DateRange$Dates, FUN = function(x){ return (as.character(x)) }), Values = sapply(tsItem$DateRange$Values, FUN = function(x){ ifelse (is.null(x), return (NA_character_ ), return (x) )} )) # Values if NULL, is printed as <NA> because, while # convertind list to vector either by using as.vector or sapply, # the NULL values in the list are deleted. and thus there will # be mismatch in no of rows and cannot be put in a dataframe print(df) } } } }
{ # first logon with your credentials. # Creating a TimeSeriesClient instance with your credentials # automatically logs on for you. timeseriesClient = TimeSeriesClient$new(NULL, 'YourID', 'YourPwd') # query for all your current timeseries items itemsResp = timeseriesClient$GetAllItems() if (!is.null(itemsResp)) { if (itemsResp$ResponseStatus != DSUserObjectResponseStatus$UserObjectSuccess) { # Your Datastream Id might not be permissioned for managing # user created items on this API print(paste('GetAllItems failed with error ', names(DSUserObjectResponseStatus)[[itemsResp$ResponseStatus + 1]], ': ', itemsResp$ErrorMessage)) } else if (!is.null(itemsResp$UserObjects) & itemsResp$UserObjectsCount > 0) { # You do have access to some timeseries # Here we just put the timeseries details into a dataframe and list them print(paste('GetAllItems returned', itemsResp$UserObjectsCount, 'timeseries items.')) df = data.frame() for (tsItem in itemsResp$UserObjects) { if (!is.null(tsItem)) { rowdata = list(Id = tsItem$Id, LastModified = tsItem$LastModified, StartDate = ifelse(!is.null(tsItem$DateInfo),as.character(tsItem$DateInfo$StartDate),""), EndDate =ifelse(!is.null(tsItem$DateInfo),as.character(tsItem$DateInfo$EndDate), ""), Frequency = ifelse(!is.null(tsItem$DateInfo), tsItem$DateInfo$Frequency, 0), NoOfValues = ifelse(!is.null(tsItem$DateRange), tsItem$DateRange$ValuesCount , 0), Desc = tsItem$Description) df = rbind(df, rowdata) } } print(df) } } #Example to show how to GetItem # query for a specific timeseries tsName = 'TSZZZ001' tsResponse = timeseriesClient$GetItem(tsName) # You may want to put the timeseries request response handling into a common function. if (!is.null(tsResponse)) { # Any request dealing with a single user created item returns a DSUserObjectResponse. # This has ResponseStatus property that indicates success or failure if (tsResponse$ResponseStatus != DSUserObjectResponseStatus$UserObjectSuccess) { print(paste('Request failed for timeseries', tsName, 'with error', names(DSUserObjectResponseStatus)[[tsResponse$ResponseStatus+1]], ':', tsResponse$ErrorMessage)) } else if (!is.null(tsResponse$UserObject)) { # The timeseries item won't be returned if you set SkipItem true # in CreateItem or UpdateItem # Here we simply display the timeseries data using a dataframe. tsItem = tsResponse$UserObject metadata = c (Id = tsItem$Id, Desc = tsItem$Description, LastModified = as.character(tsItem$LastModified), StartDate = ifelse (!is.null(tsItem$DateInfo), as.character(tsItem$DateInfo$StartDate), NULL), EndDate = ifelse(!is.null(tsItem$DateInfo),as.character(tsItem$DateInfo$EndDate), NULL), Frequency = ifelse(!is.null(tsItem$DateInfo), names(DSUserObjectFrequency)[[tsItem$DateInfo$Frequency + 1]], NULL), NoOfValues = ifelse(!is.null(tsItem$DateRange), tsItem$DateRange$ValuesCount , 0)) df = data.frame(metadata) print(df) if (!is.null(tsItem$DateRange)) { df = data.frame(Dates = sapply(tsItem$DateRange$Dates, FUN = function(x){ return (as.character(x)) }), Values = sapply(tsItem$DateRange$Values, FUN = function(x){ ifelse (is.null(x), return (NA_character_ ), return (x) )} )) # Values if NULL, is printed as <NA> because, while # convertind list to vector either by using as.vector or sapply, # the NULL values in the list are deleted. and thus there will # be mismatch in no of rows and cannot be put in a dataframe print(df) } } } }