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): 

https://mindicador.cl/api

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
doc(Indicadores)
If it's not installed, please install it using the project site https://la.mathworks.com/matlabcentral/fileexchange/75497-indicadores-enconomicos


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
rest_client.options
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.
rest_client.get_data()
% 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!

Comentarios

Entradas más populares de este blog

BCCh en pausa: ¿Esperar una disminución de las tasas en la economía chilena?

La inversión de la curva de tasas, que implica la desincentivación del flujo de crédito por parte de los Bancos Centrales, conduce a una estrangulación económica y desaceleraciones pronunciadas. En el caso del mercado de bonos chileno, esta situación es indicativa de un debilitamiento económico futuro, atribuible a diversos factores como la caída en los márgenes operacionales, el decrecimiento de las ganancias y el incremento en las tasas de interés. El spread 2y10y en el mercado de bonos chileno ha alcanzado mínimos históricos, considerablemente más pronunciados que previamente a la crisis subprime. Además, la curva de bonos tipo BCP ha estado completamente invertida durante más de un trimestre. Estos hallazgos sugieren que los inversionistas perciben una compresión significativa en los márgenes operacionales y un crecimiento de las ganancias menor al aumento en las tasas de interés de los préstamos adquiridos. También revelan la desconfianza en la narrativa propuesta por el Banco Cen

Tu primera estrategia cuantitativa

Desde que los holandeses implementaron el primer mercado de valores en 1611, los analistas han tratado de crear estrategias que sistematicen la agregación de información. El fin póstumo es adelantarse al consenso generalizado, el cual siempre está mal debido a que llegan tarde o derechamente está mal. Su mantra siempre ha sido y será comprar miedo para luego vender codicia , ya que de esa manera se logra materializar las ganancias de capital (en largo o en corto). Dicho lo anterior, los marcos de referencia han evolucionado en conjunto a la tecnología disponible en cada estadio cultural. Desde los clásico “chartistas” que descubren las zonas de liquidez en base a fractales de otros mercados e instrumentos y los replican en el instrumento analizado, hasta los tiempos mas recientes donde se enfoca en parametrizar el agregamiento de información exógena en los precios. El último enfoque se conoce como “Quant” o Cuantitativo . El método se basa en utilizar las herramientas de las ciencias e

Outlook sector Retail Chileno

A continuación te comentaré mi tesis con respecto al sector del retail chileno . Para aquello tomo elementos de la macroeconomía, fundamentos de la industria y un análisis técnico (usando ondas de Elliott) de los retailers con mayor capitalización bursátil. Esto te permitirá tener una visión externa y diferente de lo que está ocurriendo en el sector, lo que en definitiva te ayudará a generar perspectiva y contrastarlo contra tu propia tesis de inversión .