Ir al contenido principal

A Chilean Economic API

During the last few years, I've been searching for new projects to do in my free time. After searching and prototyping several options, I came with the idea to implement an SDK (Software Development Kit) for an API. With that being said, I found a GitHub site called "Listado de API’s Públicas en Chile". This site has a comprehensive list of public and free-to-use APIs made by Chileans. Among the available categories, you can find: 

  • Government
  • Transport
  • Economy
  • Entertainment
  • Weather
  • Among others
The one that I've chosen is related to the Economy. The name of the API is Mi indicador (my indicator in English). I choose it because of my profession. Additionally, it would allow Computer scientists, Economists, Social scientists, and any other person interested in economics to systematize their ideas into algorithms for rational decision making, rather than following a narrative from the news centers or from the central planners.

Despite my ambition of pursuing a new project, I was convinced that Matlab can still be useful for the Open source environment. If you may know from my previous posts, one of my main programming strengths is Matlab. This was my first programming language, and like the first love of your life, you can't easily get rid of it. Therefore, I embrace the development of an SDK that standardizes the calls from a web service. 

Why? The most obvious reason is that it was a challenge for me, and it will enhance my CV, but most importantly, it was because I can. But let's finish the talk and let me show you how you can use the service (It's completely free). 

API exploration

An API is basically a digital database that works remotely. It gives responses based on requests from the user, and those responses have a format (typically in JSON). This API in specific constantly maps the Chilean Central Bank for the following data:

So, in a nutshell, the API gives end-of-day prices and values for the indicators from above. You can test a raw call using the following URL (copy and paste it in the search bar):

You will get a result similar to this: 

Naturally, the text from above is only readable by a machine and definitely not by a human (at least I don't have the facilities), so you can't do any type of data analytics to extract insights. Consequently, here is when the Matlab SDK comes into action and helps you do any type of graphical or statistical analysis.

Matlab SDK

First, if you are a Spanish speaker and a geek, you can go directly to the SDK documentation. If that's not the case, please read the rest of the article.

An SDK is better known as toolboxes in the Matlab community (I will continue with that convention). If you don't know how to install a toolbox, please go to the following forum. If the toolbox is already installed in your Matlab session, you can request the complete documentation using the following command:

% Call the toolbox documentation
If it's not installed, please install it using the project site

The rest of the article will explain the functionality of the Economic Indicators toolbox, which includes the initialization of the class, the methods it has to request data from the API, and possible ideas for its future use. 

To initialize the Indicators object, the class must be invoked and stored in some variable. Note that the API does not require a key for its use. Hence the class can be initialized empty or just by entering the maximum wait time for the client in Matlab. Below is a use case of the above.

% Initialize the instance with a maximum waiting time of 45 segs. This parameter is optional.
rest_client = Indicadores(45);
% Show the configuration of the instance of the general class
The toolbox has only two methods; get_data() and metadata(), and their usage is the following:

% Snapshot of all of the indicators of the API with their most recent value.
% Diplay the available indicators in the API (in spanish) rest_client.metadata()

Practical use case

Below is a use case that exposes the client's potential in Matlab for the Economic Indicators API. That said, data on the euro and the dollar will be requested from the API to then graph its behavior against the Chilean peso during 2019.

% Generate the prices paths and save the variable
clear; clc; rest_client = Indicadores();
% Requesting the data from the API
euro = rest_client.get_data('indicador', 'euro', 'fecha', '2019');
dolar = rest_client.get_data('indicador', 'dolar', 'fecha', '2019');
plot(euro.valor); hold on; plot(dolar.valor)
legend("Euro", "Dolar");
title('Valor del Euro y del Dolar en pesos Chilenos')

% Calculate the correlation between the instruments
sprintf('Both instruments have a correlation of %.2f', corr(euro.valor, dolar.valor))
Blogger does not support live coding, so you will need to trust that the correlation is 0.98. You can also test it on your computer.

Conclusion and future work

This was one of my first public projects outside college and my previous work. I had fun during its development because it woke up my ambition to pursue a career in trading the markets using rational and economic arguments rather than narratives. Nowadays, I'm more towards Python, so I will conduct research and publish libraries in that programming language in future posts. 

I hope this toolbox is handy for the people mentioned. Any type of comment or suggestion will be very well received.

Until next time!


Entradas más populares de este blog

Impopular, pero no hay una píldora mágica para escapar de ella.

Los mercados son instancias en donde se transan bienes y servicios, los cuales actúan como sistemas descentralizados, gobernados por relaciones caóticas y fuertemente influenciados por factores estocásticos, es decir, son sistemas complejos. Los agentes económicos que cotizan, compran y venden los instrumentos agregan información proveniente de estímulos externos basados en riesgos macro económicos. Dentro de esos mercados, esta el mercado de bonos soberanos, los cuales transan las expectativas de crecimiento e inflación para el gobierno central de un país. Ambas variables se pueden ver desde dos ángulos complementarios: mercado secundario y balance fiscal.

A list of SDKs that may help your next project

Now that I work independently, I can code whatever I want, whenever I want. One of my favorite things to code and publish is SDKs (Software development kits) related to APIs, specifically financial APIs. This helps analysts standardize the layer of data extraction and helps them work with the actual stuff they are good at. Extract insights for educated guesses about the market. Without further due, let me show you a list of curated financial SDKs that may help your work as an analyst or trader (be aware that some of these SDK will be in Spanish):  End-of-Day data extractor This library is the Python 🐍 unofficial SDK for the EOD Historical data REST API. It's intended to be used for data extraction for financial valuations, macroeconomic analyses, sentiment analysis, option strategies, technical analysis, development of machine learning models, and more! Variance Ratio Test These statistical te

Valoración de empresas financieras

El artículo tratara sobre un método para valorizar empresas financieras desde una perspectiva del patrimonio. Primero, se abordaran los desafíos de valorizar empresas financieras; Segundo, una explicación teórica del modelo; Tercero, se desarrollará el método de valorización por medio de una aplicación practica en Python, en solo 7 simples pasos . Finalmente se discutirá si el ejemplo práctico es una oportunidad atractiva o no. Cualquier empresa que proporcione productos y servicios financieros a personas u otras empresas puede clasificarse como una empresa de servicios financieros. Dicho lo anterior, las empresas de servicios financieros se pueden desglosar en cuatro grupos (desde la perspectiva de como generan utilidades): Bancos comerciales: Estos generan utilidades entre el spread al cual prestan dinero (colocaciones) y al cual entregan los intereses a los depósitos (captaciones). La curva de tasas ayuda a explicar este fenómeno. Aseguradoras: Estas los hacen por dos vías. Por