Macrobond 1.19

Selection of new functionality

Data Navigation

Filters in the Data Tree

You can now use a predefined list of Regions in the Data Tree. This Region filter will be applied on any category or sub-category that contains a Region tree.

Macrobond Document

Filters in the Release Activity

You can now apply a set of filter lists for regions and sources to filter releases in the Release Activity. These filters are the same as the ones that you define in the Search Activity.

If you preferred selecting regions the old way, you can still use the tab “Region”.

Macrobond Document

Charting

Annotations

Circling a range of observations

Observation labels can now refer to a range of values and to a range of graphs.

Macrobond Document

Copy / Pasting the style of graphs, ornaments and annotations

You can now copy a graph, ornament or graph annotation and then right click and select “Paste style” to apply it to another object of the same type.

Macrobond Document

Copy / Pasting of ornaments and annotations

In Macrobond 1.19, you can copy & paste ornaments and annotations within the same chart, or in another chart.

Keep in mind:

  • Observation labels are pasted by selecting a point on the series graph
  • If the text box or the observation label contains dynamic text referring to a specific series, this text will likely not work when applied to a different chart.

Graphs

Line graph dashed from the end

When applying a dashed line-style in your charts, it’s possible that some data points may fall between the dashes when there are many points on a line. This is usually not a problem, but it can become one if the graph happens to end with the space between dashes. We now make sure that a graph always ends with a dash rather than a space so that the last data point is always visible.

As the end of a graph is typically more important, this might mean the gap is placed at the start of the line instead.

Scatter Charts

  • Step Length for the X-axis

There is now a setting for the Step length for x-axis in scatter charts.

Analyses

Series List

  • Sorting series in the Series Information tab

You can now sort the time series listed in the Series Information tab. The state will be stored per document.

X-13 Seasonal Adjustment analysis

  • Chinese New Year

There is an option for selecting “Chinese New Year” as a regression variable in the X-13 Seasonal adjustment analysis. This works only for monthly data.

Download the Macrobond document below for an example of how this analysis can be used.

Macrobond Document
  • Trend constant regression variable

You can add a trend constant regression variable by checking box in the constant column.

Formulas

  • Trimean

The formula “Trimean” has been added. It returns the Tukey’s trimean.

Regression analysis

  • “Diff” setting

A new setting, called Diff, has been added to the Regression analysis. Selecting it will use the first order of differences of the series in the model. The result will be converted back to levels.

Macrobond Document

VECM Analysis

  • Cholesky’s method for impulse response

Presentation Documents

  • Fixed Layout for the Paginator option

This setting allows you to set the same chart layout for the last page, when automatically dividing charts into separate pages using the paginator. Without this setting the layout (and size of charts) will adapt to the number of charts on the last page.

Macrobond Document
  • Chart names

When you rename the chart nodes in the analysis tree, this is the name that will be used for the chart in presentation documents. In version 1.19, If you haven’t renamed the chart nodes, the document name will be used instead “time chart” for example.

Macrobond Document

Miscellaneous

  • Auto-recovery

The application will automatically save a snapshot of all documents that are open, every 30 seconds. These will be used if the application is terminated abnormally. When closing the application normally, you’ll be prompted to keep these snapshots or discard them. This feature will also be used to remember the state when the computer is restarted by Windows Update.

  • File | Revert

This command will revert the document to the state of the document that was last saved.

  • Context menu for tabs in Browse and Analytics

There is now a context menu when you right click on a tab in Analytics and Browse. These options are available on the view menu too.

Macrobond Document

How To Upgrade

The new version can be installed directly via the Macrobond application by clicking on the yellow ribbon, which appears on the screen, or by selecting Check for update in the Help menu. If you need assistance, a description of how to upgrade can be found here.

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.

Product versions and end-of-life

Each of the new versions of the Macrobond application can be installed directly via the Macrobond platform by clicking the yellow line which appears on the screen or by selecting Check for update on the Help menu. If you need assistance, a description of how to upgrade may be found here. You might need additional help from your IT-department.

Versions are supported until the end of the second year after the release. It is a good practice to upgrade at least annually.

You are always welcome to contact the Macrobond team to arrange access or if you have any questions.

  • Version 1.30 released December 2024, can be used until 1st of January 2027
  • Version 1.29 released September 2024, can be used until 1st of January 2027
  • Version 1.28 released March 2024, can be used until 1st of January 2027
  • Version 1.27 released June 2023, can be used until 1st of January 2026
  • Version 1.26 released December 2022, can be used until 1st of January 2025
  • Version 1.25 released December 2021, can be used until 1st of January 2024
  • Version 1.24 released March 2021, can be used until 1st of January 2024
  • Version 1.23 released May 2020, end of life 1st of January 2023
  • Version 1.22 released December 2019, end of life 1st of January 2022
  • Version 1.21 released April 2019, end of life 1st of January 2022
  • Version 1.20 released November 2018, end of life 1st of January 2021
  • Version 1.19 released May 2018, end of life 1st of January 2021
  • Version 1.18 released October 2017, end of life 1st of January 2020
  • Version 1.17 released March 2017, end of life 1st of January 2020
  • Version 1.16 released July 2016, end of life 1st of January 2019
  • Version 1.15 released September 2015, end of life 1st January 2018
  • Version 1.14 released December 2014, end of life 1st January 2018
  • Version 1.13 released June 2014, end of life 1st January 2018
  • Version 1.12 released December 2013, end of life 1st January 2017
  • Version 1.11 released October 2013, end of life 1st January 2017
  • Version 1.10 released June 2013, end of life 1st January 2017
  • Version 1.9 released March 2013, end of life 1st January 2017
  • Version 1.8 released October 2012, end of life 1st January 2016
  • Version 1.7 released June 2012, end of life 1st January 2016
  • Version 1.6 released May 2012, end of life1st January 2016
  • Version 1.5 released March 2012, end of life 1st January 2016
  • Version 1.4 released October 2011, end of life 1st January 2015
  • Version 1.3 released June 2011, end of life 1st January 2015
  • Version 1.2 released April 2011, end of life1st January 2015
  • Version 1.1 released September 2010, no longer supported
  • Version 1.0 released May 2010, no longer supported

What’s in Macrobond settings in Excel?

The settings dialog box in the Excel add-in allows you to adjust your Macrobond account credentials, communication settings, and document directories directly from the Excel add-in.

Account

In the account tab, your Macrobond username and password, as provided by your sales representative, are stored. These credentials enable access to the database packages included in your license.

Communication

In this tab, you can define settings for a proxy server if it is not detected automatically. Additionally, it’s possible to specify the URL of the Macrobond server. In most cases, however, the default option should remain selected.

The "Automated configuration" button lets you test a number of communication configurations to see what works best for your system.

Selecting "Verify end-to-end encryption for https" verifies that the communication is encrypted between the application and the Macrobond servers and detects if anyone is eavesdropping on the communication. The option might not work in some networks where a firewall is configured to intercept and inspect all internet traffic.

Advanced

The "Enable application logging" option logs more detailed diagnostically relevant information. Because turning on this function may impact application performance negatively, it should only be turned on when prompted by Macrobond support.

Checking "Enable SQL and Web API Series provider database connector log console" activates a popup window providing details about the communication with your SQL server. This option should be used when creating or troubleshooting the SQL in-house data storage.

When the "Collect usage statistics" option is checked, the application will gather anonymous information about the application’s performance and your feature usage. These statistics help us to constantly improve your experience.

Document paths

In this tab, you can specify a location on your computer where you’d like to save the Macrobond documents that you choose to save locally rather than on the Macrobond server. By default, the Macrobond folder is located in your Documents folder.

Furthermore, you can add and name frequently used directories for easy access when opening and saving documents.

What’s in Macrobond settings?

The settings dialog box allows you to adjust your Macrobond account credentials, communication settings, document locations, and some other configurations. Screenshots represent view as of Macrobond 1.30.

Account

In the Account tab, your Macrobond username and password, as provided by your sales representative, are stored. These credentials enable access to the database packages included in your license.

DB Language

Since version 1.30 of Macrobond, we have implemented general release of the application in Chinese language [GA].

If your application version does not allow you to switch the database language yourself, ask your Macrobond representative to activate the Chinese application for you.

Communication

In this tab, you can define settings for a proxy server if it is not detected automatically. Additionally, it’s possible to specify the URL of the Macrobond server. In most cases, however, the default option should remain selected.

The ‘Automated configuration’ button lets you test a number of communication configurations to see what works best for your system. See How to use the automatic proxy configuration tool in Macrobond?.

Selecting ‘Verify end-to-end encryption for https’ verifies that the communication is encrypted between the application and the Macrobond servers and detects if anyone is eavesdropping on the communication. The option might not work in some networks where a firewall is configured to intercept and inspect all internet traffic.

My series

In this tab, you can specify external data sources and connect them with the Macrobond application. Read more about connecting to an SQL server here, and about connecting to the Bloomberg Terminal here.

SVG

When you save charts in the SVG format, the text will normally be vectorized along with the rest of the image. In this tab, you can select fonts that you don’t want to be vectorized when saving as SVG.

Document paths

In this tab, you can specify a location on your computer where you’d like to save the Macrobond documents that you choose to save locally rather than on the Macrobond server. By default, the Macrobond folder is located in your Documents folder.

Here, you can also add and name frequently used directories for easy access when opening and saving documents.

Advanced

The "Enable application logging" option logs more detailed diagnostically relevant information. Because turning on this function may impact application performance negatively, it should only be turned on when prompted by Macrobond support.

Checking "Enable SQL and Web API Series Provider connector log console" activates a popup window providing details about the communication with your SQL server. This option should be used when creating or troubleshooting the SQL in-house data storage.

When the "Collect usage statistics" option is checked, the application will gather anonymous information about the application’s performance and your feature usage. These statistics help us to constantly improve your experience.

Social

When you have connected your Macrobond to X and LinkedIn, here you can un-connect with 'Forget' button.

Quick view

Since the release of version 1.30 of Macrobond, we have introduced an enhanced data exploration workflow. Here you can assigned keyboard shortcuts or choose from several operations to open up pre-defined templates.

How to change my password?

Our security policy does not allow you to change the password. We can only reset the password and automatically generate a new one according to our internal password policy (length, special signs etc.).

If you need to reset it or do not remember it, please contact Support.