### Install DatastreamPy Package Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This command demonstrates how to install the DatastreamPy Python package using pip, the standard package installer for Python. This is the first step required to use the library. ```Shell pip install DatastreamPy ``` -------------------------------- ### Configure Proxies and Certificates for DatastreamPy Client in Python Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This Python example demonstrates how to initialize the EconomicFilters client with custom proxy, SSL verification, and client certificate settings. These parameters allow users to configure network access and security for API requests directly through the client constructor. ```Python x = EconomicFilters(None, username = 'YourID', password = 'YourPwd', proxies = x, sslVerify = y, sslCert = z) ``` -------------------------------- ### Initialize DataClient for Timeseries and Static Data Retrieval Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This code initializes the DataClient object, which is essential for accessing Datastream's timeseries and static data. It demonstrates loading credentials from a configuration file and setting up start and end dates for data retrieval, preparing for subsequent data requests. ```Python ds = dsweb.DataClient('Config.ini') start_date = '2020-01-01' end_date = '2022-12-31' ``` -------------------------------- ### Optimize Datastream Economic Updates with DATASTREAM_KEYIND_GLOBAL Filter Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This Python example demonstrates how to significantly reduce the volume of economic updates by applying the DATASTREAM_KEYIND_GLOBAL custom filter during the GetEconomicChanges call. This filter targets the most popular economic series, making the update processing more efficient, especially when dealing with a large universe of series. ```Python print('Let us repeat the processing using the same starting sequence ID. This time we will use the global filter DATASTREAM_KEYIND_GLOBAL.') updatesResp = econFilterClient.GetEconomicChanges(None, sequenceId, 'DATASTREAM_KEYIND_GLOBAL') if updatesResp: if updatesResp.ResponseStatus != dsweb.DSFilterResponseStatus.FilterSuccess: print('GetEconomicChanges failed with error ' + updatesResp.ResponseStatus.name + ': ' + updatesResp.ErrorMessage) else: if updatesResp.Updates and updatesResp.UpdatesCount > 0: # You have some updates; process them. print ('You have {:,} new updates:'.format(updatesResp.UpdatesCount)) updates = [[update.Series, update.Frequency.name, update.Updated.strftime('%Y-%m-%d %H:%M:%S')] for update in updatesResp.Updates] df = pd.DataFrame(data=updates, columns=['Series', 'Frequency', 'Updated']) print(df, end='\n\n') if updatesResp.UpdatesPending: print ('You still have {:,} updates pending starting from new sequence {}.'.format(updatesResp.PendingCount, updatesResp.NextSequenceId)) else: print ('You have no more updates pending. Use the new sequence {} and the filter to begin polling for future updates.'.format(updatesResp.NextSequenceId)) ``` -------------------------------- ### Querying Datastream Economic Changes with Custom Filters in Python Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This snippet demonstrates how to initialize the EconomicFilters client and query for economic items that have updated since a specified start date. It highlights the process of polling for recent changes using sequence IDs and mentions the global filter DATASTREAM_KEYIND_GLOBAL for reducing update volume. ```Python import DatastreamPy as dsweb import pandas as pd # Try creating the client by replacing 'YourID' and 'YourPwd' with your own credentials. econFilterClient = EconomicFilters(None, 'YourID', 'YourPwd') # We'll start searching for any changes beginning 3 weeks ago (you can go back a maximum of 28 days) # NB: Setting the timestamp to None will set the start date at 00:00 hours on the previous weekday from now updatesResp = econFilterClient.GetEconomicChanges(datetime.today() - timedelta(days=21)) ``` -------------------------------- ### Retrieve and Process Datastream Economic Updates with Sequence Tracking Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This Python snippet demonstrates how to fetch economic changes from the Datastream API, process the received updates, and manage the NextSequenceId for continuous polling. It includes error handling for filter requests and logic to identify and report pending updates, guiding the user on how to continue retrieving subsequent data blocks. ```Python sequenceId = 0 # placeholder which we will update and use later in the demo if updatesResp: if updatesResp.ResponseStatus != dsweb.DSFilterResponseStatus.FilterSuccess: # Any filter request errors, such as invalid filter, not being explicity permissioned to use custom economic filters, etc. print('GetEconomicChanges failed with error ' + updatesResp.ResponseStatus.name + ': ' + updatesResp.ErrorMessage) else: sequenceId = updatesResp.NextSequenceId # we'll now use this starting sequence in the following test cells. updatesResp = econFilterClient.GetEconomicChanges(None, sequenceId) if updatesResp: if updatesResp.ResponseStatus != dsweb.DSFilterResponseStatus.FilterSuccess: print('GetEconomicChanges failed with error ' + updatesResp.ResponseStatus.name + ': ' + updatesResp.ErrorMessage) else: if updatesResp.Updates and updatesResp.UpdatesCount > 0: # You have some updates; process them and retrieve the NextSequenceID for retrieving any subsequent updates. print ('You have {:,} new updates:'.format(updatesResp.UpdatesCount)) updates = [[update.Series, update.Frequency.name, update.Updated.strftime('%Y-%m-%d %H:%M:%S')] for update in updatesResp.Updates] df = pd.DataFrame(data=updates, columns=['Series', 'Frequency', 'Updated']) print(df, end='\n\n') if updatesResp.UpdatesPending: print ('You still have {:,} updates pending starting from new sequence {}.'.format(updatesResp.PendingCount, updatesResp.NextSequenceId)) else: print ('You have no more updates pending. Use the new sequence {} to begin polling for future updates.'.format(updatesResp.NextSequenceId)) ``` -------------------------------- ### Initialize DatastreamPy Client (v1.0.x vs v2.0.x) Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This snippet illustrates the evolution of DatastreamPy client initialization from version 1.0.x to 2.0.x. In older versions, credentials were directly supplied. Version 2.0.x renames the client to DataClient and introduces support for loading credentials from a configuration file, while still allowing direct credential input. Direct credentials override configuration file settings. ```Python # In earlier versions (1.0.x), you need to supply your credentials. ds = dsweb.Datastream(username='YourID', password='YourPwd') # In version 2.0.x, the client has been renamed from Datastream to DataClient and the credentials can be supplied from a configuration file ds = dsweb.DataClient('Config.ini') # or supplied directly as before. ds = dsweb.DataClient(None, 'YourID', 'YourPwd') # Note credentials supplied in the constructor will override any credentials set in the configuration file if also provided ds = dsweb.DataClient('Config.ini', 'YourIdOverride', 'YourPwdOverride') ``` -------------------------------- ### DatastreamPy Configuration File for Proxies and Certificates Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This configuration file snippet illustrates how to define proxy settings, SSL verification options, and request timeouts for the DatastreamPy package. These settings provide a declarative way to manage network connectivity and security parameters for API interactions. ```INI [proxies] # of the form: { 'http' : proxyHttpAddress, 'https' : proxyHttpsAddress } proxies= [cert] # option to supply a specific python requests verify option. sslVerify= [app] timeout= ``` -------------------------------- ### DatastreamPy API Reference Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Detailed API documentation for key classes, methods, and response objects used in DatastreamPy for timeseries and economic data management. ```APIDOC DatastreamPy API Reference: DSUserObjectGetAllResponse: Description: Represents the response object for retrieving all user-created timeseries items. Properties: ResponseStatus: dsweb.DSUserObjectResponseStatus - Indicates the success or failure of the operation. ErrorMessage: str - Error message if the operation failed. UserObjectsCount: int - The total number of user objects returned. UserObjects: list[TimeseriesItem] - A list of TimeseriesItem objects. DSUserObjectResponseStatus: Description: Enum for the status of a user object response. Values: UserObjectSuccess: Indicates the operation was successful. TimeseriesItem: Description: Represents a single user-created timeseries item. Properties: Id: str - Unique identifier for the timeseries. Description: str - User-defined description of the timeseries. LastModified: datetime - The last modification date of the timeseries. DateInfo: object - Contains date-related information. StartDate: datetime - The start date of the timeseries data. EndDate: datetime - The end date of the timeseries data. Frequency: enum - The frequency of the timeseries (e.g., daily, monthly). DateRange: object - Contains data range information. ValuesCount: int - The number of data points in the timeseries. timeseriesClient: Description: Client for managing user-created timeseries items. Methods: GetAllItems(): Description: Retrieves all user-created timeseries items. Returns: DSUserObjectGetAllResponse GetItem(testID: str): Description: Retrieves the full details of a specific timeseries item by its ID. Parameters: testID: str - The ID of the timeseries item to retrieve. Returns: object (with ResponseStatus and UserObject properties) UpdateItem(testTs: TimeseriesItem): Description: Updates an existing timeseries item. Parameters: testTs: TimeseriesItem - The timeseries object with updated details. Returns: object (response status) DeleteItem(testID: str): Description: Deletes a timeseries item by its ID. Parameters: testID: str - The ID of the timeseries item to delete. Returns: object (response status) EconomicFilters: Description: Client for managing and querying economic filters and changes. Constructor: __init__(self, arg1: any, YourID: str, YourPwd: str): Description: Initializes the EconomicFilters client. Parameters: arg1: any - Placeholder, often None. YourID: str - Your Datastream user ID. YourPwd: str - Your Datastream password. Methods: GetEconomicChanges(startDate: datetime): Description: Queries for economic items that have updated since a given start date. Can go back a maximum of 28 days. Polling requires managing sequence IDs. Parameters: startDate: datetime - The date from which to start searching for changes. Returns: object (updatesResp, containing next sequence ID and updates) ``` -------------------------------- ### DatastreamPy Configuration File Structure Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This defines the structure of the configuration file (e.g., 'Config.ini') used by DatastreamPy. It includes sections for URL path, user credentials, proxy settings, SSL verification, and application timeout. The 'path' setting should typically only be modified for private network configurations under expert advice. ```INI [url] path= [credentials] username=YourID password=YourPwd [proxies] proxies= [cert] sslVerify= [app] timeout= ``` -------------------------------- ### Handle API Client Initialization Errors in Python Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This Python code demonstrates how to handle exceptions when initializing the EconomicFilters client. It catches DSUserObjectFault for API-specific errors like invalid credentials and a general Exception for network-related issues, providing informative error messages. ```Python try: # Try creating the client by replacing 'YourID' and 'YourPwd' with your own credentials. econFilterClient = dsweb.EconomicFilters(None. 'YourId', 'YourPwd') print('Successfully created the EconomicFilters client.', end='\n\n') except DSUserObjectFault as dsFault: print('EconomicFilters() failed returning a DSUserObjectFault exception:') print(dsFault) except Exception as exp: print('A network error occurred.') print(exp) ``` -------------------------------- ### Authenticate DatastreamPy Client with Credentials Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This snippet provides two methods for authenticating with Datastream: loading credentials from a specified configuration file (e.g., 'Config.ini') or directly supplying the username and password in the DataClient constructor. Using a configuration file is often preferred for managing sensitive information. ```Python # loading credentials from a config file ds = dsweb.DataClient('Config.ini') # loading credentials directly into the constructor ds = dsweb.DataClient(None, 'YourID', 'YourPwd') ``` -------------------------------- ### Internal HTTP Request with Proxies and Certificates in Python Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This Python snippet illustrates the internal use of the requests library's post method within the DatastreamPy package. It shows how proxy, certificate verification, and client certificate parameters are passed to handle secure and routed HTTP communication. ```Python httpResponse = self._reqSession.post(reqUrl, json = jsonRequest, proxies = self._proxies, verify = self._certfiles, cert = self._sslCert, timeout = self._timeout) ``` -------------------------------- ### DatastreamPy Timeseries API Reference Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Reference documentation for the `TimeseriesClient` and associated objects in DatastreamPy, used for managing custom timeseries data. ```APIDOC dsweb.TimeseriesClient: Description: Client for managing custom timeseries data on Datastream. Methods: __init__(self, token: str, user_id: str, password: str): Description: Initializes the TimeseriesClient. Parameters: token: str | None - Authentication token. Can be None if user_id and password are provided. user_id: str - Your Datastream user ID. password: str - Your Datastream password. GetTimeseriesDateRange(self, startDate: date, endDate: date, freq: dsweb.DSUserObjectFrequency) -> dsweb.DSUserObjectDateRangeResponse: Description: Retrieves the list of supported dates for a given period and frequency for custom timeseries. Parameters: startDate: date - The start date for the desired date range. endDate: date - The end date for the desired date range. freq: dsweb.DSUserObjectFrequency - The frequency of the timeseries (e.g., Quarterly). Returns: dsweb.DSUserObjectDateRangeResponse - Contains supported dates and response status. CreateItem(self, timeseries_object: dsweb.DSTimeSeriesRequestObject, overWrite: bool = False) -> dsweb.DSUserObjectResponse: Description: Creates a new custom timeseries item or updates an existing one. Parameters: timeseries_object: dsweb.DSTimeSeriesRequestObject - The object containing the timeseries data and properties. overWrite: bool - If True, updates the item if it already exists; otherwise, creates a new item. Defaults to False. Returns: dsweb.DSUserObjectResponse - Indicates success or failure and the created/updated item details. GetAllItems(self) -> dsweb.DSUserObjectListResponse: Description: Retrieves summary details for all custom timeseries owned by the user. Returns: dsweb.DSUserObjectListResponse - Contains a list of user objects and response status. dsweb.DSTimeSeriesRequestObject: Description: Represents a custom timeseries object for creation or update operations. Properties: Id: str - Required. 8 uppercase alphanumeric characters, must start with 'TS' (e.g., 'TSZZZ001'). StartDate: date - Required. The start date of the timeseries data. EndDate: date - Required. The end date of the timeseries data. Frequency: dsweb.DSUserObjectFrequency - Required. The frequency of the timeseries. Values: list[float] - Required. The list of data points for the timeseries. DisplayName: str - Optional. A user-friendly name for the timeseries. Defaults to the Id if not set. DecimalPlaces: int - Optional. Number of decimal places for the values (0 to 8). Units: str - Optional. Custom text for units (max 12 characters). DateAlignment: dsweb.DSTimeSeriesDateAlignment - Optional. Specifies how quarterly dates are returned (e.g., MidPeriod). dsweb.DSUserObjectFrequency: Description: Enum defining supported frequencies for custom timeseries. Values: Quarterly dsweb.DSTimeSeriesDateAlignment: Description: Enum defining date alignment options for custom timeseries. Values: MidPeriod dsweb.DSUserObjectResponseStatus: Description: Enum defining the status of user object operations. Values: UserObjectSuccess dsweb.DSUserObjectResponse: Description: Response object for single user-created item operations (e.g., CreateItem, UpdateItem, DeleteItem). Properties: ResponseStatus: dsweb.DSUserObjectResponseStatus - The status of the operation. ErrorMessage: str - An error message if the operation failed. UserObject: dsweb.DSTimeSeriesRequestObject | None - The timeseries item, if the operation was successful and SkipItem was not true. dsweb.DSUserObjectDateRangeResponse: Description: Response object for the GetTimeseriesDateRange method. Properties: ResponseStatus: dsweb.DSUserObjectResponseStatus - The status of the operation. Dates: list[date] | None - A list of supported dates for the requested range and frequency. dsweb.DSUserObjectListResponse: Description: Response object for the GetAllItems method. Properties: ResponseStatus: dsweb.DSUserObjectResponseStatus - The status of the operation. UserObjects: list[dsweb.DSTimeSeriesRequestObject] | None - A list of summary user objects. ``` -------------------------------- ### Import DatastreamPy Library Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This Python statement shows how to import the DatastreamPy library into your script. It uses an alias 'dsweb' for convenience, allowing you to refer to the library's functions and classes using 'dsweb.' prefix. ```Python import DatastreamPy as dsweb ``` -------------------------------- ### List All Custom Timeseries in DatastreamPy Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Demonstrates how to retrieve a summary of all custom timeseries items owned by the user using the `GetAllItems` method of the `TimeseriesClient`. ```Python # list all the custom timeseries you already own itemsResp = timeseriesClient.GetAllItems() ``` -------------------------------- ### Retrieve Static Data with DatastreamPy Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Shows how to retrieve static data for specified tickers and fields using `ds.get_data` with `kind = 0`. The retrieved static data is then printed. ```Python staticdata = ds.get_data(tickers = '@AAPL,@MSFT', fields = ['NAME', 'ISIN', 'BDATE'], kind = 0) print(staticdata) ``` -------------------------------- ### DatastreamPy Configuration File Credentials Section Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This defines the specific section within the DatastreamPy configuration file dedicated to storing user credentials. Users must replace 'YourID' and 'YourPwd' with their actual Datastream username and password to enable authentication via the configuration file. ```INI [credentials] # Replace YourID and YourPwd values with your specific Datastream credentials. username=YourID password=YourPwd ``` -------------------------------- ### Datastream EconomicsFilter Object API Reference Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Provides an overview of the key methods available on the `EconomicsFilter` object for managing Datastream filters, including retrieving, updating, and deleting filters. ```APIDOC EconomicsFilter Object Methods: * GetAllFilters - returns a summary list of all filters owned by you and/or the globally available filters. * GetFilter - returns the full details, including constituents, for a specified filter. * UpdateFilter - allows you to append or remove specified constituent series or replace all the constituents. * DeleteFilter - allows you to delete one of your filters. ``` -------------------------------- ### Create or Update Custom Timeseries Data in DatastreamPy Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Illustrates the process of creating and uploading custom timeseries data to Datastream. It involves initializing a `TimeseriesClient`, retrieving supported dates, generating test data, constructing a `DSTimeSeriesRequestObject` with optional properties, and using `CreateItem` to upload or update the timeseries. ```Python import DatastreamPy as dsweb import pandas as pd # We import random only to generate some test data import random # create your client timeseriesClient = dsweb.TimeseriesClient(None, 'YourID', 'YourPwd') # Note Timeseries IDs must be 8 uppercase alphanumeric characters in length and start with TS. e.g. TSZZZ001 testID = 'TSZZZ001' # let us create a data series with quarterly values between 2016-01-01 and 2022-04-01 startDate = date(2016, 1, 1) endDate = date(2022, 4, 1) freq = dsweb.DSUserObjectFrequency.Quarterly # First step is to retrieve the list of supported dates for the above period dateRangeResp = timeseriesClient.GetTimeseriesDateRange(startDate, endDate, freq) if dateRangeResp: if dateRangeResp.ResponseStatus == dsweb.DSUserObjectResponseStatus.UserObjectSuccess and dateRangeResp.Dates != None: # You would normally use the returned supported dates to match up with dates in your data source # Here we will just create some random data based on the number of returned dates random.seed() values = [(random.randint(1000, 20000) / 100) for k in range(0, len(dateRangeResp.Dates))] # Construct our timeseries object with the ID, start and end dates, frequency and list of datapoints testTs = dsweb.DSTimeSeriesRequestObject(testID, startDate, endDate, freq, values) # Set any other optional properties directly testTs.DisplayName = 'My first test timeseries' # set to the same as the ID in the response by default. testTs.DecimalPlaces = 2 # we created our array of values with 2 decimal places. You can specify 0 to 8 decimal places. testTs.Units = "Billions" # Leave units blank or set with any custom text (max 12 chars). # when requested by users in data retrieval, you can specify the quarterly dates to be returned as start, middle or end of # the selected period (frequency). Here we want the quarterly data to be mid period (15th of middle month) testTs.DateAlignment = dsweb.DSTimeSeriesDateAlignment.MidPeriod # and create the new item with the overWrite option set to perfrom an update if the timeseries already exists. tsResponse = timeseriesClient.CreateItem(testTs, overWrite = True) # Any request dealing with a single user created item returns a DSUserObjectResponse. # This has ResponseStatus property that indicates success or failure if tsResponse.ResponseStatus != dsweb.DSUserObjectResponseStatus.UserObjectSuccess: print('Request failed for timeseries with error ' + tsResponse.ResponseStatus.name + ': ' + tsResponse.ErrorMessage, end='\n\n') elif tsResponse.UserObject != None: # 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 names = ['Id', 'Desc', 'LastModified', 'StartDate', 'EndDate', 'Frequency', 'NoOfValues'] coldata = [tsItem.Id, tsItem.Description, tsItem.LastModified.strftime("%Y-%m-%d"), tsItem.DateInfo.StartDate.strftime("%Y-%m-%d"), tsItem.DateInfo.EndDate.strftime("%Y-%m-%d"), tsItem.DateInfo.Frequency.name, tsItem.DateRange.ValuesCount] df = pd.DataFrame(coldata, index=names) ``` -------------------------------- ### Managing Datastream Timeseries Items in Python Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This snippet demonstrates how to interact with user-created timeseries items using DatastreamPy. It covers retrieving all items, fetching details for a specific item, updating an existing item, and deleting an item. It also shows how to handle API responses and display timeseries data using pandas DataFrames. ```Python # Returns a DSUserObjectGetAllResponse which has ResponseStatus property that indicates success or failure for the query if itemsResp: if itemsResp.ResponseStatus != dsweb.DSUserObjectResponseStatus.UserObjectSuccess: # Your Datastream Id might not be permissioned for managing user created items on this API print('GetAllItems failed with error ' + itemsResp.ResponseStatus.name + ': ' + itemsResp.ErrorMessage, end='\n\n') elif itemsResp.UserObjectsCount == 0 or itemsResp.UserObjects == None: print('GetAllItems returned zero timeseries items.', end='\n\n') else: """You do have access to some timeseries. # Here we just put the timeseries details into a dataframe and list them print('{}{}{}'.format('GetAllItems returned ', itemsResp.UserObjectsCount, ' timeseries items.')) data = [] colnames = ['Id', 'Start', 'End', 'Freq', 'DPs'] for tsItem in itemsResp.UserObjects: if tsItem: rowdata = [tsItem.Id, tsItem.DateInfo.StartDate.strftime("%Y-%m-%d"), tsItem.DateInfo.EndDate.strftime("%Y-%m-%d"), tsItem.DateInfo.Frequency.name, tsItem.DateRange.ValuesCount] data.append(rowdata) df = pd.DataFrame(data, columns=colnames) print(df, end='\n\n') # To retrieve the full details of a specific timeseries use the GetItem method tsResponse = timeseriesClient.GetItem(testID) if tsResponse.ResponseStatus != dsweb.DSUserObjectResponseStatus.UserObjectSuccess: print('Request failed for timeseries with error ' + tsResponse.ResponseStatus.name + ': ' + tsResponse.ErrorMessage, end='\n\n') elif tsResponse.UserObject != None: # 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 names = ['Id', 'Desc', 'LastModified', 'StartDate', 'EndDate', 'Frequency', 'NoOfValues'] coldata = [tsItem.Id, tsItem.Description, tsItem.LastModified.strftime("%Y-%m-%d"), tsItem.DateInfo.StartDate.strftime("%Y-%m-%d"), tsItem.DateInfo.EndDate.strftime("%Y-%m-%d"), tsItem.DateInfo.Frequency.name, tsItem.DateRange.ValuesCount] df = pd.DataFrame(coldata, index=names) # updating an item takes the same parameters as CreateItem. See how we construct testTs above tsResponse = timeseriesClient.UpdateItem(testTs) # And we can delete the item using the test ID we defined in the CreateItem step delResp = timeseriesClient.DeleteItem(testID) ``` -------------------------------- ### Create and Display Datastream Economics Filter in Python Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Demonstrates how to programmatically create a private Datastream Economics Filter, assign constituents, set a description, and then display its details. It includes error handling for filter creation and identifies invalid constituents. ```python initialConstituents = ['UKEPUPO', 'USEPUPO', 'USEPUEQ', 'IDTVALS', 'IDTVOLS', 'IDTVADS', 'IDTVALP', 'IDTVOLP', 'IDTVADP', 'IDTVAFP', 'BADINST1', 'BADINSTFMT'] myFilter = DSEconomicsFilter() myFilter.FilterId = demoId myFilter.Constituents = initialConstituents myFilter.Description = 'MyTempTestFilter for testing.' print('Creating private filter ' + demoId + '...') filterResp = econFilterClient.CreateFilter(myFilter) if filterResp: if filterResp.ResponseStatus != dsweb.DSFilterResponseStatus.FilterSuccess: print('Request failed for filter ' + filterName + ' with error ' + filterResp.ResponseStatus.name + ': ' + filterResp.ErrorMessage, end='\n\n') elif filterResp.Filter != None: filter = filterResp.Filter names = ['FilterId', 'OwnerId', 'Shared?', 'LastModified', 'Description', 'No. of Constituents'] data = [filter.FilterId, filter.OwnerId, 'Yes' if bool(filter.Shared) else 'No', filter.LastModified.strftime('%Y-%m-%d %H:%M:%S'), filter.Description, filter.ConstituentsCount] df = pd.DataFrame(data, index=names) print(df) print('The filter contains the following constituents:') df = pd.DataFrame(filter.Constituents) print(df, end='\n\n') if filterResp.ItemErrors and len(filterResp.ItemErrors) > 0: print('The service did not add the following items as they are invalid or are not supported:') df = pd.DataFrame(filterResp.ItemErrors) print(df, end='\n\n') ``` -------------------------------- ### Use Datastream Economics Filter for Economic Changes Query in Python Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Illustrates how to utilize a previously created Datastream Economics Filter (e.g., 'MyTempTestFilter') to retrieve economic changes using the `GetEconomicChanges` method. ```python updatesResp = econFilterClient.GetEconomicChanges(None, sequenceId, 'MyTempTestFilter') ``` -------------------------------- ### Retrieve Historical Timeseries Data with DatastreamPy Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Demonstrates how to fetch historical timeseries data for specified tickers and fields over a date range using `ds.get_data`. The data is then indexed with a date range and printed. ```Python history = ds.get_data(tickers = '@AAPL,@MSFT', fields = ['P', 'VO', 'RI'], kind = 1, start = start_date, end = end_date, freq = 'M') history.index = pd.date_range(start_date, end_date, freq = 'M') print (history) ``` -------------------------------- ### Create a Custom Datastream Economic Filter in Python Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md This Python snippet illustrates the process of defining and creating a new custom economic filter with a specified ID (e.g., 'MyTempTestFilter'). It shows how to include valid constituents and also demonstrates the server's behavior when invalid or unsupported series items are included in the filter definition. ```Python # This example demonstrates how to create a new filter. We will define this filter with ID MyTempTestFilter demoId = 'MyTempTestFilter' # Let us create the filter. We'll create it with 10 valid constituents but also include two invalid items, BADINST1 and # BADINSTFMT, to also demonstrate how the server will reject invalid or unsupported items. BADINST1 has valid syntax but is not a # valid series. BADINSTFMT is not the correct economic series format (7 to 9 chars only). ``` -------------------------------- ### DSUserObjectResponseStatus API Status Codes Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Defines the possible status values returned in the DSUserObjectResponseStatus object for user object-related API requests. These codes indicate the success or specific type of failure for operations like creating or retrieving user objects. ```APIDOC DSUserObjectResponseStatus: 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. (e.g. object not present, etc.) ``` -------------------------------- ### DSFilterResponseStatus API Status Codes Source: https://github.com/datastreamapi/datastreampy/blob/main/README.md Defines the possible status values returned in the DSFilterResponseStatus object for filter-related API requests. These codes indicate the success or specific type of failure for operations like creating, modifying, or deleting filters. ```APIDOC DSFilterResponseStatus: FilterSuccess: The request succeeded and the response object's Filter property should contain the (updated) filter (except for DeleteFilter method). FilterPermissions: Users need to be specifically permissioned to create custom filters. This flag is set if you are not currently permissioned. FilterNotPresent: Returned if the requested ID does not exist. FilterFormatError: Returned if your request filter ID is not in the correct format, or if you try and modify a Datastream global filter (ID begins DATASTREAM*). FilterSizeError: Returned if your call to CreateFilter or ModifyFilter contains a list with zero or in excess of the 100K constituents. FilterConstituentsError: Returned if your supplied filter constituent list (on CreateFilter) contains no valid economic series. The filter won't be created. FilterError: The generic error flag. This will be set for any error not specified above. (e.g. Requested filter ID is not present) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.