The Macrobond Chart Server

Introduction

The Macrobond Chart Server delivers images of Macrobond charts in either PNG or SVG format. The server uses the same components as the Macrobond client application and will render exactly the same image over http as you would see in the client application. The server runs as a Windows Service. 

The Macrobond Chart Server is a separately licensed solution.

This document refers to Macrobond Chart Server 1.28.101 or newer. 

Requirements

Minimum requirements: 64-bit versions of Windows 10, Windows Server 2016 or newer, .NET Framework 4.7.2. 

Installation

The Macrobond Chart Server is installed by running a Windows Installer script (MSI). Any previous version of the service will be replaced. The name of the Windows Service is 'Macrobond Chart Rendering Service'. 

The chart server communicates with the Macrobond servers at: https://app1.macrobondfinancial.com, https://app2.macrobondfinancial.com and https://app3.macrobondfinancial.com. 

The executables will be installed in:  

%ProgramFiles%\Macrobond Financial\Chart Server 

Working with Chart Server

Configuration

The file 'appsettings.Production.json' in the program directory contains settings for the service.

Anonymous access

To configure anonymous access set the username and password for the account that the service should use. Replace the value of these elements in the config file under ChartService:
"Username": "USERNAME GOES HERE",
"Password": "PASSWORD GOES HERE",

Anonymous requests are done to http://<server>:<port>/chartserver

Token authenticated access

This feature is currently not used by clients.

To configure token authenticated access set the token server uri by adding the following under ChartService:
"AuthenticationServer": "uri goes here",
Authenticated requests are done to http://<server>:<port>/chartserver2

To enable CORS add a list of uris by adding the following element under ChartService:
"Origins": [ "uri1", "uri2" ],

Host settings

You may want to change the port used for http communication. This is done in the file “hosting.json”. The default setting is:
"Urls": http://*:8088
The service must be restarted for the new settings to be used.

Addresses of Macrobond servers

Addresses of Macrobond backend servers to which the render service connects can be specified under ChartService:

"ChartService":{
 
 "ServerList" : [
  "https://app2.macrobondfinancial.com/app/",
  "https://app1.macrobondfinancial.com/app/",
  "https://app3.macrobondfinancial.com/app/"],

HTTP Proxy server

By default the Chart Server will communicate directly with Macrobond servers. To use explicitly configured server add this under ChartService:

"ChartService":{
 
 "Communication": {
    "ProxyUsage": 1,
    "ProxyServerAddress": "http://address.of.the.proxy:port",
 },

Cache policies

For best performance, series and documents are cached for up to three minutes. In some cases you might want to select a longer or shorter time. The time can be configured with these two settings in the appsettings.Production.json file. The time is specified in seconds. The value should never be set below 5 seconds, because the server will assume that data is cached at least.

Add the following to the ChartService section:

  "CachePolicy": {
    "entity.TimeSeries": 180,
    "Document": 180
  }

Additional series providers

Additional data providers can be configured for the Chart Server using a configuration file located here:
%ProgramData%\Macrobond Financial\Series Providers\config.xml
This is typically used to configure one or more SQL Providers. Here is a sample file that adds one SQL provider:

<?xml version="1.0" encoding="utf-8"?>
<spdc:SeriesProviderDescriptorConfiguration xmlns:spdc="http://schemas.mbnd.eu/2010/SeriesProviderDescriptorConfiguration">
<spdc:Descriptor spdc:Prefix="ppp" spdc:Description="My SQL Database" spdc:TypeName="SqlSeriesProvider" spdc:ConfigPath="c:\path\MySqlConfig.xml" />
</spdc:SeriesProviderDescriptorConfiguration>

The server will read this file when started.

This configuration file uses the same format as the configuration file for the Macrobond application. It can be a good idea to use the config file from a computer where the Macrobond application is configured as desired as a template. You can find the configuration file used by the application here: %LOCALAPPDATA%\Macrobond Financial\Series Providers\config.xml

Logging

Logging generated by Chart Server is controlled by file log4net.config in %programfiles%\Macrobond Financial\Chart Server. By default logs are written to  c:\Windows\ServiceProfiles\LocalService\appdata\local\temp\, which is accessible only from cmd with elevated privileges. Path to the log file can be changed by setting e.g.:

<file value="c:\temp\ChartServer.log" />

Please make sure that the destination folder exists and service account has permission to write to it, then restart the Chart Service.

To enabled debug-level logging please place this file in %programfiles%\Macrobond Financial\Chart Server. Such high level of logging verbosity has negative a impact on performance of the render service and should not be enabled permanently.

 

Operations 

renderpath

The 'renderpath' operation renders a Macrobond document, references by a path, as an image. The request has the following form: 

renderpath?path={path}&presentation={presentation}&width={width}&height={height}&format={format}&dpi={dpi}&bkgcolor={bkgcolor}&useAnimation={useAnimation}&useShowValuesOnHover={useShowValuesOnHover}&defaultAnimationDuration={defaultAnimationDuration}&defaultAnimationDelay={defaultAnimationDelay}
{path}  The path of the document in the Macrobond store. You can find this path by selecting a chart in the File Open/Save dialog of the Macrobond application and then select Copy. This will copy the path as text to the clipboard. 
{presentation}  If a document contains several presentations, this identifies which one that should be rendered. To use the default presentation, specify '00000000-0000-0000-0000-000000000000'.  You can find the presentation identifier by selecting 'Copy' on the context menu of a presentation in the Analysis tree in the Macrobond client application.

 

{width}  The width, in pixels, of the resulting image. This will not be used for Bar charts unless the Width mode is set to Fill for the chart in the Macrobond application. 
{height}  The height, in pixels, of the resulting image. This will not be used for Bar charts where the height is always determined by the chart layout and content. 
{format}  The image format to return. Can be either 'png' or 'svg'. 
{dpi}  The resolution of the image expressed as dots per inch. A value of '96' will result in a scale 1:1. A higher value, such as '120' will render text and line widths larger. 
{useAnimation} If set to true and animations are enabled in the document, line graphs will be animated in SVG images and data popup labels showing the date and value on mouse hover is enabled. Optional. Default is false. Available in version 1.28 and later.
{useShowValuesOnHover} If set to true and this feature is enabled in the document, the user will see a tooltip with the values when hovering over a graph. Please note that the SVG will contain a small JavaScript in this case.

Example:

In order to render the default chart of the following document 
remotepublicfilestore/common/filestore/Thomas O/Sweden/GDP.mbnd 
in the size 800x600, at 96 DPI, as a PNG and keeping any transparent areas, then the URL can look like this: 

http://localhost:8088/chartserver/renderpath?path=macrobondfilestore/macrobond/filestore/What%27s%20new/1.16/Presentation/GDP.mbnd&presentation=00000000-0000-0000-0000-000000000000&width=800&height=600&format=png&dpi=96

render

The 'render' operation renders a Macrobond document posted as XML. The XML format looks like this: 

<r:RenderSpecification xmlns:r="http://schemas.mbnd.eu/2010/renderspec"> 
  <r:ImageType>png</r:ImageType> <!-- Can be png or svg. The default is png. --> 
  <r:XPixels>200</r:XPixels> 
  <r:YPixels>125</r:YPixels> 
  <r:XHimetric>10583</r:XHimetric> 
  <r:YHimetric>6614</r:YHimetric> 
  <r:AbacusDocument> 
    <doc:CalculiDocument xmlns:doc="http://schemas.mbnd.eu/2009/calculidocument"> 
    <!-- The Macrobond document specification --> 
    </doc:CalculiDocument> 
  </r:AbacusDocument> 
</r:RenderSpecification> 

downloadpath

The 'downloadpath' downloads the Macrobond document specification referenced by a path. This specification is an XML document that be used in the 'render' operation. The request has the following form: 

downloadpath?path={path}
{path}  The path of the document in the Macrobond store. You can find this path by selecting a chart in the File Open/Save dialog of the Macrobond application and then select Copy. This will copy the path as text to the clipboard. 

listdirs

The 'listdirs' returns list of folders present in specified directory. This function, combined with the 'listfiles', can be used to implement a web-based chart selector. Returned output is in JSON format. 

listdirs?path={path}
{path}  The path within Macrobond storage. If the path is not specified, the root directories will be listed. 

Sub directories can be listed for directories where HasChildren is true by calling listdirs with the specified Path. 

If HasChildren is not true, then this directory can contain files and the path can be passed to listfiles in order to list the files. 

Example:

To get list of all folders located directly under Company Account call  

http://localhost:8088/chartserver/listdirs?path=macrobond://remotepublicfilestore/common/filestore/ 

Output:

[ 
  { 
    "Name": "Folder A", 
    "Path": "macrobond://remotepublicfilestore/common/filestore/Folder%20A/", 
    "HasChildren": true 
  }, 
  { 
    "Name": "FolderB", 
    "Path": "macrobond://remotepublicfilestore/common/filestore/FolderB/" 
  } 
] 

listfiles

The 'listfiles' returns files located in specified directory. Output is in JSON format. 

listfiles?path={path}&ext=.extension
{path}  The path within Macrobond storage. This is typically obtained from a listdir call. This parameter is obligatory. 
{ext} 

 

Defines what file types should be returned. A list of comma separated values can be specified. This parameter is obligatory. 
{ skipThumbnails}  Defines weather the response should contain base64 encoded thumbnails of the documents. Possible values: true, false. Default: false. 

Both parameters must be specified. 

Example:

To get list of all files located directly under Company Account call  

http://localhost:8088/chartserver/listfiles?path=macrobond://remotepublicfilestore/common/filestore&ext=.mbnd 

Sample output: 

[ 
  { 
    "Name": "121 - Copy", 
    "Path": "macrobond://remotepublicfilestore/common/filestore/121%20-%20Copy.mbnd", 
    "Created": "2019-12-13T17:37:45Z", 
    "LastModified": "2020-11-02T13:26:24Z", 
    "LastSavedBy": "account name_of_person_who_last_modified_the_file", 
    "CreatedBy": "account name of person that created the file", 
    "ThumbnailPng": "base 64 encoded PNG with thumbnail of the chart" 
  }, 
  { 
    "Name": "121", 
    "Path": "macrobond://remotepublicfilestore/common/filestore/121.mbnd", 
    "Created": "2018-03-31T14:35:40Z", 
    "LastModified": "2020-11-05T07:36:31Z", 
    "LastSavedBy": "account name_of_person_who_last_modified_the_file", 
    "CreatedBy": "account name of person that created the file", 
    "Title": "Semiconduct export YoY", 
    "Comment": "Some comment added for the chart in the MB app", 
    "Keywords": "export,prices", 
    "ThumbnailPng": "base 64 encoded PNG with thumbnail of the chart" 
  } 
] 

filemeta

The 'filemeta' returns meta data about a file. Output is in JSON format. 

filemeta?path={path}
{path}  The path within Macrobond storage. This is typically obtained from a listdir call. This parameter is obligatory. 

Example:

To get the file meta data for a file 'Document.mbnd' in the company store

http://localhost:8088/chartserver/filemeta?path=macrobond://macrobondfilestore/macrobond/filestore/What%27s%20new/1.16/Presentation/GDP.mbnd

Sample output: 

{
  "SeriesNames": [
    "usnaac0169",
    "pln"
  ],
  "SeriesPrimaryNames": [
    "usnaac0169",
    "pln"
  ],
  "LastSavedBy": "account name_of_person_who_last_modified_the_file",
  "CreatedBy": "account name of person that created the file",
  "Comment": "some comment",
  "Keywords": "export,prices", 
  "ThumbnailPng": "base 64 encoded PNG with thumbnail of the chart"
}

documentinfo

The 'documentinfo' returns information about the charts in a document. Output is in JSON format. 

documentinfo?path={path}
{path}  The path within Macrobond storage. This is typically obtained from a listdir call. This parameter is obligatory. 

Example:

To get the document info for a file 'Document.mbnd' in the company store

http://localhost:8088/chartserver/documentinfo?path=macrobond://macrobondfilestore/macrobond/filestore/What%27s%20new/1.16/Presentation/GDP.mbnd

 

Sample output: 

{
  "PrimaryPresentationId": "d65755be-17bb-4c83-a261-bab073f65308",
  "Presentations": [
    {
      "Id": "24f01fe1-3a3b-4f54-874c-57b2385e08c9",
      "Name": "Time chart"
    },
    {
     "Id": "d65755be-17bb-4c83-a261-bab073f65308",
     "IsPrimary": true,
     "Name": "CPI"
    },
    {
      "Id": "e3fb5084-e1a5-4afc-91dc-910358973692",
     "Name": "Core CPI"
    }
  ]
}

searchfiles

The 'searchfiles' returns list of files containing given search-string, located in specified directory and its direct and indirect sub-folders. Output is in JSON format. 

searchfiles?path={path}&query={query}&ext={ext}&fields={fields}&skipThumbnails=true
{path}  The path within Macrobond storage. This is typically obtained from a listdir call. This parameter is obligatory. 
{ext} 

 

Defines what file types should be returned. A list of comma separated values can be specified. This parameter is obligatory. 
{query} Text-search phrase. Only files containing it will be returned. Pass % symbol to match any files. This parameter is obligatory.
{fields} List of comma-separated fields to be matched. Allowed values: FileName, Title, Keywords, Regions, Comment, SeriesNames, SeriesPrimaryNames.
{ skipThumbnails}  Defines weather the response should contain base64 encoded thumbnails of the documents. Possible values: true, false. Default: false

the fields, skipThumbnails parameters are optional.

Example:

To get list of all files located directly under Company Account call  

http://localhost:8088/chartserver/searchfiles?path=macrobond://remotepublicfilestore/common/filestore/&skipThumbnails=true&ext=.mbnd&query=%

binderinfo

The 'binderinfo' returns list of presentation pages contained in a given presentation document. Output is in JSON format. 

binderinfo?path={path}

{path}  The path within Macrobond storage. This is typically obtained from a listdir call. This parameter is obligatory. 

Example:

To get list of pages contained in given presentation document:

http://localhost:8088/chartserver/binderinfo?path=macrobond://macrobondfilestore/macrobond/filestore/What%27s%20new/1.16/Presentation/Sweden%20summary.mbndp

 

Sample output: 

{
  "Items": [
    {
      "ItemType": 1,
      "Id": "56d5a65c002c8a7ec9a4d7fd48fca6f2d4692c9386f5",
      "Name": "Macro",
      "Items": null
    },
    {
      "ItemType": 1,
      "Id": "56d5a89b0039aa1f83c2747447038931220f8196a7da",
      "Name": "Financial",
      "Items": null
    }
  ]
}

Please note that presentation documents might have items nested on multiple levels. More complex example:

http://localhost:8088/chartserver/binderinfo?path=macrobond://macrobondfilestore/macrobond/filestore/What%27s%20new/1.16/Presentation/Sweden%20summary%20with%20nesting.mbndp

{
  "Items": [
    {
      "ItemType": 0,
      "Id": "67f3c83c02b421d29e144236495781782cc460b4e1ec",
      "Name": "Folder",
      "Items": [
        {
          "ItemType": 1,
          "Id": "56d5a65c002c8a7ec9a4d7fd48fca6f2d4692c9386f5",
          "Name": "Macro I",
          "Items": null
        },
        {
          "ItemType": 1,
          "Id": "67f3c85202b5314435a9f82648d9bfa79489e235ec85",
          "Name": "Macro II",
          "Items": null
        }
      ]
    },
    {
      "ItemType": 0,
      "Id": "67f3c87302b65aa2d5c214a448cfb1211bc03c44ec35",
      "Name": "Financial",
      "Items": [
        {
          "ItemType": 1,
          "Id": "67f3c87802b727325d52e61e4d3aab6d55b6af7c63ab",
          "Name": "Page 1",
          "Items": null
        },
        {
          "ItemType": 1,
          "Id": "67f3c88202b95ad44f165b754fc88ed307498499141e",
          "Name": "Page 2",
          "Items": null
        },
        {
          "ItemType": 1,
          "Id": "67f3c87802b818463236c40a48f893c1ed0158baddd1",
          "Name": "Page 3",
          "Items": null
        }
      ]
    }
  ]
}

renderbinderpage

Returns rendering of a single page from presentation document in SVG or PNG format.

renderbinderpage?width={width}&height={height}&format={format}&dpi={dpi}&path={path}&pageId={pageId}

{path}  The path within Macrobond storage. This is typically obtained from a listdir call. This parameter is obligatory. 
{width}  The width, in pixels, of the resulting image. This will not be used for Bar charts unless the Width mode is set to Fill for the chart in the Macrobond application. Obligatory.
{height}  The height, in pixels, of the resulting image. This will not be used for Bar charts where the height is always determined by the chart layout and content. Obligatory.
{format}  The image format to return. Can be either 'png' or 'svg'.  Obligatory.
{dpi} The resolution of the image expressed as dots per inch. A value of '96' will result in a scale 1:1. A higher value, such as '120' will render text and line widths larger. Obligatory.
{pageId} Identifier of page to render, taken from the output of binderinfo. Obligatory.

Example:

 

http://localhost:8088/chartserver/renderbinderpage?width=887&height=502&format=svg&dpi=96&path=macrobond://macrobondfilestore/macrobond/filestore/What%27s%20new/1.16/Presentation/Sweden%20summary.mbndp&pageId=56d5a65c002c8a7ec9a4d7fd48fca6f2d4692c9386f5

 

 

APIs/Feeds/Connectors

Connect Macrobond to your data

You can use external time series data in Macrobond application. Such solutions can be found below.

SQL Database Connector

You can read time series and metadata from your own SQL database in Macrobond. For more information see The Macrobond SQL Database Connector.

We also host a SQL database which you can connect to as a demonstration of our SQL Database Connector. To obtain access, please contact your Account Manager.

Web API Series Provider

Solution similar to SQL Connector but communicating via HTTP and JSON with a server that implements a Web API providing access to your time series. Specification of the Web API can be found on the page describing The Macrobond client Web API Series Provider.

Bloomberg Connector

We have a connector for Bloomberg Terminal which converts '=BDH' queries and allows you use the data in our application. For more information see The Macrobond Bloomberg Connector.

FactSet Data Provider

We also have connector for FactSet data which converts "=FDS" expression from Excel and URL from the Formula API Request Builder. For more information see The Macrobond FactSet Data Provider.

Note you can also upload external data from your own code to Macrobond and with code, download Macrobond data. For these solutions see sections about Data Scientist tools (i.e., Python, R) and Office package.

Data Scientist tools

Here you can find list of our Commonly used metadata. Metadata attributes can be used in the below solutions.

EViews

Add-in enables you to upload and download data from and to EViews. For more information see The Macrobond EViews add-in.

Matlab

This API enables you to upload and download data from and to Matlab. For more information see The Macrobond API for Matlab.

Python

Here you can find special Macrobond package which can be used in Python environment for uploading and downloading data. Package is designed to run alongside Macrobond application on Windows. For more information see The Macrobond Data API for Python (Python wrapper).

For more information about our old Python package see The Macrobond API for Python.

R

Here you can find special Macrobond package which can be used in R environment for uploading and downloading data. Package is designed to run alongside Macrobond application on Windows. For more information see The Macrobond API for R.

Feed solutions

Data Web API feed

This data feed is communicating via HTTPS to REST API exposed by Macrobond’s servers. It allows clients to programmatically access time series and metadata from our database. For more information see The Macrobond Data web API feed.

FTP/SFTP data feed

This data feed allows automated integration between our data and your own solution. For more information see The Macrobond FTP/SFTP data feed.

Databricks feed

This data feed pushes Macrobond and third-party time series into your Databricks. For more information see Databricks feed.

Snowflake data feed

This data feed pushes Macrobond and third-party time series into your Snowflake tables and views for direct consumption within your Snowflake environment. For more information see Snowflake data feed.

Office add-ins

Excel/Power Point/Word/Publisher

We have integrated Office package into our application and created separate add-in which allows you to use Macrobond data in Excel or our Presentation documents in Power Point. You do not need to install anything - add-in will install itself together with main application. For more information about it see Using Macrobond data in Excel.

Render Solutions

Chart Server

Best solution if you want to programmatically generate Macrobond charts with up-to-date information e.g. for publishing, web pages or mobile applications. For more information see The Macrobond Chart Server.

Web Publish

This is a feature inside our main application. It allows you to quickly publish charts - static or dynamic. For more information see Web Publish.

The Macrobond Data Web API feed

Overview

The Macrobond Data Web API feed gives access to the Macrobond database of time series and meta data. It is a REST Web API that uses JSON as the data format. OAuth2 is used for authentication and authorization.

The Macrobond Data Web API feed is a separately licensed solution.

This documentation refers to version 1 of the API and is subject to change.

References

Interactive documentation https://api.macrobondfinancial.com/swagger
Documentation of metadata https://help.macrobond.com/technical-information/common-metadata/
API URL https://api.macrobondfinancial.com
OpenAPI definition https://api.macrobondfinancial.com/swagger/v1/swagger.json
OAuth2 authentication https://apiauth.macrobondfinancial.com/mbauth
OAuth2 token endpoint https://apiauth.macrobondfinancial.com/mbauth/connect/token

Data+ license

With Data+ the only way to get the credentials for API's is by having the MB app installed in the same machine as the Python environment. See Technical information for the link.

Note that keyring or https://api.macrobondfinancial.com/swagger/index.html will only work with Web Api license credentials, it won't work if you have Data+.

Introduction

Entities and metadata

The Macrobond database contains objects called entities. Each entity has a set of metadata that describes the entity. There are different types of entities. The most common type is the time series. In
addition to the metadata, a time series also has a vector of values with corresponding dates. The Help page commonly used metadata also contains a useful introduction.

Each entity has a unique name. A name starts with one or more letters and can be followed by letters, digits and underscore. An entity can have more than one name. It can have a primary name and a list
of aliases. Any of these names can be used to reference the entity in, for example, a download operation.

The names do typically not have any special meaning. You should not infer any information from the name. For example, even though many names of time series begin with what looks like a country
code, like 'us', you should not use this to determine the country. Instead, you should use the metadata attribute called Region.

The metadata provides information about entities but can also be used as filters when search in the database.

Time series

A time series is an entity with a list of values and dates. The most important metadata of a time series are:

Frequency The highest frequency is daily and the lowest annual.
DayMask Used with daily series to tell what days of the week the series covers. It is a
bitmask where but 1 is Sunday, 2 is Monday, 3 is Tuesday etc.
FullDescription The title of the time series.
DisplayUnit A text that gives the unit of the series.
Currency The currency of the values
LastModifiedTimeStamp The time when this entity was last modified. This includes changes to metadata as well as values. This can be used in some API calls (series/fetchseries and series/fetchvintageseries) to conditionally retrieve data only if it has changed.

Note, this isn't available for calculated series because they are calculated on the fly when requested.

There is a date for each value in the time series. This date represents the period of the value and not when the value was sampled. For example, 2010-04-01 in a quarterly series represents 2010 Q2.

All dates indicated by the frequency are not always included. For example, for daily series January 1 might be missing since this was a public holiday.

A value might also be null, which indicates a missing value. Unlike the case when a date is missing, a missing value indicates that a value was expected for this date, but it is, for some reason, not available.

The API

The API is a REST based Web API over https that uses JSON as the data format. You can find detailed information about the parameters and data structures on the interactive documentation page.

Communication is made over https.

An Open API specification describes the API in a machine-readable format that can be used to generate stubs for most programming languages.

Authentication and authorization

The Macrobond Data Web API uses OAuth2 for authentication and authorization.

You use the Client credential grant flow to request an access token based on you client_id and client_secret. You need to specify a set scopes matching the API end-points you plan to use. In most
cases this includes 'macrobond_web_api.read_mb' to read time series and 'macrobond_web_api.search_mb' to be to search for series.

You can find information about the required scopes for each method in the documentation like this:
The access token is passed as a Bearer token in the Authorization http header in the subsequent API calls. The lifetime of a token is short (30-60 minutes). When you receive http status code 401 in the response from an API call, you need to request a new token and attempt the API call again. There are libraries for most programming platforms that helps with implementing OAuth2.

Note, the client_id and client_secrets are confidential information that must be stored in a safe way using best practices. It must not be shared.

Using the interactive reference documentation

The interactive reference documentation documents the arguments and data formats of the API methods.

It also allows you to test the methods directly on the web page. For this to work, you need to authorize first using the Authorize button in the top right corner. Fill in client_id and client_secrets and check the first scope called 'macrobond_web_api.read_mb'.

Once authorized you can test the methods. When the token expires, you will receive status 401 and you have to log out and log in again to get a new token.

Please note that some methods that return large amount of data can be slow for the web browser to handle.

Python wrapper

We have created The Macrobond Data API for Python (Python wrapper). The purpose of the Python API is to make the Data Web API easier to use in Python. For example, you do not need to bother with authentication, HTTP, JSON etc. and you get time series directly as Pandas series.

For documentation see The Macrobond Data API for Python (Python wrapper).
Find our guide and examples in Jupyter notebooks on Github.

Examples and use cases

The examples do not include examples of all API methods. See the reference documentation for a complete list.

Note that we have created The Macrobond Data API for Python (Python wrapper) to make Data Web API easier to use in Python. For documentation see The Macrobond Data API for Python (Python wrapper). Find our guide and examples in Jupyter notebooks on Github.

Example of retrieving a time series in Python

This example uses the Python package requests_oauthlib that can be installed using 'pip install requests_oauthlib'. It retrieves one series called 'usgdp' and prints the retrieved JSON data.

from oauthlib.oauth2 import BackendApplicationClient
from requests_oauthlib import OAuth2Session
import json

# In a real-world case you should not include the credentials directly in the source code
client_id = user.test'
client_secret = 'somepassword'

token_url='https://apiauth.macrobondfinancial.com/mbauth/connect/token'
client = BackendApplicationClient(client_id=client_id, scope="macrobond_web_api.read_mb")
# To include access to methods for searching include an additional scope like
# scope="macrobond_web_api.read_mb macrobond_web_api.search_mb ")
mbapi = OAuth2Session(client=client)

# Helper method that will request new access token if required

def downloadMbApi(request):
  url = "https://api.macrobondfinancial.com/v1/" + request
  # This is typically the first time when we do not yet have a token
  if not mbapi.authorized:
    mbapi.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
  r = mbapi.get(url)
  if r.status_code == 401:
    # If authorization failed, it is likely that the token has 
    expired. Get a new one and try again.
    mbapi.fetch_token(token_url=token_url, client_id=client_id, client_secret=client_secret)
    r = mbapi.get(url)
  r.raise_for_status()
  return r.content

# Use the helper method to access the API

d = downloadMbApi("series/fetchseries?n=usgdp")

jdata = json.loads(d)

print(jdata)

Loading time series and entities

GET series/fetchseries

Retrieve one or more time series.

The URL should not be longer than 2000 characters. Example:

Retrieve two time series.
series/fetchseries?n=usgdp&n=degdp
The result will be a list of series in the same order as requested.

POST series/fetchseries

Retrieve one or more time series.

The data is a list of series names to retrieve. Each name can optionally have a time stamp. If the series has not been modified since that time, the series will not be returned but instead there will be a status code indicating that it was not modified. The timestamp specified is typically the metadata LastModifiedTimeStamp from a previous response.

If you are retrieving many series, you might want to batch them into groups of 200 at a time for best efficiency. If your framework supports asynchronous requests, you might want to make two requests in parallel. Example:

To request two series, where one has a conditional timestamp.

[
  {
    "name": "usgdp",
    "ifModifiedSince": "2021-02-28T20:40:18.424Z"
  }
  {
    "name": "segdp"
  }
]

GET series/fetchentities

Retrieve one or more entities.

The URL should not be longer than 2000 characters. The result will be a list of sets of metadata in the same order as in the request. Example:

Get the metadata for a Release entity. The name of the Release was found as part of the metadata of the time series 'usgdp'. The metadata of the Release contains useful information such as the timestamp of the next expected release of new data.
series/fetchentities?n=rel_usbeana

GET seriestree/getleafseries

To get list of series from a particular location in the tree the path must be entered as found in the application, where each node is separated by a slash. Also, special characters should be encoded using RFC 2396. Example:

Retrieve series from Concept & Category/Prices/National Sources/Consumer Prices/Core CPI/Total/SA
seriestree/getleafseries?path=Concept%20%26%20Category%2FPrices%2FNational%20Sources%2FConsumer%20Prices%2FCore%20CPI%2FTotal%2FSA

Revision history series

For many series all changes to the values of the series are stored and they can be obtained as historical versions, or vintages, of the series. A change of an existing value or addition of a new value is regarded as a change of the series. With this information you can get older vintages of series, get point-in-time information when values where changed, get unrevised data or a specific revision. In the API there are several methods that allows you to obtain different views of this data.

GET series/getrevisioninfo

This method is used to find information related to revision history for one or more series:

  • if revision history is maintained by Macrobond for this series
  • how long history of revisions a series has
  • a list of timestamps when changes were made of the values of the series

GET series/fetchvintageseries

Get the series with the values it had at some point in time.

The metadata RevisionTimestamp will contain the timestamp when the revision was recorded. Example:

Get the version of the series 'usgdp' with the values it had 1 January 2020.
series/fetchvintageseries?t=2020-01-01T00%3A00%3A00.100Z&getTimesOfChange=true&n=usgdp

GET series/fetchallvintageseries

Get all historical revision stored for a series.

You can optionally include a timestamp as a parameter to retrieve the series conditionally. This timestamp is typically the value of the metadata LastModifiedTimeStamp obtained from the previous request.

Note, this can be a large amount of data and the interactive documentation page can struggle to show the result.

Searching for time series and entities

Search for time series and other entities by using a filter based on metadata and optional text searching. The most common case is to search for time series and this is the default of no other entity types are specified. By default, the result contains the metadata of the found entities, but if you do not need this you can specify not to include it which will make the result smaller and faster to load.

Generate search code in Macrobond main app

When you input a query into search field in Macrobond’s Search tab, you can then generate a ready-to-use code for search in Web API Call:

GET search/entities

Example:

A common and powerful use case for searching is to use the RegionKey attribute. This attribute defines classifications of data that is available across regions. By inspecting the series 'usgdp', we can see that this series has RegionKey=gdp_total.

To search for series that are the corresponding series in the regions us, gb and se, you can use the following query:
search/entities?noMetaData=true&RegionKey=gdp_total&Region=us&Region=gb&Region=se

Side note: in the interactive documentation, you specify the filter part for this example like this:

{
  "RegionKey": "gdp_total",
  "Region": ["us", "gb","se"]
}

You can search for all series of this type for all regions:
search/entities?RegionKey=gdp_total
By prefixing a condition with '!' you can exclude matching series. This query will return the GDP series identified by Macrobond, but excludes those where we only have annual data:
search/entities?RegionKey=gdp_total&!Frequency=annual

POST search/entities

This method offers the same search capabilities as the 'GET search/entities' described above, but adds the option of specifying several sets of filters. These filters will be linked together based on the entity type. Example:

This query will look for all entities of type Company with a specific classification. It will then find all entities of type Security associated with those companies that also have the attribute CompanyKey=main_equity. Finally, a match will be made with all TimeSeries, the default type, associated with those securities and that have DataType=close.

The result will be all series with the closing price of the equity of companies of the specific classification.

{
  "filters":
  [
    {
      "entityTypes": ["Company"],
      "mustHaveValues": { "IcbClassification":"icb_2713" }
    },
    {
      "entityTypes": ["Security"],
      "mustHaveValues": { "CompanyKey":"main_equity" }
    },
    {
      "mustHaveValues": { "DataType":"close" }
    }
  ]
}

Creating and updating in-house series

You can create and update a limited set of in-house series using the API just as you can do using the Macrobond application.

To be able to use the API methods related to uploading series, you must request the scope macrobond_web_api.write_ih as part of the authentication.

GET seriestree/getseriesstoragelocations

Each in-house series is identified with a prefix like “ih:mb:priv:” followed by a name that starts with a lower case letter followed by lower case letter, digits and underscore. The prefix identifies the storage location. You can list the storage locations and the corresponding prefixes by calling the API method seriestree/getseriesstoragelocations.
The storage location dictates who can access the series. The most common storage locations are "priv", for private series that can only be access using the account that uploads them, and "com" that can be accessed by the whole company.

POST series/uploadseries

To create or update a series, you call series/uploadseries and post a JSON structure containing values and metadata. At a minimum you need to specify the metadata attributes PrimName, Description, Region, IHCategory and Frequency.
For more information about metadata, see Entities and metadata.

You can either specify a list of one timestamp per value, or specify the StartDate metadata attribute. For daily series, the DayMask attribute must also be included.

Here is an example of a payload that creates or updates a private series called "test".

{
   "values": [12.23, 45.56],
   "dates": ["2021-09-23", "2021-10-21"],
   "metadata": {
      "PrimName": "ih:mb:priv:test",
      "Description": "A test series",
      "Region": "us",
      "IHCategory": "Test",
      "Frequency": "monthly"
   }
}

The dates must be in ascending order.

If your series contains one observation for each per period, you can specify the StartDate instead of the array of dates.

{
   "values": [12.23, 45.56],
   "metadata": {
      "PrimName": "ih:mb:priv:test",
      "Description": "A test series",
      "Region": "us",
      "IHCategory": "Test",
      "Frequency": "monthly"
      "StartDate": "2021-09-23"
   }
}

The attribute IHCategory can be set to any text. This will be used in the Macrobond application user interface when organizing the series into groups.

GET seriestree/getusedinhousecategories

You can get a list of previously used values of IHCategory by calling seriestree/getusedinhousecategories.

DELETE series/deleteseries

In-house series can be deleted with a call to series/deleteseries.

The Macrobond client Web API Series Provider

Introduction

The Macrobond client Web API Series Provider series provider allows the Macrobond application to use any web service that implements the HTTP and JSON based web API as described below. It offers similar features to the SQL Database Connector, but uses a predefined API contract instead of SQL to retrieve the data. It also offers the option of enabling creation and deletion of series as well-structured lists of series in the data tree with indentations, emphasized rows and groups of series.

Information flows directly between Macrobond application and your Web API Series Provider, it is not processed by or stored on Macrobond servers.

Technical details

The API uses JSON in responses and POST requests.

In POST requests, you should set Content-Type: application/json; charset=utf-8.

In all responses you should set the Cache-Control header. In most cases you want to set this to Cache-Control: no-cache, private.

Sample server

There is a Sample server implemented in C#/.NET Core at GitHub.

Implementation

The API must implement the loadseries and getcapabilities methods. The other methods are optional and will only be called if the server reports that it supports those features via the getcapabilities method.

Method Capability Comment
loadseries Load one or more series given the names of the series
getcapabilties Return a list of capabilities implemented by the server
searchseries search Search for series using keywords entered by the user
loadtree browse Return a tree structure that the user can browse to navigate the database
listseries browse List series in a location of the database tree
createseries editSeries Create or update a series
removeseries editSeries Remove a series
loadmeta meta Load just the metadata of a series
loadvintage revisions Load a vintage series
loadvintagetimestamps revisions Load the vintages timestamps of a series
loadrelease revisions+revisionsRelease Load a release series
loadcompletehistory revisions+revisionsCompleteHistory Loads all vintages of a series

For communication, both http and https are supported. For authentication, basic http authentication is supported. In this case, https is strongly recommended.

There are some requirements on the database imposed by the Macrobond application:

  • Each time series must have a unique identifier that can be used for retrieving the time series values and metadata. Any lower-case characters except double quote, colon, and any other white space than ordinary space (ASCII 32) is allowed, but it is best if the identifier begins with a-z and continues with a-z, 0-9 or underscore since such identifiers can be used unquoted in the Macrobond application.
  • A time series cannot start before year 1600 or end after year 2499.
  • The time series frequencies are limited to: day, week, month, quarter, 4 months, half year and year.

There is a swagger file for the API here: https://schemas.macrobond.com/webclientapi.swagger.json

Working with the Web API Series Provider

Configuration

To define what database server to talk to, you define a simple XML file like below:

<?xml version="1.0" encoding="utf-8"?>
<web:WebApiSeriesProvider xmlns:web="http://schemas.mbnd.eu/2019/webapiseriesprovider">
  <web:Host>http://ourdbserver:5555</web:Host>
</web:WebApiSeriesProvider>

In the Macrobond application, in the Settings dialog (Configuration > Settings > My series (for MB pre-1.28: Edit > Settings > My series)) you specify the path to this configuration file:

 

During development and troubleshooting, it can be helpful to enable the log console.

This will cause a log window to be displayed as soon as there is any communication via the Web API. The log contains information about what queries that are sent, what the response is and some diagnostic messages that can be helpful for troubleshooting the service.

Metadata

Each series in the server must contain meta data in the form of a dictionary of string+object. The meta data gives different information about how the series should be handled by the application. Every property in a Meta data dictionary is case sensitive, and they should be written with pascal case. Some meta data properties are optional but there are some that are crucial to make a series work.

The property PrimName is required as a unique identifier of the series. Letters of the identifier must be lower case.

It is recommended to specify the frequency using the Frequency attribute. This can have one of the values annual, semiannual, quadmonthly, quarterly, bimonthly, monthly, weekly or daily.

The StartDate is required when no list of dates is provided for the series. In most cases you also want to include a Description attribute too.

The Class attribute influences how automatic frequency conversion is done and is useful to set. Here are a list of possible values: Class attribute info

The Region metadata specifies what region a data series refers to. For countries, the values is the ISO 3166 code of the region. See this list for possible values: Region attribute info

The Currencymetadata attribute is the ISO 4217 currency code. This is used for automatic currency conversion in the Macrobond application. See this list for possible values: Currency attribute info

The IHInfofree-text attributes allows for providing verbose description of the time series. It can be accessed from within the Macrobond application in the Time series information view.

The StoresRevisionHistory is set to true to indicate that a series supports revision history. See below for more details.

For more information about metadata see Commonly used metadata.

Commands

getcapabilities

Tells the Macrobond application whether this server support browse, search and edit capabilities.

This method must be implemented by the server.

Response

One or more of these boolean values:

  • browse
  • search
  • editSeries
  • allowMultipleSeriesPerRequest
  • meta
  • revisions
  • revisionsRelease
  • revisionsCompleteHistory

If browse is false or not present, no tree will be shown in the application. This should be true if loadtree and listseries have been implemented.

If search is false or not present, no search bar will be available in the application. This should be true if searchseries has been implemented.

If editSeries is false or not present, the option to create or remove series will not be available to the user. Set to true if the createseries and removeseries have been implemented.

If allowMultipleSeriesPerRequest is set to false, then there will never be more than one series requested in loadseries. This is less efficient, but can simplify the implementation in some scenarios. By default, this is set to true.

If meta is set to true, then loadmeta might be called by the application to retrieve the just the metadata of a series in some situations. This is useful since there is less data to return than the complete series data.

If revisions is set to true, the provider must implement loadvintage and loadvintagedates. Series that has revisions are expected to include the metadata StoresRevisionHistory, FirstRevisionTimeStamp and LastRevisionTimeStamp. The last two are set only if there actually are any revisions for the series. This enables series vintages in the application.

If revisions and revisionsRelease are  true, the provider must implement loadrelease. This enables series releases in the application.

If revisions and revisionsCompleteHistoryare  true, the provider must implement completehistory. This enables the "Show revision history" feature in the application.

Example

URL:

/getcapabilities

Response:

{
"browse": true,
"search": true
}

loadseries

Returns a list of series from the server by name.

This method must be implemented by the server.

Parameters

  • n : Array of strings. The identifier of a series. The parameter can be included several times in order to request several series simultaneously. (It is possible to turn off the option to send multiple series in one request. See allowMultipleSeriesPerRequest in getcapabilities above.)

Response

A list of responses corresponding to each series requested in the same order as in the request. Each element in the list is either a data element with

  • values
  • metaData

or an error element with an error text explaining why the series could not be loaded. You must not include both data and error elements for a series.

There are three options for specifying the calendar:

  • Specify the frequency without list of dates. For daily frequencies you may also specify the DayMask attribute if you do not want the default of Monday-Friday. In this case the calendar will be created from Frequency, StartDate and DayMask.
  • Specify the frequency attribute and a list of dates. For daily frequencies you may also specify the DayMask attribute if you do not want the default of Monday-Friday. In this case the calendar will be created from Frequency, StartDate and DayMask and values will be made available for the periods corresponding to the specified dates. Any 'gaps' in the set of dates will be gaps in the resulting calendar. The StartDate metadata must reference the first observation.
  • Include a list of dates, but do not specify the frequency. The application will guess the frequency based on the provided set of observations. It will pick the lowest frequency to cover the specified dates without duplicates. The StartDate metadata must reference the first observation. This option is not allowed if if meta is returned from getcapabilities.

The DayMask metadata is used for daily series. It is a bitmask as an integer where Sunday is the bit with value 1. A mask for Monday-Friday is thus 62. A string can be passed instead of a bitmask and should then have the weekdays in English separated with space. For instance Monday Tuesday Wednesday Thursday Friday. Such a string will be converted to the corresponding bitmask.

Example

URL:

/loadseries?n=name1&n=name2&n=name3

Response:

[
    {
        "data": {
            "metaData": {
                "Description": "0-7 Years",
                "Frequency": "annual",
                "PrimName": "name1",
                "StartDate": "1990-01-01T00:00:00"
            },
            "values": [
                600.0,
                570.0,
                630.0,
                450.0,
                200.0
            ]
        }
    },
    {
        "data": {
            "dates": [
                "1990-01-01T00:00:00",
                "1990-02-01T00:00:00",
                "1990-04-01T00:00:00",
                "1990-05-01T00:00:00"
            ],
            "metaData": {
                "Description": "8-12 Years",
                "Frequency": "monthly",
                "PrimName": "name2"
            },
            "values": [
                10,
                11,
                12,
                13
            ]
        }
    },
    {
        "error": "Series name3 not found"
    }
]

loadmeta

Returns a list of series metadata from the server by name.

This method is optional to implemented by the server. It is called only if meta is returned from getcapabilities. The application will call this method instead of loadseries in some cases when it needs only the metadata and not the full series data. This can be useful if it is a lot of work for the server to retrieve the full series data.

Parameters

  • n : Array of strings. The identifier of a series. The parameter can be included several times in order to request several series simultaneously. (It is possible to turn off the option to send multiple series in one request. See allowMultipleSeriesPerRequest in getcapabilities above.)

Response

A list of responses corresponding to each series requested in the same order as in the request. Each element in the list is either a data element with

  • metaData

or an error element with an error text explaining why the series could not be loaded. You must not include both data and error elements for a series.

One difference compared to loadseries is that the metadata fields Frequency and StartDate must be specified. For daily series, it is recommended to also set DayMask. If not set Monday-Friday will be assumed.

Example

URL:

/loadmeta?n=name1&n=name2&n=name3

Response:

[
    {
        "data": {
            "metaData": {
                "Description": "0-7 Years",
                "Frequency": "annual",
                "PrimName": "name1",
                "StartDate": "1990-01-01T00:00:00"
            }
        }
    },
    {
        "data": {
            "metaData": {
                "Description": "8-12 Years",
                "Frequency": "monthly",
                "PrimName": "name2",
                "StartDate": "1997-01-01T00:00:00"
            }
        }
    },
    {
        "error": "Series name3 not found"
    }
]

searchseries

Gets a list of meta data of series from given string.

Parameters

  • query: The text entered by the user

Response

The response is a list of metadata sets. The metadata must contain Description and PrimName.

The Macrobond application can show some additional attributes as columns in the list of a search result. These are optional. Frequency, StartDate, EndDate, Currency, DisplayUnit, Region, LastValue, PreviousLastValue, Class

Example

URL:

/searchseries?query=US

Response:

[
    {
        "Description": "US Main Regressions",
        "Frequency": "annual",
        "PrimName": "series1"
    },
    {
        "Description": "US Main Regressions",
        "PrimName": "series2"
    }
]

loadtree

Returns a tree or subtree from the database. If the tree is large or costly to load from the database, it can be split up into sub trees that will be loaded when the user expands them.

Parameter

  • reference: Optional. If specified, load the referenced sub tree. If not specified, load the root of the tree.

Response

The returned data forms a nested tree which is used to create a database tree in the application UI.

Each node in the tree can contain either Children, ChildrenReference or SeriesReference.

A Children element contains a nested list of the tree.

A ChildrenReference contains a deferred nested list of the tree. A request for the branch will be sent as a loadtree request to the server and the specified reference will be included in the query.

The leaves of the tree contain an element called SeriesReference. When the user clicks on such a branch in the tree a listseries request, including the specified reference, is sent to the server to retrieve the list of series to present to the user.

Example

URLs:

/loadtree
/loadtree?reference=treeNodeReference

Response:

[
    {
        "Description": "First folder",
        "SeriesReference": "ref1"
    },
    {
        "Children": [
            {
                "Description": "First sub folder",
                "SeriesReference": "ref2"
            },
            {
                "ChildrenReference": "sub2",
                "Description": "Second sub folder"
            }
        ],
        "Description": "Second folder"
    }
]

listseries

Lists all series for a leaf in the data tree.

The application will call this method when the user selects a leaf in the data tree.

Parameters

  • reference: The reference from the leaf in the data tree.

Response

The following elements are required:

  • groups
  • entityMeta
  • names

The list of series will be presented in the Macrobond application when a leaf in the data tree is selected.

Aspects

The result can optionally contain 'aspects' will be presented as tabs in the UI. For example 'NSA, Monthly' in the image above.

The presented list below the aspect tabs is the same for all tabs but refers to different series.

If there is only one aspect, then aspects can omitted.

For every aspect there must be as many metadata collections in each row of series. If there are two aspects then every row of series must contain two collections, if there are three aspects then every row must contain three collections etc.

If there are no aspects, the entityMeta element contains only one collection.

The response is a list of metadata sets. The metadata must contain Description and PrimName.

The Macrobond application can show some additional attributes as columns in the list of a search result. These are optional. FrequencyStartDateEndDateCurrencyDisplayUnitRegionLastValuePreviousLastValueClass

Groups

The list may be divided into groups. If there is only one group, then the name property of that group can be omitted.

Formatting

The entries in the list can be indented by specifying an indentation level.

Entries can be emphasized like 'Food & Beverages' in the image above.

Additional space can be added above an entry, like for 'Food' in the image, but specifying spaceAbove as true.

Example

URL:

/listseries?reference=serieslistreference

Response:

{
    "aspects": [
        {
            "description": "Tooltip of tab a",
            "name": "Tab 1"
        },
        {
            "description": "Tooltip of tab b",
            "name": "Tab 2"
        }
    ],
    "groups": [
        {
            "name": "The first group",
            "series": [
                {
                    "description": "Variable 1",
                    "emphasized": false,
                    "entityMeta": [
                        {
                            "Description": "Total, Goods",
                            "PrimName": "series1a",
                            "Region": "se"
                        },
                        {
                            "Description": "Total, Goods",
                            "PrimName": "series1b",
                            "Region": "se"
                        }
                    ],
                    "indentation": 3,
                    "spaceAbove": false
                }
            ]
        }
    ]
}

createseries

Creates a new in-house series.

Parameters

  • lastModified : Timestamp. When replacing an existing series, this value reflects the LastModifiedTimeStamp metadata, if present, of the series edited by the user. It will not be included when creating a new series. It is included when overwriting an existing series unless the forceReplace parameter is true.
  • forceReplace : Boolean. If this parameter is included and set to true, then the existing series should be overwritten. If the series does not already exist, HTTP status 404 Not Found should be returned.
Response

Success (200): Must return new lastModified time for the series.

Not Found (404): If lastModified has a value or forceReplace is true but the series could not be found.

Conflict (409): If the lastModified parameter does not match the actual timestamp of the stored series. This means that someone else might be editing the same series.

Example

URL:

/createseries

Post data:

{
    "dates": [
        "2016-01-01T00:00:00",
        "2017-01-01T00:00:00",
        "2018-01-01T00:00:00",
        "2019-01-01T00:00:00"
    ],
    "metaData": {
        "Description": "Total",
        "Frequency": "monthly",
        "LastModifiedTimeStamp": "2019-12-04T00:00:00",
        "PrimName": "myseries1",
        "StartDate": "2016-01-01T00:00:00"
    },
    "values": [767161, 782911, 866119, 929586]
}

Response:

2019-12-04T00:00:00

removeseries

Removes a series.

Parameters

  • name : The name of the series to be removed

Response

Success (200): The series was removed.

Not Found (404): Series with given name parameter could not be found.

Example

URL:

/removeseries?name=myseries1

loadvintage

Load a specific vintage of a series as it looked at the specified time.

The returned series is expected to have the metadata RevisionSeriesType=vintage and RevisionTimeStamp set to the time of the vintage, if it is known. RevisionLabel can optionally be set if there is a descriptive text of the vintage.

Please note that the actual vintage of the series, as specified in the RevisionTimeStamp metadata should be at or before the requested time.

When a time before the first known vintage is requested, there are two scenarios:

  1. For some series, the complete revision history might not be known and there is a version of the series as it looked before revisions were collected. In this case this original series is returned without any RevisionTimeStamp metadata.
  2. If all revision of the series is known, an empty series is returned without the RevisionTimeStamp metadata.

Parameters

  • n: The name of the series
  • timestamp: The time of the vintage. This will be in a ISO 8601 format with a time zone offset or Z for UTC.

Response

Success (200): The vintage series is returned. This is the same format as the data element in the return from the loadseries.

Not Found (404): Series with given name could not be found.

Example

URL:

/loadvintage?n=myseries1&timestamp=2022-06-27T14%3A00%3A00Z

Response:

{
    "dates": [
        "2022-01-01T00:00:00",
        "2022-02-01T00:00:00",
        "2022-04-01T00:00:00",
        "2022-05-01T00:00:00"
    ],
    "metaData": {
        "Description": "8-12 Years",
        "Frequency": "monthly",
        "PrimName": "myseries1",
        "RevisionSeriesType": "vintage",
        "RevisionTimeStamp": "2022-05-15T10%3A00%3A00Z"
    },
    "values": [
        10,
        11,
        12,
        13
    ]
}

loadvintagetimestamps

Load the vintage timestamps available for a series. This is used by the application to populate lists in the GUI where the user can pick a vintage.

Parameters

  • n: The name of the series

Response

Success (200): The list of timestamps + optional label name is returned.

Not Found (404): Series with given name could not be found.

Example

URL:

/loadvintagetimestamps?n=myseries1

Response:

[
  {"timeStamp": "2022-05-13T10%3A00%3A00Z", "label": "May 2022 first release" },
  {"timeStamp": "2022-05-15T10%3A00%3A00Z" }
]

loadrelease

Load a specific release of a series. Typically release 0 corresponds to the first value of each observation, release 1 is the first revision of each value and so on.

The returned series is expected to have the metadata RevisionSeriesType=nth and RevisionSeriesNth set to the ordinal of the revision. RevisionLabel can optionally be set if there is a descriptive text of the release.

Parameters

  • n: The name of the series
  • nthrelease: The ordinal of the release. It can be 0 or greater.

Response

Success (200): The series is returned. This is the same format as the data element in the return from the loadseries.

Not Found (404): Series with given name could not be found.

Example

URL:

/loadrelease?n=myseries1&nthrelease=1

Response:

{
  "values": [
    10, 11, 12, 13],
  "dates": [
    "2022-01-01T00:00:00", "2022-02-01T00:00:00", "2022-04-01T00:00:00", "2022-05-01T00:00:00"],
  "metaData": {
    "Description": "8-12 Years",
    "PrimName": "myseries1",
    "Frequency": "monthly",
    "RevisionSeriesType": "nth",
    "RevisionSeriesNth": 1
    }
}

loadcompletehistory

Load all vintages of a series. This is used by the Macrobond application to show a complete view of all historical vintages of a series.

The returned series are expected to have the metadata RevisionSeriesType=vintage and RevisionTimeStamp set to the time of the vintage. The first vintage may omit the RevisionTimeStamp if it is not known. RevisionLabel can optionally be set if there is a descriptive text of the vintage.

Parameters

  • n: The name of the series

Response

Success (200): The complete history is returned.

Not Found (404): Series with given name could not be found.

Example

URL:

/loadcompletehistory?n=myseries1

Response:

[
    {
        "dates": [
            "2022-01-01T00:00:00",
            "2022-02-01T00:00:00",
            "2022-04-01T00:00:00"
        ],
        "metaData": {
            "Description": "8-12 Years",
            "Frequency": "monthly",
            "PrimName": "myseries1",
            "RevisionSeriesType": "vintage"
        },
        "values": [
            10,
            11,
            12
        ]
    },
    {
        "dates": [
            "2022-01-01T00:00:00",
            "2022-02-01T00:00:00",
            "2022-04-01T00:00:00",
            "2022-05-01T00:00:00"
        ],
        "metaData": {
            "Description": "8-12 Years",
            "Frequency": "monthly",
            "PrimName": "myseries1",
            "RevisionLabel": "May 2022 first release",
            "RevisionSeriesType": "vintage",
            "RevisionTimeStamp": "2022-05-13T10%3A00%3A00Z"
        },
        "values": [
            10,
            11,
            12,
            13.5
        ]
    },
    {
        "dates": [
            "2022-01-01T00:00:00",
            "2022-02-01T00:00:00",
            "2022-04-01T00:00:00",
            "2022-05-01T00:00:00"
        ],
        "metaData": {
            "Description": "8-12 Years",
            "Frequency": "monthly",
            "PrimName": "myseries1",
            "RevisionSeriesType": "vintage",
            "RevisionTimeStamp": "2022-05-15T10%3A00%3A00Z"
        },
        "values": [
            10,
            11,
            12,
            13.7
        ]
    }
]

Web Publish

Overview

The Web publish feature makes publishing charts a simple and quick process. The feature is designed to provide URL addresses for charts that you can post on blogs, social media, websites or a content management system (CMS).

How to use Web publish?

From Analytics

Save chart on Personal/Department/Company account. When it is open in Analytics tab go to (in upper menu) File > Web publish.

See here pre-1.29 version view

 

This will open the following window where you can change several settings such as size, format and whether the chart should be static or dynamic. You can also add a comment to the chart.

See here pre-1.29 version view

 

From Web publish tab

In left bottom corner press ‘Publish document’ button, then select file. This will open new window same as above.

Publishing types

Two types of images are available for publishing:

  • Static image of a chart – published image will be a snapshot of the chart, meaning the image won’t be updated when data is updated from the source.
  • Dynamic image of a chart – published image will be updated with the latest data from the source. This update will happen automatically.

Web publish tab

In the Web publish tab, you will find all charts added from the file menu.

Here, you can easily access and manage all charts ready for web publishing. You can view them in your preferred way:

  • Flat view – simple list of all charts,
  • Tree view – charts are grouped according to the account in which the original documents are stored.

You can also add charts from here by clicking on 'Publish document.'

After choosing which document to publish, you can copy the chart either as a HTML or a URL link. If you choose the latter, and the chart is dynamic, you can send the link as an email and the chart will be updated whenever the link is opened.

NOTE: The capacity for published images is limited. You can store up to 3 dynamic and 10 static documents per license. This limit can be increased as an add-on service.

Technical notes

  • You can modify the URL of dynamic publications in order to render the chart in a different size. For a URL that ends with …5f85f2c8e7e/chart.png you can change the URL to …5f85f2c8e7e/900x300/chart.png in order to get an image of size 900x300 pixels.
  • Published charts that have not been viewed by anyone for more than 2 years will automatically be removed.
  • Dynamic publications do not work with in-house data or data that comes from local data sources such as SQL servers or Bloomberg.

The Macrobond API for Python

Introduction

Macrobond offers an API that can be used in Python for Windows. You can download time series (values, dates, and metadata) and upload your own series to the in-house database which can then be used in the Macrobond application and optionally shared with others.

This article refers to an older version of our Python connector. For information on the new version, please see The Macrobond Data API for Python (Python wrapper).

Requirements

The Macrobond API has been tested with Python 2.7.11 and 3.9.5 which can be downloaded here as well as Anaconda 4.3.1 with Python 3.6 that can be found here. This is a COM API and requires the pywin32 extension found here. We have tested with pywin32 b301.

If you are running the 64-bit version of Python, you need to use the 64-bit version of Macrobond. The 32-bit version of Python will work with 64-bit Macrobond too.

Note that due to an issue with pywin32 b220 you must not use the "makepy" or win32com.client.gencache.EnsureModule features of pywin32 on the type of the Macrobond API.

This API can be used only with Legacy (without searching and revision history functions) or Data+ license.

Getting started

To successfully use the API, you might want to learn more about the Commonly used metadata.

We also recommend installing special package with Macrobond constants. For more information about it see Class with constants.

Working with Python API

About time series

A time series is represented by the ISeries interface. A time series consists of a vector of values, a calendar, and a set of metadata.

The vector of values consists of floating-point values. A missing value is represented by a NaN. To test if a value is a NaN in Python, you use the method math.isnan(value). To represent a NaN you can use float('nan') or math.nan (Python 3.5 and later). Note! You must never use these constants to compare if a value is NaN; always use math.isnan(value) to test if a value is NaN.

A missing value typically means that a value was expected, but it is missing for some reason. When you do a unified series request, you have the option of specifying what method, if any, that should be used to fill in missing values.

The calendar is exposed as lists of dates as well as a couple of methods to go between index in the list of values and a date. Dates are represented as timestamps with time zone UTC. Each time series has a frequency and a start date. Daily series also have information about what weekdays that are covered. In addition to this, certain dates can be skipped.  This is mostly used for daily series when there is a holiday or other day when the market is closed. It is not common, but you may find skipped dates in series of other frequencies too. For instance, some Chinese monthly data is not reported for February and this month is then skipped.

About downloading series

Series are represented by objects that implement the ISeries interface. This interface has properties and methods to retrieve values, dates and metadata.

You can select from two modes when downloading series:

  • Download raw data. All available data will be made available without any conversion. You do this by calling FetchOneSeries or FetchSeries with one or more series names (strings).
  • Download unified data. You can specify frequency, currency, date range, missing value, and frequency conversion methods. When more than one series is downloaded, they will all have the same calendar. This means that they will have equal length, the same frequency and that a specific index in the vector or values corresponds to the same point in time for all the series. This type of download is made by creating a request object by calling CreateUnifiedSeriesRequest().

Interfaces

The documentation of the interfaces uses a 'c' style syntax which includes the type of information for parameters and return values.

The special type VARIANT is used when several data types are accepted which is then explained in the text.

[] is used to denote a list. For instance, ISeries[] is a list of ISeries objects.

In the examples below a class called constants defines all the constants used in the example. For more information about it see Class with constants paragraph.

IConnection

All interaction with the Macrobond starts with an instance of the Connection object which is access through the IConnection interface. You create an instance of the object like this:

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")

The interface contains the following methods and properties:

IDatabase Database This property returns a reference to the database interface.
Close() Call this method if you want to free all resources used by the Macrobond API. Opening and closing sessions can be slow, so it is usually not a good idea to open and close them for each request.
int[] Version Returns an array of three values for the version of the installed API. For example, for the version 1.25.3 it will return [1, 25, 3].

Time series - codes

Download one series

This will download the entire time series usgdp without any transformations.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database
s = d.FetchOneSeries("usgdp")

values = s.Values
print(values)

Download one series and scale values

We store values in their original form, in single units, i.e., 19699465000000. While our main app transforms these values automatically on Time table/Time chart, Python download them in original form, without any formatting. You can scale them by yourself with below code. For scaling with pandas see Download one series, create data frame and scale values.

import win32com.client

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database
s = d.FetchOneSeries("usgdp")

values = s.Values
values2 = tuple(val/1000000000000 for val in values)
print(values2)

Download one series wrapped in ratio (#PerCapita)

Use the #PerCapita ratio to get a series of the US GDP per capita. For more information about this functionality see Ratios.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("#PerCapita(usgdp)")

values = s.Values 
print(values)

Download several series

This will download the entire time series usgdp and uscpi without any transformations. It is faster to download several series in one call rather than one by one.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

listOfSeries = d.FetchSeries(["usgdp", "uscpi"])
seriesUsgdp = listOfSeries[0]
seriesUscpi = listOfSeries[1]

values = seriesUsgdp.Values
print(values)

Download several series, transform them to a common length and calendar

By default, the highest frequency of the series and the union on the ranges will be used. For more examples, see the documentation about the ISeriesRequest.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp")
r.AddSeries("uscpi")

listOfSeries = d.FetchSeries(r)
seriesUsgdp = listOfSeries[0]
seriesUscpi = listOfSeries[1]

values = seriesUsgdp.Values
print(values)

Download series and set start year

This will download two series and convert them to the higher frequency. The data range is set to start year 2020 and continue until the last observation that has data in both series. You can also set relative date like "-5y" or "-10" (observations). For more information see ISeriesRequest.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp")
r.AddSeries("uscpi")
r.StartDate = "2020-01-01"

listOfSeries = d.FetchSeries(r)
seriesUsgdp = listOfSeries[0]
seriesUscpi = listOfSeries[1]

values = seriesUsgdp.Values
print(values)

Download series and set common start Date and end Date

This example uses our constants package. For more information about it see here.

For all available 'CalendarDate' methods see CalendarDateMode.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import CalendarDateMode as cd

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp")
r.AddSeries("uscpi")

#set the start to the first point where data is available in all series 
r.StartDateMode = cd.ALL_SERIES
#set the end to the last point where data is available in all series 
r.EndDateMode = cd.ALL_SERIES

listOfSeries = d.FetchSeries(r)
seriesUsgdp = listOfSeries[0]
seriesUscpi = listOfSeries[1]

values = seriesUsgdp.Values
print(values)

Download several series, change frequency, and set missing value method

This example uses our constants package. For more information about it see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'MissingValue' methods see SeriesMissingValueMethod.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesMissingValueMethod as mv

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp").MissingValueMethod = mv.NONE
r.AddSeries("uscpi").MissingValueMethod = mv.NONE
r.Frequency = f.MONTHLY

listOfSeries = d.FetchSeries(r)
seriesUsgdp = listOfSeries[0]
seriesUscpi = listOfSeries[1]

values = seriesUsgdp.Values
print(values)

Download series and convert it with 'to higher frequency' method

This example uses our constants package. For more information about it see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'ToHigher' methods see SeriesToHigherFrequencyMethod.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesToHigherFrequencyMethod as th

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp").ToHigherFrequencyMethod = th.LINEAR_INTERPOLATION
r.AddSeries("uscpi").ToHigherFrequencyMethod = th.LINEAR_INTERPOLATION
r.Frequency = f.WEEKLY

listOfSeries = d.FetchSeries(r)
seriesUsgdp = listOfSeries[0]
seriesUscpi = listOfSeries[1]

values = seriesUsgdp.Values
print(values)

Download series, convert frequency with 'to lower frequency' method and set one currency

This example uses our constants package. For more information about it see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'ToLower' methods see SeriesToLowerFrequencyMethod.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesToLowerFrequencyMethod as tl

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp").ToLowerFrequencyMethod = tl.LAST
r.AddSeries("chgdp").ToLowerFrequencyMethod = tl.LAST
r.Frequency = f.ANNUAL
r.Currency = "CHF"

listOfSeries = d.FetchSeries(r)
seriesUsgdp = listOfSeries[0]
seriesChgdp = listOfSeries[1]

values = seriesUsgdp.Values
print(values)

Download series, convert frequency and fill in partial periods

This example uses our constants package. For more information about it see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'PartialPeriods' methods see SeriesPartialPeriodsMethod.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesPartialPeriodsMethod as pp

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("uscpi").PartialPeriodsMethod = pp.REPEAT_LAST
r.Frequency = f.QUARTERLY

listOfSeries = d.FetchSeries(r)
seriesUscpi = listOfSeries[0]

values = seriesUscpi.Values
print(values)

Download series, and set calendar mode

This example uses our constants package. For more information about it see here.

For all available 'CalendarMode' methods see CalendarMergeMode.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import CalendarMergeMode as cm

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usfcst3898")
r.AddSeries("eur")

#all holidays will always be included as missing values instead of being skipped in the calendar 
r.CalendarMergeMode = cm.FULL_CALENDAR

listOfSeries = d.FetchSeries(r)
seriesUs = listOfSeries[0]
seriesEur = listOfSeries[1]

values = seriesUs.Values
print(values)

Get values and dates

This will download the time series usgdp and the list of values as well as a list of the dates corresponding to each value.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("usgdp")
values = s.Values
dates = s.DatesAtStartOfPeriod

print(values)
print(dates)

Create and upload a monthly series

This creates a monthly time series. Since just one data is specified, this will be the start date of the series and the rest of the dates will be implicitly calculated based on the frequency. Series will be stored as Account in-house. This example uses our constants package. For more information about it see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'Weekdays' methods see SeriesWeekdays.

import win32com.client
import datetime

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesWeekdays as wk

m = d.CreateEmptyMetadata()
startDate = datetime.datetime(1990, 1, 1, tzinfo=datetime.timezone.utc)
values = [12.2, 12.7, 12.8, 13.0]
s = d.CreateSeriesObject("ih:mb:priv:s1", "My forecast", "us", "Forecasts", f.MONTHLY, wk.MONDAY_TO_FRIDAY, startDate, values, m)

d.UploadOneOrMoreSeries(s)

To see series in Macrobond main app after uploading please refresh Account in-house tree in Macrobond with rounded arrow icon.

Create and upload a daily series, specify each date

This will create a daily time series. In this case we have chosen to specify the date for each observation. Please note that the 5th and 6th of January 1980 are Saturday, Sunday, and will not be included in the series since it is set to use Monday-Friday. The 7th is no included in the list of dates, so this date will be skipped in the calendar. Series will be stored as Account in-house. This example uses constants package. For more information see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'Weekdays' methods see SeriesWeekdays.

import win32com.client
import datetime

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesWeekdays as wk

m = d.CreateEmptyMetadata()
dates = [datetime.datetime(1980, 1, 2, tzinfo=datetime.timezone.utc),
         datetime.datetime(1980, 1, 3, tzinfo=datetime.timezone.utc),
         datetime.datetime(1980, 1, 4, tzinfo=datetime.timezone.utc),
         datetime.datetime(1980, 1, 8, tzinfo=datetime.timezone.utc)]
values = [12.2, 12.7, 12.8, 13.0]
s = d.CreateSeriesObject("ih:mb:priv:s2", "My forecast", "us", "Forecasts", f.DAILY, wk.MONDAY_TO_FRIDAY, dates, values, m)

d.UploadOneOrMoreSeries(s)

To see series in Macrobond main app after uploading please refresh Account in-house tree in Macrobond with rounded arrow icon.

Create and upload a daily series with currency metadata

Series will be stored as Account in-house. This example uses constants package. For more information see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'Weekdays' methods see SeriesWeekdays.

import win32com.client
import datetime

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesWeekdays as wk

m = d.CreateEmptyMetadata()
m.AddValue("Currency", "sek")
startDate = datetime.datetime(1980, 1, 1, tzinfo=datetime.timezone.utc)
values = [12.2, 12.7, 12.8, 13.0]
s = d.CreateSeriesObject("ih:mb:priv:s1", "My forecast", "us", "Forecasts", f.DAILY, wk.MONDAY_TO_FRIDAY, startDate, values, m)

d.UploadOneOrMoreSeries(s)

To see series in Macrobond main app after uploading please refresh Account in-house tree in Macrobond with rounded arrow icon.

Create and upload a monthly series with flagged forecast

Series will be stored as Account in-house. This example uses our constants package. For more information about it see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'Weekdays' methods see SeriesWeekdays.

import win32com.client
import datetime

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesWeekdays as wk

m = d.CreateEmptyMetadata()
startDate = datetime.datetime(2022, 11, 1, tzinfo=datetime.timezone.utc)
values = [12.2, 12.7, 12.8, 13.0]
forecastFlags = [False, False, True, True]
s = d.CreateSeriesObjectWithForecastFlags("ih:mb:priv:s1", "My forecast", "us", "Forecasts", f.MONTHLY, wk.MONDAY_TO_FRIDAY, startDate, values, forecastFlags, m)

d.UploadOneOrMoreSeries(s)

To see series in Macrobond main app after uploading please refresh Account in-house tree in Macrobond with rounded arrow icon.

Delete a series

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

d.DeleteOneOrMoreSeries("ih:mb:priv:s1")

IDatabase

This interface allows you to interact with the Macrobond database.

ISeries FetchOneSeries(string seriesName) Download one series from the database.
ISeries[] FetchSeries(VARIANT seriesNames) Download one or more series from the database. The parameter can be a string, a vector of series names or an object created by CreateUnifiedSeriesRequest(). The result is a vector of series in the same order as requested.
IEntity FetchOneEntity(string entityName) Download an entity, such as a Release.
IEntity[] FetchEntities(VARIANT entityNames) Download one or more entities from the database. The parameter can be a string or a list of entity names. The result is a vector of entities in the same order as requested.
ISeriesRequest CreateUnifiedSeriesRequest() Create a request of one or more series where the resulting time series will be converted to a common length and calendar. You can specify frequency, currency, date range, missing value, and frequency conversion methods
ISeries CreateSeriesObject(string name, string description, string region, string category, SeriesFrequency frequency, SeriesWeekdays dayMask, object startDateOrDates, object values, IMetadata metadata) Create a series object that can be uploaded to the server using the UploadOneOrMoreSeries method. The startDateOrDates can either be just one start date or one date for each value. It is recommended to use timezone UTC for these dates.
The values should be an array of numbers.
The region is a value of the Region metadata which is based on the 2 letter ISO for countries. See list here.
The metadata parameter is optional.
The name should be of the form 'ih:storage:id', where storage is 'priv', 'dept' or 'com' corresponding to the private, department and company storages. Id should must be a unique identifier per storage.
ISeries CreateSeriesObjectWithForecastFlags(string name, string description, string region, string category, SeriesFrequency frequency, SeriesWeekdays dayMask, object startDateOrDates, object values, object forecastFlags, IMetadata metadata) Create a series object that can be uploaded to the server using the UploadOneOrMoreSeries method. The startDateOrDates can either be just one start date or one date for each value. It is recommended to use timezone UTC for these dates.
The values should be an array of numbers.
The forecastFlags should be an array of boolean values where true means that the corresponding value is a forecast.
The region is a value of the Region metadata which is based on the 2 letter ISO for countries. See list here.
The metadata parameter is optional.
The name should be of the form 'ih:storage:id', where storage is 'priv', 'dept' or 'com' corresponding to the private, department and company storages. Id should must be a unique identifier per storage.
UploadOneOrMoreSeries(VARIANT series) Upload one or more series created by the CreateSeriesObject method. The parameter can be a single series or a list of series. It is more efficient to upload more series at once than one by one.
DeleteOneOrMoreSeries(VARIANT nameOrNames) Delete one or more series. The parameter can be a single series name or a list of names. It is more efficient to delete more than one series at once than one by one.
IMetadata CreateEmptyMetadata() Create an empty set of metadata. The content can be changed until it is used in a series.
IMetadata CreateDerivedMetadata(IMetadata metadata) Create a set of metadata derived from another set. The content can be changed until it is used in a series.
IMetadataInformation GetMetadataInformation(string name) Get information about a type of metadata.
ISearchQuery CreateSearchQuery() Create a search query object. Set properties on this object and pass it to the Search function in order to search for series and other entities.
(Requires Data+ license.)
ISearchResult Search(ISearchQuery[] queries) Execute a search for series and other entities. See specification of ISearchQuery for details.
(Requires Data+ license.)
ISeriesWithRevisions FetchOneSeriesWithRevisions(string name) Download one revision history for one series.

(Requires Data+ license.)

ISeriesWithRevisions[] FetchSeriesWithRevisions(VARIANT seriesNames) Download one or more series from the database. The parameter can be a string or a vector of series names. The result is a vector of revision history objects in the same order as requested.

(Requires Data+ license.)

ISeries

This interface represents a Macrobond time series.

string Name The name of the series.
bool IsError If True, then the series request resulted in an error and the ErrorMessage property contains an error message. If there is an error, only these two properties are valid.
string ErrorMessage Contains an error message if IsError is True.
string Title The title of the series.
IMetadata Metadata Metadata information for the time series.
double[] Values A list of all values in the time series.
date[] DatesAtStartOfPeriod A list of dates. There is one date for the start of the period for each value in Values.
date[] DatesAtEndOfPeriod A list of dates. There is one date for the end of the period for each value in Values.
bool[] ForecastFlags A list flags where a value is True if the corresponding value in Values is a forecast.
date StartDate The date of the first observation of the time series.
date EndDate The date of the last observation of the time series.
SeriesFrequency Frequency The series frequency.
SeriesWeekdays Weekdays A bit field of weekdays to use for daily time series.
double GetValueAtDate(date d) Get the value at or preceding a specific date.
int GetIndexAtDate(date d) Get the zero-based index of the value at or preceding the specified date in the Value list.
double TypicalObservationCountPerYear The typical number of observations per year based on the frequency of the series.
IMetadata[] ValuesMetadata Returns a list of metadata for each value in Values. The list will be empty if there is no metadata for any value. If the list is not empty, if will be an object of type IMetadata or None if no metadata is available for that specific value.

ISeriesRequest

Use this interface to set up a request of unified series. You create objects with this interface by calling IDatabase.CreateUnifiedSeriesRequest(). Then you configure the object and pass it as a parameter to IDatabase.FetchSeries().

ISeriesExpression
AddSeries(string name)
Add a series to the list of series to request. You can optionally use the returned interface to do further configurations, such as methods for missing value and frequency conversion.
ISeriesExpression
[] AddedSeries
A list of the added series.
SeriesFrequency Frequency The frequency that all series will be converted to. The default value is ‘Highest’, which means that all series will be converted to the same frequency as the series with the highest frequency.
CalendarMergeMode
CalendarMergeMode
Determines how to handle points in time that are not available in one or more series. The default value is ‘AvailibleInAny’
SeriesWeekdays Weekdays This determines what days of the week that are used when the resulting frequency is Daily and the CalendarMergeMode is ‘FullCalendar’.
string Currency The currency code based on the three letter IS 4217 codes that will be used to convert any series expressed in currency units. The default is an empty string, which means that no currency conversion will be done. There is a list of the supported currencies on a Currencies List web page.
When converting to another currency the method for each series is Automatic. Use the main app to see what it is for particular series.
CalendarDateMode StartDateMode Determines if the automatic start of the series is at the first point when there is data in any series or the first point where there is data in all series. The default is ‘DataInAnySeries’. This setting is not used when the StartDate property is set to an absolute point in time.
VARIANT StartDate This specifies the start date used for all the series in the request. The value can be empty, a specific date or a string representing a point in time as described below. If it is empty or a relative reference, the StartDateMode will be used to determine the start.
CalendarDateMode EndDateMode Determines if the automatic end of the series is at the last point when there is data in any series or the last point where there is data in all series. The default is ‘DataInAnySeries’. This setting is not used when the EndDate property is set to an absolute point in time.
VARIANT EndDate This specifies the end date used for all the series in the request. The value can be empty, a specific date or a string representing a point in time as described below. If it is empty or a relative reference, the EndDateMode will be used to determine the end.

For the StartDate and EndDate properties, you can specify a string representing a point in time. This can either be an absolute reference on the form 'yyyy', 'yyyy-mm' or 'yyyy-mm-dd' or a reference relative the last observation of the series based on these examples:

-50 Fifty observations before the last available observation.
+40 Forty observations after the last available observation.
-2y Two years before the last available observation.
-1q One quarter before the last available observation.
-4m Four months before the last available observation.
-3w Three weeks before the last available observation.
-5d Five days before the last available observation.

ISeriesExpression

Use this interface to set properties for a series requested by calling ISeriesRequest.AddSeries().

string Name The name of the series
SeriesMissingValueMethod
MissingValueMethod
The method to use when filling in any missing values in this series. The default is ‘Auto’.
SeriesToLowerFrequencyMethod
ToLowerFrequencyMethod
The method to use when converting this series to a lower frequency. The default is ‘Auto’.
SeriesToHigherFrequencyMethod
ToHigherFrequencyMethod
The method to use when converting this series to a higher frequency. The default is ‘Auto’.
SeriesPartialPeriodsMethod
PartialPeriodsMethod
The method to use for partial periods at the ends of the series when converting to a lower frequency. The default is None.
datetime Vintage Optional. A timestamp of the desired vintage of the series. You can inspect the RevisionTimeStamp attribute in the result to see the resulting vintage times stamp.

Metadata - codes

See Commonly used metadata.

How to see series metadata?

List metadata available for a series.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("usgdp")
m = s.Metadata.ListNames()

print(m)

How to see specific metadata?

To see other metadata replace text in last line's quotation marks:

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("usgdp")
m = s.Metadata

metadata = m.GetFirstValue("LastModifiedTimeStamp")

print(metadata)

Get information about the metadata attribute

All possible commands can be found under IMetadataInformation.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

#get information about the TimeDim metadata attribute
m = d.GetMetadataInformation("TimeDim")
v = m.ListAllValues()

for timedim in v:
    print(timedim.Value) #list of versions of this metadata

Get series title

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("usgdp")
t = s.Title

print(t)

Get the presentation text for a region code

This will get information about the metadata type called 'Region' and then get the presentation text for the region called 'us'. The result will be the string 'United States'.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

m = d.GetMetadataInformation("Region")
description = m.GetValuePresentationText("us")

print(description)

Get currency metadata from a series

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("segdp")
m = s.Metadata

currencyCode = m.GetFirstValue("Currency")

print(currencyCode)

Get a list of all currencies

This will get information about the metadata type called 'Currency' and list all available currency codes.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

m = d.GetMetadataInformation("Currency")
v = m.ListAllValues()

for currency in v:
    print(currency.Value)

Get name of release

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("usgdp")
releaseName = s.Metadata.GetFirstValue("Release")

print(releaseName)

Get the next release time

The NextReleaseEventTime attribute contains information about the next scheduled release of updated series. The date might be missing if no release date is known.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("usgdp")

releaseName = s.Metadata.GetFirstValue("Release")
if (releaseName is not None):
 r = d.FetchOneEntity(releaseName)
 nextReleaseTime = r.Metadata.GetFirstValue("NextReleaseEventTime")

print(nextReleaseTime)

Get next publication date

Some series have 'NextReleaseEventTime' metadata but some don't. Then it's the best to use 'CalendarUrl' metadata connected to Release metadata.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("usgdp")

releaseName = s.Metadata.GetFirstValue("Release")
if (releaseName is not None):
 r = d.FetchOneEntity(releaseName)
 calendarUrl = r.Metadata.GetFirstValue("CalendarUrl")

print(calendarUrl)

How to know if series is discontinued?

EntityState = 0 means series is active
EntityState = 4 means series is discontinued

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

r = d.CreateUnifiedSeriesRequest()

r.AddSeries("usgdp")
r.AddSeries("arbopa5021")
for series in d.FetchSeries(r):
    print(series.Metadata.GetFirstValue("EntityState"))

How to handle double region?

Some series have two regions and they do not display properly when you ask for Region metadata.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("eea_8_579")
m = s.Metadata

cc = m.GetValues("Region")
print(cc) #get shortenings for double regions i.e., ('ch', 'city_ch_lug')

regions = d.GetMetadataInformation("Region")
print(regions.GetValuePresentationText(cc)) #get full names for double regions i.e., Switzerland, Lugano

IMetadata

This interface represents a set of metadata for a time series or entity.

Metadata is represented by a name and a value. The type of the value can be a string, a boolean, an integer or a date. An examples of a metadata names are 'Region' and 'Currency.' Some metadata can have multiple values, like Region, but others, Currency, can have only one value.

VARIANT GetFirstValue(string name) Get the first metadata value with the specified name.
VARIANT[] GetValues(string name) Get a list of all the values for a specified metadata name.
VARIANT[,] ListNames() Get a list of all the metadata specified together with a description for each name.
bool IsReadonly Indicating whether new values can be added or hidden in this instance. Typically, only newly created instances of the metadata objects can be edited and only until they have been used in a series.
AddValue(string name, VARIANT value) Add a value to the metadata instance. The value can be a single value or a list of values.
HideValue(string name) Hide a value inherited from a parent metadata collection.

You can find more information on this page: Commonly used metadata.

Region The region code based on the two letter ISO 3166 codes. There is a list of the supported regions on a Regions List web page.
Currency The currency code based on the three letter ISO 4217 codes. There is a list of the supported currencies on a Currencies List web page.
When converting to another currency the method for each series is Automatic. Use the main app to see what it is for particular series.
DisplayUnit The unit of the time series.
Class The class is a string with one of the values Stock or Flow. This determines how the automatic frequency conversion in Macrobond works. If the value is Flow, the data will be aggregated when converted to a lower frequency and distributed over the period when converted to a higher frequency.
ForecastCutoffDate All observations at this date and later will flagged as forecasts. The date must not be before the start or after the end of the series.
MaturityDate Some analyses, such as the Yield curve analysis, can use this information to automatically configure the maturity length. If you set this value, you should also set RateMethod but not set the MaturityDays value.
MaturityDays This value is a positive integer that some analyses, such as the Yield curve analysis, can use this information to automatically configure the maturity length. If you set this value, you should also set RateMethod but not set the MaturityDate value. 1 week is 7 days, 1 month is 30 days and one year is 360 days.
RateMethod This value should be either simple or effective that some analyses, such as the Yield curve analysis, can use this information for automatically configuration. If you set this value, you should also set one of the MaturityDate or MaturityLength values.
IHCategory This is a text describing the category for an in-house series. This can be set when uploading series. It will be used together with Region to group series in the Macrobond application when browsing the in-house database.
IHInfo This is an optional comment for an in-house series. This can be set when uploading series and can be seen in the Series information report in the Macrobond application.
LastModifiedTimeStamp The time when this entity was last modified. For time series, this includes changes in either values or metadata.
LastReleaseEventTime This value can be available for entities of type Release. It contains the time of the previous scheduled update.
NextReleaseEventTime This value can be available for entities of type Release. It contains the time of the next scheduled update.

IMetadataInformation

Use this interface to get information about a type of metadata.

string Name The name of the metadata type
string Description A description of the metadata type.
string Comment A comment about the metadata type.
bool UsesValueList If True, then this type of metadata uses a list of possible values and only values from that list can be used. The list can be obtained from ListAllValues. Information about a specific value can be found by calling GetValueInformation().
MetadataValueType ValueType Get the datatype of the values for this type of metadata.
bool CanHaveMultipleValues If True, then a metadata collection can have several values of this type.
bool IsDatabaseEntity If True, then this value corresponds to an entity in the database that can be retrieved by IDatabase.FetchOneEntity().
string GetValuePresentationText(VARIANT value) Format a value as a presentable text.
IMetadataValueInformation GetValueInformation(VARIANT value) Get information about a metadata value. This information is only available for metadata types that uses value lists
IMetadataValueInformation[] ListAllValues() Get a list of all possible values for a metadata type that uses a value list.
bool CanListValues If True, then the possible values can be listed using the ListAllValues function.

IMetadataValueInformation

Use this interface to get information about a value of metadata.

VARIANT Value The value of the metadata
string Description The description of the value.
string Comment A comment about the value.

IEntity

This interface represents a Macrobond entity. There are many types of entities in the Macrobond database. Examples are Source, Release, Company and Security. Time series are also entities.

The reason you might want to download an entity, is to obtain some metadata.

string Name The name of the entity.
bool IsError If True, then the entity request resulted in an error and the ErrorMessage property contains an error message. If there is an error, only these two properties are valid.
string ErrorMessage Contains an error message if IsError is True.
string Title The title of the entity.
IMetadata Metadata Metadata information for the entity.

Concept/Region key - codes

Some of our series are connected with each other through metadata called Region Key. If you know it, you can find series for other countries/regions. In main-app you can see those data sets under Concept & Region data tree.

Get 'concept' from a series

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("uscpi")

#get the 'concept' this series is associated with
cpiKey = s.Metadata.GetFirstValue("RegionKey")
if cpiKey == None:
   print("No RegionKey defined")
else:
   print(cpiKey)

Get 'concept' description

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("uscpi")

#get the 'concept' this series is associated with
cpiKey = s.Metadata.GetFirstValue("RegionKey")
if cpiKey == None:
   print("No RegionKey defined")
else:
   print(cpiKey)
   
#get description of 'concept'
keyMetaInfo = d.GetMetadataInformation("RegionKey")
  
print(keyMetaInfo.GetValuePresentationText(cpiKey))

Search - codes

You can pass more than one search filter to IDatabase.Search(filters). In this case the filters have to use different entity types and searches will be nested so that the result of the previous filter will be used as a condition in the subsequent filter linked by the entity type.

We return up to ~6000 entities in the search result. Note that it is possible that particular series is not among the first 6000 returned.

Generate search code in Macrobond main app

When you input a query into search field in Macrobond’s Search tab, you can then generate a ready-to-use code for search in Python:

Search for 'concept' based on a series, download whole data set

This method requires a Data+ license.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeries("ted_ar_ahw")
cpiKey = s.Metadata.GetFirstValue("RegionKey") #get the 'concept' of a series

query = d.CreateSearchQuery()
query.SetEntityTypeFilter("TimeSeries")
query.AddAttributeValueFilter("RegionKey", cpiKey) #create search query based on 'concept'

result = d.Search(query).Entities

for s in result:
    print(s.Name)

Search for specific time series defined by the 'concept' and download them

This method requires a Data+ license.

This example searches for time series that are defined by Macrobond as the GDP series for the regions 'us', 'gb' and 'cn'. The RegionKey attribute defines what is called a 'concept' and is used to build the 'Concept & Category' database view in Macrobond Application. It is a powerful way to identify corresponding series for many regions. For the GDP series, the RegionKey is 'gdp_total.'

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

query = d.CreateSearchQuery()
query.SetEntityTypeFilter("TimeSeries")
query.AddAttributeValueFilter("RegionKey", "gdp_total")
query.AddAttributeValueFilter("Region", ["us", "gb", "cn"])

result = d.Search(query).Entities

for s in result:
  print(s.Name)

Search for series of a specific industry sector

This method requires Data+ license.

This will select the Companies where IcbClassification=icb2713 (Aerospace).

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

query = d.CreateSearchQuery()
query.SetEntityTypeFilter("Company")
query.AddAttributeValueFilter("IcbClassification", "icb_2713")

result = d.Search(query).Entities

for s in result:
    print(s.Name)

Search for series closing prices and traded volume for companies of a specific industry sector

This method requires Data+ license.

This example uses list of search queries. The first query will select the Companies where IcbClassification=icb2713 (Aerospace).

The second query (querySecurity) will find all securities where CompanyKey=main_equity and has the Company equal to one of the companies in the result of the first query.

The query called queryCloseSeries will find all series where DataType=close and has the Security equal to one of the securities found by the previous filter. The volume series are found in an analogous way.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

query = d.CreateSearchQuery()
query.SetEntityTypeFilter("Company")
query.AddAttributeValueFilter("IcbClassification", "icb_2713")

querySecurity = d.CreateSearchQuery()
querySecurity.SetEntityTypeFilter("Security")
querySecurity.AddAttributeValueFilter("CompanyKey", "main_equity")

queryCloseSeries = d.CreateSearchQuery()
queryCloseSeries.SetEntityTypeFilter("TimeSeries")
queryCloseSeries.AddAttributeValueFilter("DataType", "close")

querySeriesVolume = d.CreateSearchQuery()
querySeriesVolume.SetEntityTypeFilter("TimeSeries")
querySeriesVolume.AddAttributeValueFilter("PriceType", "vl")

resultClose = d.Search([query, querySecurity, queryCloseSeries]).Entities
resultVolume = d.Search([query, querySecurity, querySeriesVolume]).Entities

for s in resultClose:
  print(s.Name)

for s in resultVolume:
  print(s.Name)

Search  for series based on its ISIN

This method requires Data+ license.

ISIN is a metadata, you cannot download series by it in API but with below workaround you can use search to find series code based on ISIN and then download series.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

#Search for Security using ISIN
query = d.CreateSearchQuery()
query.SetEntityTypeFilter("Security")
query.AddAttributeValueFilter("Region",["it"])
query.Text = "IT0003132476"
result = d.Search(query).Entities

for s in result:
    print(s.Name)

With below code you can pass a list of ISINs:

def GetTickers_FromISIN(filepath):   
    #Search for "Security" type using ISINs (Text) as tickers
    query = Macrobond.CreateSearchQuery()
    query.SetEntityTypeFilter("TimeSeries") # or "Security"
   
    # Read the list of tickers and store them into a list
    with open(filepath, 'r') as file:
        tickers = [line.strip() for line in file]
   
    #Start fetching all the ISIN and convert them into tickers
    all_results = []
    for ticker in tqdm(tickers, desc="Processing ISINs"):
        query.Text = ticker
        ISO = query.Text[:2].lower() # Get the region/ISO-2 code in no capital letters!

    for s in result:
        print(s.Name)

        query.AddAttributeValueFilter("Region", [ISO])
        result = Macrobond.Search(query).Entities
        all_results.extend(result) # Append tickers
       
    return all_results

ISearchQuery

Use this interface to set up a search query. You create objects with this interface by calling IDatabase.CreateSearchQuery(). Then you configure the object and pass it as a parameter to IDatabase.Search().

string Text An optional text to search for. The search will be made by matching each word.
SetEntityTypeFilter(VARIANT types) A single string or a vector of strings identifying what type of entities to search for. The options are TimeSeries, Release, Source, Index, Security, Region, RegionKey, Exchange and Issuer.

Typically you want to set this to TimeSeries. If not specified, the search will be made for several entity types.

AddAttributeFilter(string attributeName, bool include = true) Add a name of an attribute that must or must not be set on entities returned by the search. The 'include' parameter determines if the search should include or exclude entities that have the attribute.

For example, if you do AddAttributeFilter("SeasonAdj"), only series that are seasonally adjusted will be included.

You can call this method several times to add more filters.

AddAttributeValueFilter(string attributeName, VARIANT attributeValues, bool include = true) Add attribute values that must or must not be set on entities returned by the search. You can specify one value or a list of values. The 'include' parameter determines if the search should include or exclude entities that have the attribute values.

For example, if you do AddAttributeValueFilter("Region", ["us", "gb", "cn"]) only entities that have the Region attribute set to any of "us", "gb" or "cn" will be included.

You can call this method several times to add more filters.

bool IncludeDiscontinued Set to True to include discontinued series in the search. The default is False.

ISearchResult

This interface represents a search result returned by a call to IDatabase.Search(query).

IEntity[] Entities The list of entities returned by the search.
bool IsTruncated This is True if the result is not exhaustive. There is a limit on the number of entities that can be returned. It is possible to get at least 2000 entities before the result is truncated.

Revision/Vintage - codes

Get all available revisions

This example only works with Data+ license.

Below example uses pandas - for more information on how to use it see Pandas.

import win32com.client
import pandas as pd

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

#Helper method
def toPandasSeries(series):
    #For some reason, pandas 0.19 does not like the result when to_datetime
    #is used directly on the array DatesAtStartOfPeriod. Convert to string first.
    pdates = pd.to_datetime([d.strftime('%Y-%m-%d') for d in series.DatesAtStartOfPeriod])
    return pd.Series(series.values, index=pdates)

s = d.FetchOneSeriesWithRevisions("uscpi")
history = s.GetCompleteHistory()

full_history = pd.DataFrame()

for x in range(13, len(history)):
    full_history[str(history[x].Metadata.GetFirstValue("RevisionTimestamp"))] = toPandasSeries(history[x])

print(full_history)

Get the timestamps of each value in the current series

This example only works with Data+ license.

This example fetches the revision history for a series and obtains a series with the current vintage. The values will be the same as the 'head' series, but you will also get the ValuesMetadata with a timestamp of when each value was last modified.

import win32com.client
import datetime

def getRevisionTimestamp(m):
   if m == None:
      return(None)
   t = m.GetFirstValue("RevisionTimestamp")
   return (t)

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeriesWithRevisions("uscpi")
currentVintageSeries = s.GetVintage(datetime.datetime.now())
lastChangedTimestamps = [getRevisionTimestamp(vm) for vm in currentVintageSeries.ValuesMetadata]

for t in lastChangedTimestamps:
   print(t)

Get revision history for original and first release

This example only works with Data+ license.

This example fetches the revision history for a series and obtains a series with the original release values and one with the values of the first revision.

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeriesWithRevisions("uscpi")

firstRevisionSeries = s.GetNthRelease(0)
secondRevisionSeries = s.GetNthRelease(1)

values = firstRevisionSeries.Values
print(values)

Get the timestamps of each value in Nth release

This example only works with Data+ license.

This example fetches the revision history for a series and obtains a series with the original release values. It then creates a list of the timestamps when the values were recorded.

import win32com.client

def getRevisionTimestamp(m):
   if m == None:
      return(None)
   t = m.GetFirstValue("RevisionTimestamp")
   return (t)

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

s = d.FetchOneSeriesWithRevisions("uscpi")
firstReleaseSeries = s.GetNthRelease(0)
firstReleaseDates = [getRevisionTimestamp(vm) for vm in firstReleaseSeries.ValuesMetadata]

for t in firstReleaseDates:
   print(t)

ISeriesWithRevisions

This example only works with Data+ license.

This interface represents a time series with revision history.

The series returned by Head, GetNthRelease, GetVintage and GetCompleteHistory will all be of equal length and share the same calendar. In this way they can easily be used in a data frame.

bool IsError If True, then the series request resulted in an error and the ErrorMessage property contains an error message. If there is an error, only these two properties are valid.
string ErrorMessage Contains an error message if IsError is True.
bool HasRevisions If True, then the series has one or more revisions.
bool StoresRevisions If True, then the series stores revision history. This can be True while HasRevisions is False if no revisions have yet been recorded.
datetime TimeOfLastRevision The timestamp of the last revision.
ISeries Head The current revision of the time series.
ISeries GetNthRelease(int n) Get then nth revision of each value. GetNthRelease(0) will return the first release of each value.

Values that have not been revised the number of times specified and value for which the complete revision history is not known will be represented by NaN.

The series ValuesMetadata will contain the metadata attribute RevisionTimeStamp with the timestamp when the revision was made to that value.

ISeries GetVintage(datetime time) Get the series as it looked at the time specified.

The metadata attribute RevisionTimeStamp will contain the timestamp of when this revision was recorded.

In order to make this series of the same length as the Head series, it may be padded with NaN.

ISeries GetObservationHistory(date d) Get a daily series with the revision history of the value specified by the date.
ISeries[] GetCompleteHistory() Get list of all revisions.

Each time series has the metadata attribute RevisionTimeStamp with the timestamp the revision. The first series typically has date 1899-12-30 which means that the timestamp of the original data is not known.

Please note that this can potentially be a lot of data and use a large amount of memory.

datetime[] GetVintageDates() Get a list of timestamps representing when revisions were recorded.

Class with constants

The class below contains the values of all constants for the API as used in the preceding examples.

You can also find these constants in the PIP package macrobond-api-constants which can be found here. To define constant in a code please use after import win32com.client for example:

from macrobond_api_constants import SeriesFrequency as f

and then you can call in code:

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp")
r.Frequency = f.MONTHLY

How to define the lowest frequency with last value?

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesToLowerFrequencyMethod as l

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("mxn").ToLowerFrequencyMethod = l.LAST
r.AddSeries("usexportwheatmx").ToLowerFrequencyMethod = l.LAST
r.Frequency = f.LOWEST
r.StartDate = "2000"

How to define average monthly values?

import win32com.client
c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

from macrobond_api_constants import SeriesToLowerFrequencyMethod as l
from macrobond_api_constants import CalendarDateMode as cd 
from macrobond_api_constants import SeriesFrequency as f

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("vix").ToLowerFrequencyMethod = l.AVERAGE
r.StartDateMode = cd.ALL_SERIES
r.Frequency = f.MONTHLY

listOfSeries = d.FetchSeries(r)
values = listOfSeries[0].Values
dates = listOfSeries[0].DatesAtStartOfPeriod

SeriesFrequency

This enumeration contains the supported time series frequencies.

ANNUAL Once a year. (int = 1)
SEMI_ANNUAL Twice a year. (int = 2)
QUAD_MONTHLY Once in 4 months. (int = 3)
QUARTERLY Once in 3 months (int = 4)
BI_MONTHLY Every second month. (int = 5)
MONTHLY Once a month. (int = 6)
WEEKLY Once a week (int = 7)
DAILY Once a day. (int = 8)
LOWEST When specified in a series request, this corresponds to the lowest frequency of the series in set. (int = 100)
HIGHEST When specified in a series request, this corresponds to the highest frequency of the series in the request. (int = 101)

SeriesWeekdays

This enumeration contains flags that are used as bitmasks to determine what weekdays that are used in a daily time series.

SUNDAY (int = 1)
MONDAY (int = 2)
TUESDAY (int = 4)
WEDNESDAY (int = 8)
THURSDAY (int = 16)
FRIDAY (int = 32)
SATURDAY (int = 64)
FULLWEEK Sun+Mon+Tue+Wed+Thu+Fri+Sat (int = 127)
MONDAY_TO_FRIDAY Mon+Tue+Wed+Thu+Fri (int = 62)
SATURDAY_TO_THURSDAY Sun+Mon+Tue+Wed+Thu+Sat (int = 95)
SATURDAY_TO_WEDNESDAY Sun+Mon+Tue+Wed+Sat (int = 79)
SUNDAY_TO_THURSDAY Sun+Mon+Tue+Wed+Thu (int = 31)
MONDAY_TO_THURSDAY_AND_SATURDAY Sun+Mon+Tue+Wed+Thu+Sat (int = 94 )

CalendarMergeMode

This enumeration defines how calendars are merged into one calendar when there are time periods missing in one or more series. Please note that missing time period is not the same thing as a missing value. A time period is missing in cases when there should be no observation such as on a holiday. A missing value, on the other hand, is a special value in the time series that indicates that there should have been a value, but it is unknown for some reason.

FULL_CALENDAR Use all the time periods as specified by the frequency and weekdays. (int = 0)
AVAILABLE_IN_ALL Use the time periods that are available in all series. (int = 1)
AVAILABLE_IN_ANY Use the time periods that are available in any series. (int = 2)

CalendarDateMode

This enumeration defines how the StartDate and EndDate properties of a unified series request are interpreted when they are set to a relative or empty reference.

ANY_SERIES Use the first or last time period where there is valid data in any series. (int = 0)
ALL_SERIES Use the first or last time period where there is valid data in all series. (int = 1)

SeriesMissingValueMethod

This enumeration determines the method for filling in any missing values.

NONE Do not fill in missing values. They will remain NaN in the value vector. (int = 0)
AUTO Determine the method based on the series classification. (int = 1)
PREVIOUS Use the previous non-missing value. (int = 2)
ZERO Use the value zero. (int = 3)
LINEAR_INTERPOLATION Do a linear interpolation between the previous and next non-missing values. (int = 4)

SeriesToLowerFrequencyMethod

This enumeration determines the method for converting a series to a lower frequency.

AUTO Determine the method based on the series classification. (int = 0)
LAST Use the last value of the time period. (int = 1)
FIRST Use the first value of the time period. (int = 2)
FLOW Aggregate the values of the time period. (int = 3)
PERCENTAGE_CHANGE Aggregate the percentage change over the period. (int = 4)
HIGHEST Use the highest value in the time period. (int = 5)
LOWEST Use the lowest value of the time period. (int = 6)
AVERAGE Use the average value of the period. (int = 7)
CONDITIONAL_PERCENTAGE_CHANGE Aggregate percentage change of the period depending on series properties. (int = 8)

SeriesToHigherFrequencyMethod

This enumeration determines the method for converting a series to a higher frequency.

AUTO Determine the method based on the series classification. (int = 0)
SAME Use the same value for the whole period. (int = 1)
DISTRIBUTE Use the first value of the time period. (int = 2)
PERCENTAGE_CHANGE Distribute the percentage change over the period. (int = 3)
LINEAR_INTERPOLATION Use a linear interpolation of the values from this to the next period. (int = 4)
PULSE Use the value for the first value of the period. (int = 5)
QUADRATIC_DISTRIBUTION Use quadratic interpolation to distribute the value over the period. (int = 6)
CUBIC_INTERPOLATION Use a cubic interpolation of the values from this to the next period. (int = 7)
CONDITIONAL_PERCENTAGE_CHANGE Aggregate percentage change of the period depending on series properties. (int = 8)

SeriesPartialPeriodsMethod

This enumeration determines the method for converting a series with partial periods.

NONE Do not include partial periods. (int = 0)
AUTO Determine the method based on the series meta data. (int = 1)
REPEAT_LAST Fill up the partial period by repeating the last value. (int = 3)
FLOW_CURRENT_SUM Fill up the partial period with the average of the incomplete period. (int = 3)
PAST_RATE_OF_CHANGE Use the rate of change from the previous year to extend the partial period. (int = 4)
ZERO Fill up the partial period with zeroes. (int = 5)

MetadataValueType

The type of a metadata value. These values correspond to the COM VARIANT data types.

INT A 32-bit signed integer. VT_I4. (int = 3)
DOUBLE A 64-bit floating-point number. VT_R8. (int = 5)
DATE A date. VT_DATE. (int = 7)
STRING A unicode string. VT_BSTR. (int = 8)
BOOL A boolean value where -1 is True and 0 is False. VT_BOOL. (int = 11)

Pandas - examples how to use them with the Macrobond API

Helper method and defined options

For each use of pandas we recommend to add our Helper method and one of the three options visible below:

#Helper method
def toPandasSeries(series):
    #For some reason, pandas 0.19 does not like the result when to_datetime
    #is used directly on the array DatesAtStartOfPeriod. Convert to string first.
    pdates = pd.to_datetime([d.strftime('%Y-%m-%d') for d in series.DatesAtStartOfPeriod])
    return pd.Series(series.values, index=pdates)
#OPTION 1 - Get one series from Macrobond as a pandas time series
def getOneSeries(db, name):
    return toPandasSeries(db.FetchOneSeries(name))

#OPTION 2 - Get several series from Macrobond as pandas time series
def getSeries(db, names):
    series = db.FetchSeries(names)
    return [toPandasSeries(s) for s in series]

#OPTION 3 - Get several series from Macrobond as a pandas data frame with a common calendar
def getDataframe(db, unifiedSeriesRequest):
    series = db.FetchSeries(unifiedSeriesRequest)
    return pd.DataFrame({s.Name: toPandasSeries(s) for s in series})

Download one series

import pandas as pd
import win32com.client

#Helper method
def toPandasSeries(series):
    #For some reason, pandas 0.19 does not like the result when to_datetime
    #is used directly on the array DatesAtStartOfPeriod. Convert to string first.
    pdates = pd.to_datetime([d.strftime('%Y-%m-%d') for d in series.DatesAtStartOfPeriod])
    return pd.Series(series.values, index=pdates)
#OPTION 1 - Get one series from Macrobond as a pandas time series
def getOneSeries(db, name):
    return toPandasSeries(db.FetchOneSeries(name))

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

series = getOneSeries(d, 'uscpi')
print(series)

Download two series

import pandas as pd
import matplotlib.pyplot as plt
import win32com.client

#Helper method
def toPandasSeries(series):
    #For some reason, pandas 0.19 does not like the result when to_datetime
    #is used directly on the array DatesAtStartOfPeriod. Convert to string first.
    pdates = pd.to_datetime([d.strftime('%Y-%m-%d') for d in series.DatesAtStartOfPeriod])
    return pd.Series(series.values, index=pdates)

#OPTION 2 - Get several series from Macrobond as pandas time series
def getSeries(db, names):
    series = db.FetchSeries(names)
    return [toPandasSeries(s) for s in series]

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

two_series = getSeries(d, ('uscpi', 'secpi'))
print (two_series)

Download several series, create data frame

import pandas as pd
import matplotlib.pyplot as plt
import win32com.client

#Helper method
def toPandasSeries(series):
    #For some reason, pandas 0.19 does not like the result when to_datetime
    #is used directly on the array DatesAtStartOfPeriod. Convert to string first.
    pdates = pd.to_datetime([d.strftime('%Y-%m-%d') for d in series.DatesAtStartOfPeriod])
    return pd.Series(series.values, index=pdates)

#OPTION 3 - Get several series from Macrobond as a pandas data frame with a common calendar
def getDataframe(db, unifiedSeriesRequest):
    series = db.FetchSeries(unifiedSeriesRequest)
    return pd.DataFrame({s.Name: toPandasSeries(s) for s in series})

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

r = d.CreateUnifiedSeriesRequest()
r.AddSeries('gbcpi')
r.AddSeries('uscpi')
r.AddSeries('secpi')

frames = getDataframe(d, r)

frames.plot()
plt.show()

Download one series, create data frame and scale values

We store values in their original form, in single units, i.e., 19699465000000. While our main app transforms these values automatically on Time table/Time chart, Python download them in original form, without any formatting. You can scale them by yourself with below code. For scaling without pandas see Download one series and scale values.

import win32com.client
import pandas as pd

#Helper method
def toPandasSeries(series):
    #For some reason, pandas 0.19 does not like the result when to_datetime
    #is used directly on the array DatesAtStartOfPeriod. Convert to string first.
    pdates = pd.to_datetime([d.strftime('%Y-%m-%d') for d in series.DatesAtEndOfPeriod])
    return pd.Series(series.values, index=pdates)

#OPTION 3 - Get several series from Macrobond as a pandas data frame with a common calendar
def getDataframe(db, unifiedSeriesRequest):
    series = db.FetchSeries(unifiedSeriesRequest)
    return pd.DataFrame({s.Name: toPandasSeries(s) for s in series})

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp")

frames = getDataframe(d, r)
print(frames/1000000000000)

Outcome:
2022-03-31 19.727918
2022-06-30 19.699465

Download one series, change frequency & currency, keep dates at the end of period, create data frame

The End of Period is defined inside the Helper method (series.DatesAtEndOfPeriod]). This example uses our constants package. For more information about it see here.

For all available 'Frequency' methods see SeriesFrequency.
For all available 'ToLower' methods see SeriesToLowerFrequencyMethod.

import win32com.client
import pandas as pd

from macrobond_api_constants import SeriesFrequency as f
from macrobond_api_constants import SeriesToLowerFrequencyMethod as tl

#Helper method
def toPandasSeries(series):
    #For some reason, pandas 0.19 does not like the result when to_datetime
    #is used directly on the array DatesAtStartOfPeriod. Convert to string first.
    pdates = pd.to_datetime([d.strftime('%Y-%m-%d') for d in series.DatesAtEndOfPeriod])
    return pd.Series(series.values, index=pdates)

#OPTION 3 - Get several series from Macrobond as a pandas data frame with a common calendar
def getDataframe(db, unifiedSeriesRequest):
    series = db.FetchSeries(unifiedSeriesRequest)
    return pd.DataFrame({s.Name: toPandasSeries(s) for s in series})

c = win32com.client.Dispatch("Macrobond.Connection")
d = c.Database

r = d.CreateUnifiedSeriesRequest()
r.AddSeries("usgdp").ToLowerFrequencyMethod = tl.LAST
r.Frequency = f.MONTHLY
r.Currency = "EUR"

frames = getDataframe(d, r)
print(frames)

The Macrobond API for R

Introduction

Macrobond offers an API that can be used in R for Windows. You can download time series (values, dates and metadata) and upload your own series to the in-house database which can then be used in the Macrobond application and optionally shared with others.

This document refers to Macrobond application version 1.27 and later and Macrobond API for R version 1.2-8. Examples were tested on R 4.3.0.

Requirements

The API requires Macrobond to be installed and functioning on the computer where R is run.

Package version

We provide a package for R 3.5 - 4.4. If you are running the 64-bit version of R, you need to use the 64-bit version of Macrobond. We have tested our package with various R versions and recommend to use:

for R 3.5.0 - 4.1.0 Macrobond API 1.1-5
for R 4.2.0 - 4.4.0 Macrobond API 1.2-8

The Macrobond API uses the xts package and requires at least version 0.9-7 of that package.

Macrobond license and main app version

This API can be used only with Legacy (without searching and revision history functions) or Data+ license.

R in other programs

Note we test that the API works with R.exe and RGui.exe. When R is used as an embedded component in other programs, it might or might not work. You need to test this yourself and we can only give limited support in those cases.

Installation

The Macrobond R API comes in the form of an R binary package called 'MacrobondAPI' from the Macrobond repository at https://download.macrobond.com/installation/R (you cannot browse to that URL). Here are two ways to install the Macrobond API package.

These methods always download the newest version of our package. If you have older R version, please check here if you need an older Macrobond API package for your R version. If yes, please contact our support for further instructions.

Method 1: Add the Macrobond repository to the list of repositories

You can add this repository to the list of repositories that R will search in various ways. One option is to use the command:

setRepositories(addURLs = c(Macrobond = "https://download.macrobond.com/installation/R"))

or add the repository to the configuration file. See ?setRepositories for details.

Once you have added the Macrobond repository to your list of repositories, you can just run this R command:

install.packages("MacrobondAPI", type="win.binary")

Method 2: Explicitly specify the repository

  1. Restart R
  2. If you do not have 'xts' installed, install it by
    install.packages("xts")

    If you have 'xts' installed, make sure you have the latest version by running

    update.packages("xts")
  3. Install the MacrobondAPI package by running
    install.packages("MacrobondAPI", type="win.binary", repos="https://download.macrobond.com/installation/R")

Upgrading the Macrobond API

  1. Restart R
  2. Run
    update.packages(repos="https://download.macrobond.com/installation/R", type="win.binary")

We urge you to keep your Macrobond API for R up to date. We also suggest that you periodically upgrade the Macrobond application as described here.

Getting Started

To successfully use the API, you might want to learn more about the Commonly used  metadata.

Working with R API

Once you have installed the Macrobond API package, you can view the documentation from R like this:

library(MacrobondAPI)
?MacrobondAPI

You can also view documentation for a specific function directly with:

?getValues

While using help available directly from within R - as described above - is the recommended way of reading the Macrobond R API documentation, you can also view it online (list of commands).

Time series

Download one series

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")
seriesGdp

#check that the series loaded OK 
if (getIsError(seriesGdp)) 
  stop(getErrorMessage(seriesGdp))

Download one series wrapped in ratio (#PerCapita)

Use the #PerCapita ratio to get a series of the US GDP per capita. For more information about this functionality see Ratios.

library(MacrobondAPI)

seriesGdpPerCapita <- FetchOneTimeSeries("#PerCapita(usgdp)")
seriesGdpPerCapita

Download several series, transform them to a common length and calendar

You need to use addSeries for each series. This allows you to access the settings object for each requested series. By default, the highest frequency of the series and the union on the ranges will be used.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest()

addSeries(seriesRequest, "usgdp")
addSeries(seriesRequest, "uscpi")

twoSeries <- FetchTimeSeries(seriesRequest)
twoSeries

Download series and set start year

This will download two series and convert them to the higher frequency. The data range is set to start year 2020 and continue until the last observation that has data in both series. You can also set relative date like "-5y" or "-10" (observations). For more information see SeriesRequest-class.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest()
setStartDate(seriesRequest, "2020-01-01")

seriesAll <- addSeries(seriesRequest, "usgdp")
seriesAll <- addSeries(seriesRequest, "uscpi")


twoSeries <- FetchTimeSeries(seriesRequest)
twoSeries

Download series and set common start Date and end Date

For all available 'MissingValue' methods see CalendarDateMode.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest() 

#set the start to the first point where data is available in all series 
setStartDateMode(seriesRequest, "DataInAllSeries") 

#set the end to the last point where data is available in all series 
setEndDateMode(seriesRequest, "DataInAllSeries") 

#or you can write:
#setStartDateMode(seriesRequest, CalendarDateMode[["DataInAllSeries"]]) 
#setEndDateMode(seriesRequest, CalendarDateMode[["DataInAllSeries"]]) 

addSeries(seriesRequest, "usgdp") 
addSeries(seriesRequest, "uscpi") 

twoSeries <- FetchTimeSeries(seriesRequest)
twoSeries

Download several series, change frequency, and set missing value method

For all available 'MissingValue' methods see Missing value methods.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest()
setFrequency(seriesRequest, "Monthly")

seriesAll <- addSeries(seriesRequest, "usgdp")
seriesAll <- addSeries(seriesRequest, "uscpi")

setMissingValueMethod(seriesAll, "None")

twoSeries <- FetchTimeSeries(seriesRequest)
twoSeries

Download series and convert it with 'to higher frequency' method

For all available 'ToHigher' methods see To higher frequency methods.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest()
setFrequency(seriesRequest, "Weekly")

seriesAll<-addSeries(seriesRequest, "usgdp")
seriesAll <- addSeries(seriesRequest, "uscpi")

setToHigherFrequencyMethod(seriesAll, "LinearInterpolation")

twoSeries <- FetchTimeSeries(seriesRequest)
twoSeries

Download series, convert frequency with 'to lower frequency' method and set one currency

For all available 'ToLower' methods see To lower frequency methods.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest()

setFrequency(seriesRequest, "Annual")
setCurrency(seriesRequest, "chf")

seriesAll<-addSeries(seriesRequest, "usgdp")
seriesAll <- addSeries(seriesRequest, "chgdp")

setToLowerFrequencyMethod(seriesAll, "Last")


twoSeries <- FetchTimeSeries(seriesRequest)
twoSeries

Download series, convert frequency and fill in partial periods

For all available 'PartialPeriods' methods see TimeSeriesPartialPeriodsMethod.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest()
setFrequency(seriesRequest, "Quarterly")

series <- addSeries(seriesRequest, "uscpi")
setPartialPeriodsMethod(series, "RepeatLastValue")

seriesCPI <- FetchTimeSeries(seriesRequest)
seriesCPI

Download series, and set calendar mode

For all available 'CalendarMode' methods see CalendarMergeMode.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest() 

#all holidays will always be included as missing values instead of being skipped in the calendar 
setCalendarMergeMode(seriesRequest,"FullCalendar") 
#or you can write: setCalendarMergeMode(seriesRequest, CalendarMergeMode[["FullCalendar"]]) 

addSeries(seriesRequest, "usfcst3898") 
addSeries(seriesRequest, "eur") 

twoSeries <- FetchTimeSeries(seriesRequest) 
twoSeries

Get values and dates

Obtain separate vectors with values and dates.

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")

vectorOfValues <- getValues(seriesGdp)
vectorOfObservationDates <- getDatesAtStartOfPeriod(seriesGdp)

vectorOfValues
vectorOfObservationDates

Create and upload a series with only one value

Normally it's not possible to create series with only one value because "The values must be specified as an array". But see below workaround:

library(MacrobondAPI)

seriesNew <- CreateTimeSeriesObject("ih:mb:priv:s2", "My forecast", "de", "Financial", "Monthly", as.Date("1990-01-01"), list(2))
seriesNew
UploadOneOrMoreTimeSeries(seriesNew)

Create and upload a monthly series

library(MacrobondAPI)

seriesNew <- CreateTimeSeriesObject("ih:mb:priv:s1", "My forecast", "us", "Forecasts", "Monthly", as.Date("1990-01-01"), c(12.2, 12.7, 12.8, 13.0))

UploadOneOrMoreTimeSeries(seriesNew)

To see series in Macrobond main app after uploading please refresh Account in-house tree in Macrobond with rounded arrow icon.

Create and upload a daily series with currency metadata

The default value for 'dayMask' parameter is "MondayToFriday". For the list of all available parameters see TimeSeriesWeekdays.

library(MacrobondAPI)

meta <- CreateEmptyMetadata()
addMetadataValue(meta, "Currency", "eur")

seriesNew <- CreateTimeSeriesObject("ih:mb:priv:s2", "My forecast", "de", "Financial", "Daily", as.Date("1990-01-01"), c(12.2, 12.7, 12.8, 13.0, 12.2, 13.1, 14.4),"FullWeek", meta)

UploadOneOrMoreTimeSeries(seriesNew)

To see series in Macrobond main app after uploading please refresh Account in-house tree in Macrobond with rounded arrow icon.

Create and upload a monthly series with flagged forecast

seriesNew <- CreateTimeSeriesObjectWithForecastFlags("ih:mb:priv:s1", "My forecast", "us", "Forecasts", "Monthly", as.Date("2022-11-01"), c(12.2, 12.7, 12.8, 13.0), c(FALSE, FALSE, TRUE, TRUE))

UploadOneOrMoreTimeSeries(seriesNew)

To see series in Macrobond main app after uploading please refresh Account in-house tree in Macrobond with rounded arrow icon.

Append new value to in-house

First create an in-house time series - s1, that step is needed only once. It'll fetch that in-house series, add to it value 123 at a specific date, then upload it.

library(MacrobondAPI)

mySeries <- FetchOneTimeSeries("ih:mb:priv:s1")

values = getValues(mySeries)
values[getIndexAtDate(mySeries,as.Date("1990-11-01"))] <- 123

seriesNew = CreateTimeSeriesObject("ih:mb:priv:s1", "My forecast", "us", "Forecasts", "Monthly", as.Date("1990-01-01"), values )
UploadOneOrMoreTimeSeries(seriesNew)

How to automatically update in-house from my R-file?

There is no such function in MB API, we recommend to use taskscheduleR package or use built-in schedulers.

Delete a series

library(MacrobondAPI)

DeleteOneOrMoreTimeSeries("ih:mb:priv:s1")

Metadata

See Commonly used metadata.

How to see series metadata?

List metadata available for a series.

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")
meta <- getMetadata(seriesGdp)

show(meta)

How to see specific metadata?

To see other metadata replace text in last line's quotation marks:

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")

getMetadataValues(getMetadata(seriesGdp), "LastModifiedTimeStamp")

Get information about the metadata attribute

All possible commands can be found under MetadataInformation.

library(MacrobondAPI)

#get information about the TimeDim metadata attribute
metaInfo <- GetMetadataInformation("TimeDim")

show(metaInfo) #information about metadata
listAllValues(metaInfo) #list of versions of this metadata

#other
getDescription(metaInfo)
getComment(metaInfo)
getValueType(metaInfo)

Get series title

library(MacrobondAPI) 

seriesGdp <- FetchOneTimeSeries("usgdp")

getTitle(seriesGdp)

Get the presentation text for a region code

This will get information about the metadata type called 'Region' and then get the presentation text for the region called 'us'. The result will be the string 'United States'.

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")

meta <- GetMetadataInformation("Region")
country <- getMetadataValues(getMetadata(seriesGdp), "Region")

getValuePresentationText(meta, country)

Get currency metadata from a series

library(MacrobondAPI) 

seriesGdp <- FetchOneTimeSeries("usgdp")

metaGdp <- getMetadata(seriesGdp)
currency <- getFirstMetadataValue(metaGdp, "Currency")

currency

Get a list of all currencies

This will get information about the metadata type called 'Currency' and list all available currency codes.

library(MacrobondAPI)

metaInfo <- GetMetadataInformation("Currency")
metaInfo

listAllValues(metaInfo)

Get name of release

The name of the release is a metadata property of the time series. The release has a corresponding "entity" in the database.

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")

metaGdp <- getMetadata(seriesGdp)
releaseGdpName <- getFirstMetadataValue(metaGdp, "Release")

releaseGdpName

Get the next release date

The NextReleaseEventTime attribute contains information about the next scheduled release of updated series. The date might be missing if no release date is known.

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")

metaGdp <- getMetadata(seriesGdp)
releaseGdpName <- getFirstMetadataValue(metaGdp, "Release")

if (!is.null(releaseGdpName))
{
  releaseGdp <- FetchOneEntity(releaseGdpName)
  getFirstMetadataValue(getMetadata(releaseGdp), "NextReleaseEventTime")
}

Get next publication date

Some series have 'NextReleaseEventTime' metadata but some don't. Then it's the best to use 'CalendarUrl' metadata connected to Release metadata.

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")

metaGdp <- getMetadata(seriesGdp)
releaseGdpName <- getFirstMetadataValue(metaGdp, "Release")

if (!is.null(releaseGdpName))
{
  releaseGdp <- FetchOneEntity(releaseGdpName)
  getFirstMetadataValue(getMetadata(releaseGdp), "CalendarUrl")
}

How to know if series is discontinued?

EntityState = 0 means series is active
EntityState = 4 means series is discontinued

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")

getMetadataValues(getMetadata(seriesGdp), "EntityState")

How to handle double region?

Some series have two regions and they do not display properly when you ask for Region metadata in R because of it. We have two solutions:

library(MacrobondAPI)

series <- FetchOneTimeSeries("eea_8_579")

metaRegion <- GetMetadataInformation("Region")
meta <- getMetadata(series)

for (singleRegion in getMetadataValues(meta, name = "Region") ){
  print(getValuePresentationText(metaRegion, singleRegion ) )
}
library(MacrobondAPI)

series <- FetchOneTimeSeries("eea_8_579")

metaRegion <- GetMetadataInformation("Region")
meta <- getMetadata(series)

paste(lapply(getMetadataValues(meta, name = "Region"), getValuePresentationText,m=metaRegion),collapse = ", ")

#to get country you can use to this code:
getValuePresentationText(metaRegion, getMetadataValues(meta, name = "Region")[1])

Unfortunately you cannot be sure that from two attributes country always the first element. If you really want to find the region, the best option right now is to look for the region where RegionType="country". In future versions there will be a "ArrangeValues" method you can use sort them.

Concept/Region key

Some of our series are connected with each other through metadata called Region Key. If you know it, you can find series for other countries/regions. In main-app you can see those data sets under Concept & Region data tree.

Get 'concept' from a series

library(MacrobondAPI)

getMetadata(FetchOneTimeSeries("delead1000"))

In the output you will see:

RegionKey              busc_mb : Macrobond Defined, Business Cycle

The busc_mb is a Region key.

Get 'concept' description

library(MacrobondAPI)

series <- FetchOneTimeSeries("uscpi")

show(GetConceptDescription(getConcepts(series)))

Use 'concept' to reference a series

library(MacrobondAPI)

FetchOneTimeSeries(":Region:gdp_total[Region=us]")

Use 'concepts' to find series for several countries

library(MacrobondAPI)

ks <- function(type, region) paste0(":Region:", type, "[Region=", region, "]")
rs <- function(region) FetchTimeSeries(c(ks("cpi_total", region), ks("gdp_total", region), ks("trade_balance", region)))

#this will download three series for United States
rs("us") 

#this will download the corresponding three series for Great Britain
rs("gb") 

#this will download all three series for both countries
rs(c("gb", "us"))

Search

The number of results returned by MacrobondAPI::SearchEntities is limited to 12,000 without search text (only filters) and 6,000 with search text. If you’re experiencing result truncation – please provide more precise search criteria.

To see how to use search function in creating charts go to Circular bar chart (incl. automated search) and Choropleth map (incl. automated search).

Generate search code in Macrobond main app

When you input a query into search field in Macrobond’s Search tab, you can then generate a ready-to-use code for search in R:

Simple search query

This method requires a Data+ license.

library(MacrobondAPI)

query <- CreateSearchQuery()
setSearchText(query, "germany cpi")
entities <- SearchEntities(query)
entities

Search for 'concept' based on a series, download whole data set

This method requires a Data+ license.

library(MacrobondAPI)

series<-FetchOneTimeSeries("ted_ar_ahw")

#get the concept of a series and create search query based on it
query <- CreateSearchQuery() 
setEntityTypeFilter(query, "TimeSeries") 
addAttributeValueFilter(query, "RegionKey", getConcepts(series)) 
country_set <- getEntities(SearchEntities(query))

#create empty vector
list_of_series<-NULL

#get list of series' codes
for (i in country_set){
  list_of_series<-append(list_of_series, getName(i))
}
  
list_of_series

Search for specific time series defined by the 'concept' and download them

This method requires a Data+ license.

Search for time series defined for the concept 'gdp_total' for four countries (based on List of countries and regions) and then download those series.

library(MacrobondAPI)

gdp_names <- SearchByConcept(c("us", "gb", "jp", "cn"), "gdp_total")

series <- FetchUnifiedTimeSeriesDefault(gdp_names)
series

Search for series of a specific industry sector

This example only works with Data+ license.

This will select the Companies where IcbClassification=icb2713 (Aerospace).

library(MacrobondAPI)

query <- CreateSearchQuery() 

setEntityTypeFilter(query, "Company")
addAttributeValueFilter(query, "IcbClassification", "icb_2713") 

dataset <- getEntities(SearchEntities(query))

#create empty vector
list_of_series<-NULL

#get list of series' codes
for (i in dataset){
  list_of_series<-append(list_of_series, getName(i))
}

list_of_series

Search for series closing prices and traded volume for companies of a specific industry sector

This example only works with Data+ license.

Search for series closing prices and traded volume for companies of a specific industry sector.
The first query will select the Companies where IcbClassification=icb2713 (Aerospace).

The second query (querySecurity) will find all securities where CompanyKey=main_equity and has the Company equal to one of the companies in the result of the first query.

The third query called queryCloseSeries will find all series where DataType=close and has the Security equal to one of the securities found by the previous filter.
The fourth query, volume series are found in an analogous way.

library(MacrobondAPI)

query <- CreateSearchQuery() 
setEntityTypeFilter(query, "Company")
addAttributeValueFilter(query, "IcbClassification", "icb_2713") 

querySecurity <- CreateSearchQuery() 
setEntityTypeFilter(querySecurity, "Security")
addAttributeValueFilter(querySecurity, "CompanyKey", "main_equity") 

queryCloseSeries <- CreateSearchQuery() 
setEntityTypeFilter(queryCloseSeries, "TimeSeries")
addAttributeValueFilter(queryCloseSeries, "DataType", "close") 

querySeriesVolume <- CreateSearchQuery() 
setEntityTypeFilter(querySeriesVolume, "TimeSeries")
addAttributeValueFilter(querySeriesVolume, "PriceType", "vl")

entities_close <- SearchEntities(c(query, querySecurity, queryCloseSeries))
entities_volume <- SearchEntities(c(query, querySecurity, querySeriesVolume))

entities_close
entities_volume

Search for series with free text and exclude a source

This method requires a Data+ license.

Search for time series, that are seasonally adjusted, belongs to the region us or de and matches the free text 'steel production'. Exclude series from the source World Steel Association.

To get metadata code use How to see specific metadata?.

library(MacrobondAPI)

query <- CreateSearchQuery()

setEntityTypeFilter(query, "TimeSeries")
setSearchText(query, "steel production")

addAttributeFilter(query, "SeasonAdj")
addAttributeValueFilter(query, "Region", c("us", "de"))
addAttributeValueFilter(query, "Source", "src_worldsteel", FALSE)

entities <- SearchEntities(query)
entities

Revisions/Vintage

To see how to use this feature in creating charts go to Slope chart (incl. vintage/revision data).

Get all available revisions

This method requires a Data+ license.

library(MacrobondAPI)

getCompleteHistory(FetchOneTimeSeriesWithRevisions("usgdp"))

Get timestamps of each value in the current series

This method requires a Data+ license.

library(MacrobondAPI)

getVintageTimes(FetchOneTimeSeriesWithRevisions("usgdp"))

Get the vintage series that shows what it looked like at specific point in time

This method requires a Data+ license.

library(MacrobondAPI)

seriesWithRevisions <- FetchOneTimeSeriesWithRevisions("usgdp") 

series2018 <- getVintage(seriesWithRevisions, as.POSIXct("2018-01-01 18:00:00", tz = "EST")) 

plot(series2018)

Get revision history for original and first release

This method requires a Data+ license.

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeriesWithRevisions("usgdp") 

firstRelease <- getNthRelease(seriesGdp, 0) 
secondRelease <- getNthRelease(seriesGdp, 1) 

series.xts <- MakeXtsFromUnifiedResponse(c(firstRelease, secondRelease)) 

plot(series.xts)

Get the timestamps of each value in release

This method requires a Data+ license.

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeriesWithRevisions("usgdp")

firstRelease <- getNthRelease(seriesGdp, 0)

getTimesFromHistoricalSeries(firstRelease)

XTS

MacrobondAPI for R uses package xts to create its objects and you can convert series to xts objects.

Convert the Macrobond time series object to an xts series

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp") 
seriesGdp.xts <- as.xts(seriesGdp)

seriesGdp.xts

Create data frame in one step

library(MacrobondAPI)

seriesGdp.xts <- as.xts(FetchOneTimeSeries("usgdp"))

Download one series, create data frame and scale values

We store values in their original form, in single units, i.e., 19699465000000. While our main app transforms these values automatically on Time table/Time chart, R download them in original form, without any formatting. You can scale them by yourself with below code:

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")
seriesGdp.xts <- as.xts(FetchOneTimeSeries("usgdp"))
seriesGdp.xts/1000000000000

Outcome:
2022-01-01 19.727918
2022-04-01 19.699465

Download one series, set start year, and then create an xts data frame

Set start year for a series and download it with shortened history. It can be modified for more than one series - use this line: addSeries(seriesRequest, "usgdp") to add more time series.

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest()
setStartDate(seriesRequest, "2020-01-01")

addSeries(seriesRequest, "usgdp")

oneSeries <- FetchTimeSeries(seriesRequest)
series.xts <- MakeXtsFromUnifiedResponse(oneSeries)

series.xts

Download two series, convert them to the same frequency using default settings, and then create an xts data frame

library(MacrobondAPI)

twoSeries <- FetchUnifiedTimeSeriesDefault(c("usgdp", "uscpi"))
series.xts <- MakeXtsFromUnifiedResponse(twoSeries)

series.xts

Download two series, convert them to quarterly, set missing value method for one of them, and then create an xts data frame

library(MacrobondAPI)

seriesRequest <- CreateUnifiedTimeSeriesRequest()
setFrequency(seriesRequest, "Quarterly")

addSeries(seriesRequest, "usgdp")
seriesExpressionCpi <- addSeries(seriesRequest, "uscpi")
setMissingValueMethod(seriesExpressionCpi, "None")

twoSeries <- FetchTimeSeries(seriesRequest)
series.xts <- MakeXtsFromUnifiedResponse(twoSeries)

series.xts

Convert series to use them with ggplot2

To go from MacrobondAPI to ggplot2 please use for example below code. For more advanced examples see Charts with R.

library(MacrobondAPI)
library(ggplot2)

#download series
series_pl <- FetchOneTimeSeries("plnaac0195")
series_hu <- FetchOneTimeSeries("hunaac0118")
series_cz <- FetchOneTimeSeries("cznaac0246")
series_ro <- FetchOneTimeSeries("ronaac0012")

#convert them into xts objects
series_pl.xts <- as.xts(series_pl)
series_hu.xts <- as.xts(series_hu)
series_cz.xts <- as.xts(series_cz)
series_ro.xts <- as.xts(series_ro)

#combine them
br<-cbind(series_pl.xts, series_hu.xts,series_cz.xts, series_ro.xts)

#plot one series with ggplot2
ggplot(br, aes(x=plnaac0195, y=Index))+geom_line()

#plot all four series with ggplot2
ggplot(br, aes(y=Index))+
  geom_line(aes(x=plnaac0195, colour="red")) +
  geom_line(aes(x=hunaac0118, colour="blue")) +
  geom_line(aes(x=cznaac0246, colour="black")) +
  geom_line(aes(x=ronaac0012, colour="green"))

Charts with R

Simple plot

library(MacrobondAPI)

seriesGdp <- FetchOneTimeSeries("usgdp")
plot(seriesGdp)

Outside of Macrobond - charts with R

Under Charts with R you can find examples (with code) how to download and construct certain charts unavailable in Macrobond.

Macrobond version

Some functions are available since a specific version of main application. With this command you can check in R which version you have.

GetMacrobondVersion()

Troubleshooting

If you're having problems with the Macrobond R connector, please contact us via https://www.macrobond.com/contact/support/ and:

  • Describe what you’re trying to achieve
  • Include the relevant code you tried to run
  • Provide information about version of Macrobond, R and the Macrobond’s R add–in. To do it, issue those two commands:
library(MacrobondAPI)
sessionInfo()

and send us the output.

License

The Macrobond R API uses the license GPL-2. It uses portions of an enhanced version of RDCOMClient. There is a source package available.

The Macrobond API for Matlab

Introduction

With the API for MATLAB you can load series from the Macrobond database, and you can store series to the Macrobond account in-house database from MATLAB.

Requirements

The Macrobond API in MATLAB works with MATLAB R2012B or later. If you are running the 64-bit version of MATLAB, you need to use the 64-bit version of Macrobond. This is a COM API and uses the support for COM in MATLAB.

This API can be used only with Legacy or Data+ license.

Getting started

To successfully use the API, you might want to learn more about the Commonly used  metadata.

Working with Matlab API

Time series

A time series is represented by the ISeries interface, described below. A time series consists of a vector of values, a calendar, and a set of metadata.

The vector of values consists of floating-point values. A missing value is represented by a NaN. To test if a value is a NaN in MATLAB use the method isnan(value). To represent a NaN you can use the constant NaN. Note! You must never use the constant to compare if a value is NaN; always use isnan(value) to test if a value is NaN.

A missing value typically means that a value was expected, but it is missing for some reason. When you do a unified series request, you have the option of specifying what method, if any, that should be used to fill in missing values.

The calendar is exposed as lists of dates as well as a couple of methods to go between index in the list of values and a date. Each time series has a frequency and a start date. Daily series also have information about what weekdays that are covered. In addition to this, certain dates can be skipped.  This is mostly used for daily series when there is a holiday or other day when the market is closed. It is not common, but you may find skipped dates in series of other frequencies too. For instance, some Chinese monthly data is not reported for February and this month is then skipped.

Handling of dates

There is no data type for dates in MATLAB. Instead MATLAB uses a convention to store dates as a number calculated from start date. When passing a value to and from COM, which has a specific type for dates, there is no way for MATLAB to know if the number is just a number or should be interpreted as a date. For this purpose, there is a helper object in MATLAB called COM.date.

When passing data to the Macrobond API and the API expects a date, but gets a number instead, this is interpreted as a MATLAB date. This means that you can pass a date created by any of these two methods:

startDate = COM.date(1980, 11, 30)
startDate = datenum(1980, 11, 30)

However, when a date is returned from the API the date must be converted to a MATLAB date number by using the datenum method and the date format pattern defined in Windows regional settings on your computer. In this sample, it is assumed Windows is configured with the date format 'yyyy-mm-dd'. Other common formats are 'mm/dd/yyyy' and 'dd/mm/yyyy'.

matlabDate = datenum(s.StartDate, 'yyyy-mm-dd')

Note! If you do not convert dates passed from COM in this manner, MATLAB will convert them to strings. However, the string format used by MATLAB in this case, is for some reason based on your Windows date format settings, which is not always compatible with the format accepted by MATLAB functions such as datenum(string).

Interfaces

IConnection

All interaction with the Macrobond starts with an instance of the Connection object which is access through the IConnection interface. You create an instance of the object like this:

c = actxserver('Macrobond.Connection')

The interface contains the following methods and properties:

IDatabase Database This property returns a reference to the database interface.
Close() Call this method if you want to free all resources used by the Macrobond API. Opening and closing sessions can be slow, so it is usually not a good idea to open and close them for each request.

IDatabase

This interface allows you to interact with the Macrobond database.

ISeries FetchOneSeries(string seriesName) Download one series from the database.
ISeries[] FetchSeries(VARIANT seriesNames) Download one or more series from the database. The parameter can be a string, a vector of series names or an object created by CreateUnifiedSeriesRequest(). The result is a vector of series in the same order as requested.
IEntity FetchOneEntity(string entityName) Download an entity, such as a Release.
IEntity[] FetchEntities(VARIANT entityNames) Download one or more entities from the database. The parameter can be a string or a list of entity names. The result is a vector of entities in the same order as requested.
ISeriesRequest CreateUnifiedSeriesRequest() Create a request of one or more series where the resulting time series will be converted to a common length and calendar. You can specify frequency, currency, date range, missing value, and frequency conversion methods
ISeries CreateSeriesObject(string name, string description, string region, string category, SeriesFrequency frequency, SeriesWeekdays dayMask, VARIANT startDateOrDates, VARIANT values, IMetadata metadata) Create a series object that can be uploaded to the server using the UploadOneOrMoreSeries method.
The startDateOrDates can either be just one start date or one date for each value.
The values should be an array of numbers.
The metadata parameter is optional.
The region is a value of the Region metadata which is based on the 2 letter ISO for countries. See list here.
The name should be of the form 'ih:storage:id', where storage is 'priv', 'dept' or 'com' corresponding to the private, department and company storages. It must be a unique identifier per storage
ISeries CreateSeriesObjectWithForecastFlags(string name, string description, string region, string category, SeriesFrequency frequency, SeriesWeekdays dayMask, VARIANT startDateOrDates, VARIANT values, VARIANT forecastFlags, IMetadata metadata) Create a series object that can be uploaded to the server using the UploadOneOrMoreSeries method.The startDateOrDates can either be just one start date or one date for each value.
The values should be an array of numbers.
The forecastFlags should be an array of boolean values where true means that the corresponding value is a forecast.
The metadata parameter is optional.
The region is a value of the Region metadata which is based on the 2 letter ISO for countries. See list here.
The name should be of the form 'ih:storage:id', where storage is 'priv', 'dept' or 'com' corresponding to the private, department and company storages. Id should must be a unique identifier per storage.
UploadOneOrMoreSeries(VARIANT series) Upload one or more series created by the CreateSeriesObject method. The parameter can be a single series or a list of series. It is more efficient to upload more series at once than one by one.
DeleteOneOrMoreSeries(VARIANT nameOrNames) Delete one or more series. The parameter can be a single series name or a list of names. It is more efficient to delete more than one series at once than one by one.
IMetadata CreateEmptyMetadata() Create an empty set of metadata. The content can be changed until it is used in a series.
IMetadata CreateDerivedMetadata(IMetadata metadata) Create a set of metadata derived from another set. The content can be changed until it is used in a series.
IMetadataInformation GetMetadataInformation(string name) Get information about a type of metadata.
ISearchQuery CreateSearchQuery() Create a search query object. Set properties on this object and pass it to the Search function in order to search for series and other entities.
(Requires Data+ license.)
ISearchResult Search(ISearchQuery query) Execute a search for series and other entities.
(Requires Data+ license.)
ISeriesWithRevisions FetchOneSeriesWithRevisions(string name) Download one revision history for one series.
(Requires Data+ license.)
ISeriesWithRevisions[] FetchSeriesWithRevisions(VARIANT seriesNames) Download one or more series from the database. The parameter can be a string or a vector of series names. The result is a vector of revision history objects in the same order as requested.
(Requires Data+ license.)

Downloading series

You can select from two modes when downloading series:

  • Download raw data. All available data will be made available without any conversion. You do this by calling FetchOneSeries or FetchSeries with one or more series names (strings).
  • Download unified data. You can specify frequency, currency, date range, missing value, and frequency conversion methods. When more than one series is downloaded, they will all have the same calendar. This means that they will have equal length, the same frequency and that a specific index in the vector or values corresponds to the same point in time for all the series. This type of download is made by creating a request object by calling CreateUnifiedSeriesRequest().

Download one series

This will download the entire time series usgdp without any transformations.

c = actxserver('Macrobond.Connection')
d = c.Database
s = d.FetchOneSeries('usgdp')

You can also use one of the ratio expressions to when downloading series. Here the usgdp series is expressed per capita.

c = actxserver('Macrobond.Connection')
d = c.Database
s = d.FetchOneSeries('#PerCapita(usgdp)')

After any of the above you should use its Values property to retrieve the values with:

values = s.Values
dates = datenum(s.DatesAtStartOfPeriod, 'yyyy-mm-dd')

Download several series

This will download the entire time series usgdp and uscpi without any transformations. It is faster to download several series in one call rather than one by one.

c = actxserver('Macrobond.Connection')
d = c.Database
listOfSeries = d.FetchSeries({'usgdp', 'uscpi'})
seriesUsgdp = listOfSeries{1}
seriesUscpi = listOfSeries{2}

Download and transform series

This will download the entire time series usgdp and uscpi transform them to a common length and calendar. By default, the highest frequency of the series and the union on the ranges will be used. For more examples, see the documentation about the ISeriesRequest interface.

c = actxserver('Macrobond.Connection')
d = c.Database
r = d.CreateUnifiedSeriesRequest()
r.AddSeries('usgdp')
r.AddSeries('uscpi')
listOfSeries = d.FetchSeries(r)

Create and upload a monthly series

This creates a monthly time series. Since just one data is specified, this will be the start date of the series and the rest of the dates will be implicitly calculated based on the frequency.

c = actxserver('Macrobond.Connection')
d = c.Database
m = d.CreateEmptyMetadata()
startDate = COM.date(1980, 1, 1)
values = { 12.2, 12.7, 12.8, 13.0 }
s = d.CreateSeriesObject('ih:mb:priv:s1', 'My forecast', 'us', 'Forecasts', 'SeriesFrequency_Monthly', 'SeriesWeekdays_MondayToFriday', startDate, values, m)
d.UploadOneOrMoreSeries(s)

Create and upload a daily series

This will create a daily time series. In this case we have chosen to specify the date for each observation. Please note that the 5th and 6th of January 1980 are Saturday and Sunday and will not be included in the series since it is set to use Monday-Friday. The 7th is not included in the list of dates, so this date will be skipped in the calendar.

c = actxserver('Macrobond.Connection')
d = c.Database
m = d.CreateEmptyMetadata()
dates = { COM.date(1980, 1, 2), COM.date(1980, 1, 3), COM.date(1980, 1, 4), COM.date(1980, 1, 8) }
values = { 12.2, 12.7, 12.8, 13.0 }
s = d.CreateSeriesObject('ih:mb:priv:s1', 'My forecast', 'us', 'Forecasts', 'SeriesFrequency_Daily', 'SeriesWeekdays_MondayToFriday', dates, values, m)
d.UploadOneOrMoreSeries(s)

Delete a series

c = actxserver('Macrobond.Connection')
d = c.Database
d.DeleteOneOrMoreSeries('ih:mb:priv:s1')

Search for series using a 'concept'

This example only works with Data+ license.

This example searches for time series that are defined by Macrobond as the GDP series for the regions 'us', 'gb' and 'cn'. The RegionKey attribute defines what is called a 'concept' and is used to build the 'Concept & Category' database view in Macrobond Application. It is a powerful way to identify corresponding series for many regions. For the GDP series, the RegionKey is 'gdp_total.'

c = actxserver('Macrobond.Connection')
d = c.Database
query = d.CreateSearchQuery()
query.SetEntityTypeFilter('TimeSeries')
query.AddAttributeValueFilter('RegionKey', 'gdp_total')
query.AddAttributeValueFilter('Region', {'us', 'gb', 'cn'})
result = d.Search(query).Entities

Find the 'concept' from a time series

This example shows how you can find out what 'concept' or RegionKey a series is associated with. Far from all series have this classification, but we know that the uscpi series has . This is a good way to find out the names of RegionKeys to use when searching for data.

c = actxserver('Macrobond.Connection')
d = c.Database
query = d.CreateSearchQuery()
query.SetEntityTypeFilter('TimeSeries')
query.AddAttributeValueFilter('RegionKey', 'gdp_total')
query.AddAttributeValueFilter('Region', {'us', 'gb', 'cn'})
result = d.Search(query).Entities

ISeries

This interface represents a Macrobond time series.

string Name The name of the series.
bool IsError If True, then the series request resulted in an error and the ErrorMessage property contains an error message. If there is an error, only these two properties are valid.
string ErrorMessage Contains an error message if IsError is True.
string Title The title of the series.
IMetadata Metadata Metadata information for the time series.
double[] Values A list of all values in the time series. The COM data type is SAFEARRAY(VT_R8)
VARIANT[] DatesAtStartOfPeriod A list of dates. There is one date for the start of the period for each value in Values. The COM data type is VT_SAFEARRAY|VT_DATE.
VARIANT[] DatesAtEndOfPeriod A list of dates. There is one date for the end of the period for each value in Values. The COM data type is VT_SAFEARRAY|VT_DATE.
bool[] ForecastFlags A list flags where a value is True if the corresponding value in Values is a forecast.
date StartDate The date of the first observation of the time series.
date EndDate The date of the last observation of the time series.
SeriesFrequency Frequency The series frequency.
SeriesWeekdays Weekdays A bit field of weekdays to use for daily time series.
double GetValueAtDate(date d) Get the value at or preceding a specific date.
int GetIndexAtDate(date d) Get the zero-based index of the value at or preceding the specified date in the Value list.
double TypicalObservationCountPerYear The typical number of observations per year based on the frequency of the series.

Get the values of a series

This will download the time series usgdp and the list of values as well as a list of MATLAB 'datenums'. Please note that the date format pattern passed as an argument to datenum function must match the regional settings in Windows.

c = actxserver('Macrobond.Connection')
d = c.Database
s = d.FetchOneSeries('usgdp')
values = s.Values
dates = datenum(s.DatesAtStartOfPeriod, 'yyyy-mm-dd')

IEntity

This interface represents a Macrobond entity. There are many types of entities in the Macrobond database. Examples are Source, Release, Company and Security. Time series are also entities.

The reason you might want to download an entity, is to obtain some metadata.

string Name The name of the entity.
bool IsError If True, then the entity request resulted in an error and the ErrorMessage property contains an error message. If there is an error, only these two properties are valid.
string ErrorMessage Contains an error message if IsError is True.
string Title The title of the entity.
IMetadata Metadata Metadata information for the entity.

Get the next release time

This will download the time series usgdp and then download the corresponding release entity. The release entity can contain metadata about the when time series associated with this release is scheduled to be updated.

c = actxserver('Macrobond.Connection')
d = c.Database
s = d.FetchOneSeries('usgdp')
releaseName = s.Metadata.GetFirstValue('Release')
if (not(isnan(releaseName)))
 r = d.FetchOneEntity(releaseName)
 nextReleaseTime = datenum(r.Metadata.GetFirstValue('NextReleaseEventTime'), 'yyyy-mm-dd')
end

IMetadata

This interface represents a set of metadata for a time series or entity.

Metadata is represented by a name and a value. The type of the value can be a string, a boolean, an integer or a date. An examples of a metadata names are 'Region' and 'Currency.' Some metadata can have multiple values, like Region, but others, Currency, can have only one value.

VARIANT GetFirstValue(string name) Get the first metadata value with the specified name.
VARIANT[] GetValues(string name) Get a list of the values for metadata of the specified name.
VARIANT[,] ListNames() Get a list of all the metadata specified together with a description for each name.
bool IsReadonly Indicating whether new values can be added or hidden in this instance. Typically, only newly created instances of the metadata objects can be edited and only until they have been used in a series.
AddValue(string name, VARIANT value) Add a value to the metadata instance. The value can be a single value or a list of values.
HideValue(string name) Hide a value inherited from a parent metadata collection.

You can find more information on this page: Commonly used metadata.

Get the currency of a time series

c = actxserver('Macrobond.Connection')
d = c.Database
s = d.FetchOneSeries('usgdp')
m = s.Metadata
currencyCode = m.GetFirstValue('Currency')

Create and upload a series and specify the currency

c = actxserver('Macrobond.Connection')
d = c.Database
m = d.CreateEmptyMetadata()
m.AddValue('Currency', 'sek')
startDate = COM.date(1980, 1, 1)
values = { 12.2, 12.7, 12.8, 13.0 }
s = d.CreateSeriesObject('ih:mb:priv:s1', 'My forecast', 'us', 'Forecasts', 'SeriesFrequency_Daily', 'SeriesWeekdays_MondayToFriday', startDate, values, m)
d.UploadOneOrMoreSeries(s)

ISeriesRequest

Use this interface to set up a request of unified series. You create objects with this interface by calling IDatabase.CreateUnifiedSeriesRequest(). Then you configure the object and pass it as a parameter to IDatabase.FetchSeries().

ISeriesExpression
AddSeries(string name)
Add a series to the list of series to request. You can optionally use the returned interface to do further configurations, such as methods for missing value, and frequency conversion.
ISeriesExpression
[] AddedSeries
A list of the added series.
SeriesFrequency Frequency The frequency that all series will be converted to. The default value is ‘Highest’, which means that all series will be converted to the same frequency as the series with the highest frequency.
CalendarMergeMode
CalendarMergeMode
Determines how to handle points in time that are not available in one or more series. The default value is ‘AvailibleInAny’
SeriesWeekdays Weekdays This determines what days of the week that are used when the resulting frequency is Daily and the CalendarMergeMode is ‘FullCalendar’.
string Currency The currency code based on the three letter IS 4217 codes that will be used to convert any series expressed in currency units. The default is an empty string, which means that no currency conversion will be done. There is a list of the supported currencies on a Currencies List web page.
CalendarDateMode StartDateMode Determines if the automatic start of the series is at the first point when there is data in any series or the first point where there is data in all series. The default is ‘DataInAnySeries’. This setting is not used when the StartDate property is set to an absolute point in time.
VARIANT StartDate This specifies the start date used for all the series in the request. The value can be empty, a specific date or a string representing a point in time as described below. If it is empty or a relative reference, the StartDateMode will be used to determine the start.
CalendarDateMode EndDateMode Determines if the automatic end of the series is at the last point when there is data in any series or the last point where there is data in all series. The default is ‘DataInAnySeries’. This setting is not used when the EndDate property is set to an absolute point in time.
VARIANT EndDate This specifies the end date used for all the series in the request. The value can be empty, a specific date or a string representing a point in time as described below. If it is empty or a relative reference, the EndDateMode will be used to determine the end.

For the StartDate and EndDate properties, you can specify a string representing a point in time. This can either be an absolute reference on the form 'yyyy,' 'yyyy-mm' or 'yyyy-mm-dd' or a reference relative the last observation of the series based on these examples:

-50 Fifty observations before the last available observation.
+40 Forty observations after the last available observation.
-2y Two years before the last available observation.
-1q One quarter before the last available observation.
-4m Four months before the last available observation.
-3w Three weeks before the last available observation.
-5d Five days before the last available observation.

Download and set start year

This will download two series and convert them to the higher frequency. The data range is set to start year 1980 and continue until the last observation that has data in both series.

c = actxserver('Macrobond.Connection')
d = c.Database
r = d.CreateUnifiedSeriesRequest()
r.AddSeries('usgdp')
r.AddSeries('uscpi')
r.StartDate = '1980'
r.EndDateMode = 'CalendarDateMode_DataInAllSeries'
listOfSeries = d.FetchSeries(r)

Download and convert currency

This will download two series and convert them to USD. The data range is set to cover the range where there is data in both series.

c = actxserver('Macrobond.Connection')
d = c.Database
r = d.CreateUnifiedSeriesRequest()
r.AddSeries('usgdp')
r.AddSeries('gbgdp')
r.Currency = 'USD'
r.StartDateMode = 'CalendarDateMode_DataInAllSeries'
r.EndDateMode = 'CalendarDateMode_DataInAllSeries'
listOfSeries = d.FetchSeries(r)

ISeriesExpression

Use this interface to set properties for a series requested by calling ISeriesRequest.AddSeries().

string Name The name of the series
SeriesMissingValueMethod
MissingValueMethod
The method to use when filling in any missing values in this series. The default is ‘Auto’.
SeriesToLowerFrequencyMethod
ToLowerFrequencyMethod
The method to use when converting this series to a lower frequency. The default is ‘Auto’.
SeriesToHigherFrequencyMethod
ToHigherFrequencyMethod
The method to use when converting this series to a higher frequency. The default is ‘Auto’.
SeriesPartialPeriodsMethod
PartialPeriodsMethod
The method to use for partial periods at the ends of the series when converting to a lower frequency. The default is None.

Download and convert without filling in missing values

This will download two series and convert them to the same calendar, but do not fill in any missing values.

c = actxserver('Macrobond.Connection')
d = c.Database
r = d.CreateUnifiedSeriesRequest()
r.AddSeries('usgdp').MissingValueMethod = 'SeriesMissingValueMethod_None'
r.AddSeries('gbgdp').MissingValueMethod = 'SeriesMissingValueMethod_None'
listOfSeries = d.FetchSeries(r)

IMetadataInformation

Use this interface to get information about a type of metadata.

string Name The name of the metadata type
string Description A description of the metadata type.
string Comment A comment about the metadata type.
bool UsesValueList If True, then this type of metadata uses a list of possible values and only values from that list can be used. The list can be obtained from ListAllValues. Information about a specific value can be found by calling GetValueInformation().
MetadataValueType ValueType Get the datatype of the values for this type of metadata.
bool CanHaveMultipleValues If True, then a metadata collection can have several values of this type.
bool IsDatabaseEntity If True, then this value corresponds to an entity in the database that can be retrieved by IDatabase.FetchOneEntity().
string GetValuePresentationText(VARIANT value) Format a value as a presentable text.
IMetadataValueInformation GetValueInformation(VARIANT value) Get information about a metadata value. This information is only available for metadata types that uses value lists
IMetadataValueInformation[] ListAllValues() Get a list of all possible values for a metadata type that uses a value list.
bool CanListValues If True, then the possible values can be listed using the ListAllValues function.

Get the presentation text for a region code

This will get information about the metadata type called ‘Region’ and then get the presentation text for the region called ‘us’. The result will be the string ‘United States’.

c = actxserver('Macrobond.Connection')
d = c.Database
m = d.GetMetadataInformation('Region')
description = m.GetValuePresentationText('us')

IMetadataValueInformation

Use this interface to get information about a value of metadata.

VARIANT Value The value of the metadata
string Description The description of the value.
string Comment A comment about the value.

Get a list of all currencies

This will get information about the metadata type called 'Region' and then get the presentation text for the region called 'us'. The result will be the string 'United States'.

c = actxserver('Macrobond.Connection')
d = c.Database
m = d.GetMetadataInformation('Currency')
v = m.ListAllValues()
currencies = cellfun(@(x) x.Value, v, 'UniformOutput', 0)

ISearchQuery

This example only works with Data+ license.

Use this interface to set up a search query. You create objects with this interface by calling IDatabase.CreateSearchQuery(). Then you configure the object and pass it as a parameter to IDatabase.Search().

string Text An optional text to search for. The search will be made by matching each word.
SetEntityTypeFilter(VARIANT types) A single string or a vector of strings identifying what type of entities to search for. The options are TimeSeries, Release, Source, Index, Security, Region, RegionKey, Exchange and Issuer.
Typically you want to set this to TimeSeries. If not specified, the search will be made for several entity types.
AddAttributeFilter(string attributeName, bool include = true) Add a name of an attribute that must or must not be set on entities returned by the search. The 'include' parameter determines if the search should include or exclude entities that have the attribute.
For example, if you do AddAttributeFilter("SeasonAdj"), only series that are seasonally adjusted will be included.You can call this method several times to add more filters.
AddAttributeValueFilter(string attributeName, VARIANT attributeValues, bool include = true) Add attribute values that must or must not be set on entities returned by the search. You can specify one value or a list of values. The 'include' parameter determines if the search should include or exclude entities that have the attribute values.

For example, if you do AddAttributeValueFilter("Region", ["us", "gb", "cn"]) only entities that have the Region attribute set to any of "us", "gb" or "cn" will be included.

You can call this method several times to add more filters.

bool IncludeDiscontinued Set to True to include discontinued series in the search. The default is False.

ISearchResult

This example only works with Data+ license.

This interface represents a search result returned by a call to IDatabase.Search(query).

IEntity[] Entities The list of entities returned by the search.
bool IsTruncated This is True if the result is not exhaustive. There is a limit on the number of entities that can be returned. It is possible to get at least 2000 entities before the result is truncated.

ISeriesWithRevisions

These examples only works with Data+ license.

This interface represents a time series with revision history.

The series returned by Head, GetNthRelease, GetVintage and GetCompleteHistory will all be of equal length and share the same calendar. In this way they can easily be used in a data frame.

bool IsError If True, then the series request resulted in an error and the ErrorMessage property contains an error message. If there is an error, only these two properties are valid.
string ErrorMessage Contains an error message if IsError is True.
bool HasRevisions If True, then the series has one or more revisions.
bool StoresRevisions If True, then the series stores revision history. This can be True while HasRevisions is False if no revisions have yet been recorded.
datetime TimeOfLastRevision The timestamp of the last revision.
ISeries Head The current revision of the time series.
ISeries GetNthRelease(int n) Get then nth revision of each value. GetNthRelease(0) will return the first release of each value.
Values that have not been revised the number of times specified and value for which the complete revision history is not known will be represented by NaN.The series ValuesMetadata will contain the metadata attribute RevisionTimeStamp with the timestamp when the revision was made to that value.
ISeries GetVintage(datetime time) Get the series as it looked at the time specified.
The metadata attribute RevisionTimeStamp will contain the timestamp of when this revision was recorded.In order to make this series of the same length as the Head series, it may be padded with NaN.
ISeries GetObservationHistory(date d) Get a daily series with the revision history of the value specified by the date.
ISeries[] GetCompleteHistory() Get list of all revisions.

Each time series has the metadata attribute RevisionTimeStamp with the timestamp the revision. The first series typically has date 1899-12-30 which means that the timestamp of the original data is not known.

Please note that this can potentially be a lot of data and use a large amount of memory.

datetime[] GetVintageDates() Get a list of timestamps representing when revisions were recorded.

Get all available revisions

c = actxserver('Macrobond.Connection');
d = c.Database;
s = d.FetchOneSeriesWithRevisions("uscpi");
history = s.GetCompleteHistory();

Get revision history for original and first release

c = actxserver('Macrobond.Connection');
d = c.Database;
s = d.FetchOneSeriesWithRevisions("uscpi");
firstRevisionSeries = s.GetNthRelease(0);
secondRevisionSeries = s.GetNthRelease(1);

Get series for selected timestamp

c = actxserver('Macrobond.Connection');
d = c.Database;
seriesWithRevisions = d.FetchOneSeriesWithRevisions('usgdp');
s = seriesWithRevisions.GetVintage('2021-04-02 00:00:00');

SeriesFrequency

This enumeration contains the supported time series frequencies.

Annual Once a year.
SemiAnnual Twice a year.
QuadMonthly Once in 4 months.
Quarterly Once in 3 months
BiMonthly Every second month.
Monthly Once a month.
Weekly Once a week
Daily Once a day.
Lowest When specified in a series request, this corresponds to the lowest frequency of the series in set.
Highest When specified in a series request, this corresponds to the highest frequency of the series in the request.

SeriesWeekdays

This enumeration contains flags that are used as bitmasks to determine what weekdays that are used in a daily time series.

Sunday 1
Monday 2
Tuesday 4
Wednesday 8
Thursday 16
Friday 32
Saturday 64
FullWeek Sun+Mon+Tue+Wed+Thu+Fri+Sat
MondayToFriday Mon+Tue+Wed+Thu+Fri
SaturdayToThursday Sun+Mon+Tue+Wed+Thu+Sat
SaturdayToWednesday Sun+Mon+Tue+Wed+Sat
SundayToThursday Sun+Mon+Tue+Wed+Thu
MondayToThursdayAndSaturday Sun+Mon+Tue+Wed+Thu+Sat

CalendarMergeMode

This enumeration defines how calendars are merged into one calendar when there are time periods missing in one or more series. Please note that missing time period is not the same thing as a missing value. A time period is missing in cases when there should be no observation such as on a holiday. A missing value, on the other hand, is a special value in the time series that indicates that there should have been a value, but it is unknown for some reason.

FullCalendar Use all the time periods as specified by the frequency and weekdays.
AvailableInAll Use the time periods that are available in all series.
AvailableInAny Use the time periods that are available in any series.

CalendarDateMode

This enumeration defines how the StartDate and EndDate properties of a unified series request are interpreted when they are set to a relative or empty reference.

DataInAnySeries Use the first or last time period where there is valid data in any series.
DataInAllSeries Use the first or last time period where there is valid data in all series.

SeriesMissingValueMethod

This enumeration determines the method for filling in any missing values.

None Do not fill in missing values. They will remain NaN in the value vector.
Auto Determine the method based on the series classification.
PreviousValue Use the previous non-missing value.
ZeroValue Use the value zero.
LinearInterpolation Do a linear interpolation between the previous and next non-missing values.

SeriesToLowerFrequencyMethod

This enumeration determines the method for converting a series to a lower frequency.

Auto Determine the method based on the series classification.
Last Use the last value of the time period.
First Use the first value of the time period.
Flow Aggregate the values of the time period.
PercentageChange Aggregate the percentage change over the period.
Highest Use the highest value in the time period.
Lowest Use the lowest value of the time period.
Average Use the average value of the period.

SeriesToHigherFrequencyMethod

This enumeration determines the method for converting a series to a higher frequency.

Auto Determine the method based on the series classification.
Same Use the same value for the whole period.
Distribute Use the first value of the time period.
PercentageChange Distribute the percentage change over the period.
LinearInterpolation Use a linear interpolation of the values from this to the next period.
Pulse Use the value for the first value of the period.
QuadraticDistribution Use quadratic interpolation to distribute the value over the period.
CubicInterpolation Use a cubic interpolation of the values from this to the next period.

SeriesPartialPeriodsMethod

This enumeration determines the method for converting a series with partial periods.

None Do not include partial periods.
Auto Determine the method based on the series meta data.
RepeatLastValue Fill up the partial period by repeating the last value.
FlowCurrentSum Fill up the partial period with the average of the incomplete period.
PastRateOfChange Use the rate of change from the previous year to extend the partial period.
Zero Fill up the partial period with zeroes.

MetadataValueType

The type of a metadata value. These values correspond to the COM VARIANT data types.

Int A 32-bit signed integer. VT_I4.
Double A 64-bit floating point number. VT_R8.
Date A date. VT_DATE.
String A unicode string. VT_BSTR.
Bool A boolean value where -1 is True and 0 is False. VT_BOOL.

The Macrobond EViews add-in

Introduction

With the Macrobond add-in for EViews you can load series from the Macrobond database, and you can store series to the Macrobond account in-house database from EViews.

Requirements

You need to have Macrobond and EViews 7.2 Enterprise Edition (Apr 29, 2011 build) or later. Note that only EViews Enterprise Edition can connect to external data sources - other versions of EViews won't be able to connect due to EViews restrictions regarding 3rd party vendors. Since E-Views 14 there is only one Edition. If you are running the 64-bit version of EViews, you need the 64-bit version of Macrobond.

This API can be used only with Legacy or Data+ license.

Getting started

The first time you start EViews after installing the required versions of both Macrobond and EViews, you will be asked if you want to register the Macrobond add-in. To be able to use the add-in, you should answer Yes to this question
eViews - 1
Once the Macrobond add-in is registered, you will see the Macrobond Database in the list of databases shown when you select File|Open|Database in EViews:
eViews - 2
To open the database, just press OK in this dialog

Working with EViews add-in

Manually registering and unregistering the add-in

The Macrobond add-in  by default registers automatically but in case it fails, you can manually register add-in for EViews by executing this command in EViews:

edxadd Abacus.EViewsDBManager

You can unregister the add-in with this command:

edxdrop Abacus.EViewsDBManager

Reading data into EViews

You can add series to the list of series presented in the Macrobond database window in EViews by pressing the Browse or Browse-append buttons. These commands will display the Macrobond 'Select time series' dialog:
eViews - 3
You can pick one or more series to add to your database view in EViews.
eViews - 4
You can now work with these series like series from any other external data source in EViews. The most common operation is to export them to a Workfile. You can do this from the Object or context menu in EViews.

Vintage data (revision history)

Unfortunately, there is currently no way to access revision history in EViwes.

Storing data from EViews

You can store time series in EViews to the 'Account in-house database' in Macrobond. The time series will then be available in the Macrobond application.

To store a time series you can do 'Store to DB…' from the Object menu or context menu when you have selected a time series in EViews. You may also use drag and drop and drop the series in a Macrobond Database window in EViews.

If more information is required in order to store the series in Macrobond, a dialog like this will be displayed:
eViews - 5
When all information is filled in and you press OK, the series will then be stored.

In order to avoid this dialog, which is useful when automating tasks, you can complement the series in EViews with some additional attributes: Name, Macrobond_category, Macrobond_region, Macrobond_ihdatabase. See section Labels below. No dialog will be displayed when all these attributes are present.

In EViews you can specify these attributes in the View|Label view of a series:
eViews - 6
Note: You enter new labels on the empty line above the 'Remarks:' label.

You can see hints for these attributes in the dialog where you enter complementary series information:
eViews - 7
If you have the Macrobond application running when you save a new series to the Macrobond database in EViews, you might need to press the refresh button in Macrobond in order to see the new series in the list.

Labels

The following labels are used by the Macrobond add-in:

Name The name of the series in Macrobond.
Description This is the description of the series in Macrobond.
Remarks A comment about the series.
Convert_HiLo
Convert_LoHi
For series that have Class = "Flow", these are Convert_HiLo=sum and Convert_LoHi=const_s. Otherwise they are Convert_HiLo=last and Convert_LoHi=const_a.
Macrobond_category The Macrobond category of the series. For example, the value could be "Wages".
Macrobond_region The country or region code of the series when stored in Macrobond. This must be an existing region. The codes are based on two letter ISO 3166 codes. You can find a complete list of the supported regions at https://www.macrobond.com/go/regionList.
Macrobond_ihdatabase This attribute tells Macrobond where the series is stored. It can be 'mb:priv', 'mb:com' or 'mb:lib'.
Macrobond_forecaststartdate If present, all values from this date forward are forecasts. The date format is yyyy-MM-dd. For example: 2012-06-15
Macrobond_releasestage If present, indicates the status of the last value in the series. Can be one of advance, preliminary or final.
Macrobond_currency The currency of the series, if any. This is the three letter ISO 4217 code. You can get a list of the supported countries at The Currency List
Last_update If present, indicates when the series was last updated. The format is yyyy-MM-ddTHH:mm:ss. For example: 2012-08-20T15:00:00
Next_update If present, indicates when the series is scheduled to be updated the next time. The format is yyyy-MM-ddTHH:mm:ss. For example: 2012-08-20T15:00:00
Source The source of the data.
Units The unit of the data.

Using EViews commands

You can use commands in EViews to download series from any source, including Macrobond. Assuming that you have defined a database alias called 'mb' for the Macrobond database, you can use a command like this:

fetch(d=mb) gold

or

fetch mb::gold

You can download several series with one command:

fetch(d=mb) gold silver

In order to be able to update the series in the workbook you need to create a link:

fetch(d=mb,link) gold

If the Macrobond series name contains spaces, you need to put the identifier within quotes. For example, to download a series from Bloomberg:

fetch(d=mb,link) "ih:bl:ibm us equity"

To store a time series you use the EViews 'store' command, which works in a similar way to 'fetch':

store(d=mb) myseries1

To set labels, you use the 'label' function:

myseries1.label(Macrobond_region) us
myseries1.label(Macrobond_category) Wages
myseries1.label(Macrobond_ihdatabase) mb:priv
store(d=mb) myseries1

The Macrobond Bloomberg Connector

Introduction

With the Macrobond Bloomberg Connector you can retrieve historical time series from Bloomberg if Bloomberg Terminal is installed and running on your computer.

The application determines the start date and frequency automatically. The highest supported frequency is daily data, and the earliest start date is 1930-01-01.

Requirements

Please note that the product Bloomberg Anywhere, which is a lightweight version of Bloomberg Terminal, does not come with the API needed by the Macrobond Bloomberg Connector. You need to run the installed version of Bloomberg Terminal for the connector to work.

Enabling the Bloomberg Connector

To be able to use the Bloomberg connector, it must be enabled in the Macrobond application. This is done on the Configuration (in upper menu) > Settings > tab 'My series' (for MB pre-1.28: Edit > Settings > tab 'My series'):

Working with Bloomberg Connector

Series names

Series names for the Bloomberg connector, in their simplest form, are specified as "ih:bl:symbol". Note, if the BBG symbol has ' : ' in it (i.e., CL 1 N:00_0_N_Comdty) should be written as"ih:bl:c 5 a::00_0_N Comdty:PX_LAST", with two colons inside symbol.

The symbol is a Bloomberg symbol. The default format for Bloomberg symbols is the Bloomberg ticker followed by the 'yellow key'. An example of a Bloomberg symbol is IBM US Equity and the series name to enter in Macrobond would then be "ih:bl:IBM US Equity". When you use this as a series name in the Series List you need to specify the quotes around the name since it contains spaces.

A name without a specific field specified will refer to the field PX_LAST. The full format of the name is "ih:bl:symbol:field:override1=value1:override2=value2", where the field and the list of overrides are optional.

Here is an example the uses another field than PX_LAST: "ih:bl:IBM US Equity:BEST_EPS".

You may optionally append one or more 'overrides' to the name. For example: "ih:bl:nky Index:BEST_PE_RATIO:eqy_consolidated=N".

Bloomberg have some variations on their symbol codes. For instance, you can include the pricing source as in "ih:bl:MSFT@ETPX US Equity".

You may also use other symbol schemas than the Bloomberg ticker format. For example: "ih:bl:/cusip/912828GM6@BGN".

Please consult the Bloomberg documentation for further information on the symbol format, field names and overrides.

Entering Bloomberg symbols in the Series browser

To make it easier to enter Bloomberg symbols and to use such series together with the Action command bar, you can select Bloomberg in the Series browser. This allows you to type in the Bloomberg symbols and look them up.

You may include the 'yellow key' ('Equity', 'Index' etc.) at the end of the symbol. If it is not included, the Macrobond application will try all the keys and present all series found.

If you want some other field than PX_LAST, you may include it like in this example:

IBM US:BEST_EPS

You can also find below a non-exhaustive list of Bloomberg field codes:

Ask Price  PX_ASK
Bid Price PX_BID
High Price PX_HIGH
Last trade/Last price LAST_PRICE
Low Price PX_LOW
Mid Price PX_MID
Open Price PX_OPEN
Option Price OPT_PX
Settlement Price PX_SETTLE
Strike Price STRIKE_PX
Best EV/EBITDA TO_EBITDA
Best P/E Ratio PE_RATIO
Closing Price 1 Day Ago CLOSE_1D
Contract value CONTRACT_VALUE
Current Enterprise Value ENTP_VAL
Enterprise Value ENTERPRISE_VALUE
Enterprise Value (EV) to Book Value BOOK_VALUE
Estimated P/E Nest Year Aggregate YR_AGGTE
Net Asset Value (NAV) ASSET_VAL
Price to Book Ratio BOOK_RATIO
P/E ratio PE_RATIO
Total market Value TOT_MKT_VAL MKT_VAL
Volume VOLUME
Volatility 30 day VOLATILITY_30D
VWAP (Vol Weighted Average Price) AVG_PX
Yesterday Close Price YEST_CLOSE

Using Bloomberg 'overrides'

Bloomberg has a system for specifying additional parameters in historical data requests that can affect the series returned. An override can look like this: Eqy_Consolidated=N.

As explained above you can specify such overrides when writing the series names in Macrobond. These the same overrides as you can specify in the Bloomberg BDH Excel function. In the BDH function there are, however, some parameters that look like 'overrides', but they are technically not. Some of these are also supported in the Macrobond application:

QtTyp Price/Yield quote. Valid values are “P” (price) and “Y” (yield). The default is “Y”.
Quote Quote calculation. Valid values are “A” (average) and “C” (close). The default is “C”.
CshAdjNormal Cash Adjustment Normal. Valid values are “Y” (yes) and “N” (no). The default is “N”.
CshAdjAbnormal Cash Adjustment Abnormal. Valid values are “Y” (yes) and “N” (no). The default is “N”.
CapChg Capital Changes. Valid values are “Y” (yes) and “N” (no). The default is “N”.
Curr Currency conversion. Valid values are ISO codes such as “USD” and “GBP”.

For further details, please see the Bloomberg documentation.

Bloomberg Connector Enhancement

In the Bloomberg series provider, visible below, you can paste Bloomberg Excel BDH expressions, and the application will suggest a time series.

For example, you can use:

=BDH("goog us equity","EBIT","1/1/2005","12/31/2009","per=cy")

Note that it won't work for =BDP or =BDS.

Troubleshooting

If you get an error like 'Unknown series prefix' when trying to specify a Bloomberg series in the Series List, please verify that the Bloomberg connector has been enabled in Macrobond as described in the section 'Enabling the Bloomberg connector' above.

For other errors, the best approach is to try loading the same series by using the Bloomberg Excel add-in by using the BDH function. If you cannot load the series using the BDH function, please contact Bloomberg support.