One of the reasons we decided to focus on SliceMatrix-IO as Platform as a Service (PaaS) API was to make it play nicely with other systems. The Bloomberg terminal is one of the most widely used sources of data in the financial world, so we wanted to present a quick notebook which shows how to integrate SliceMatrix-IO and "The Bloomberg" in a way few thought possible.
First let's create an IO client to do our bidding. Remember to substitute your api key in the code below. Don't have a key yet? Get your api key here
from slicematrixIO import SliceMatrix
api_key = "insert your api key here"
sm = SliceMatrix(api_key)
In order to connect to the Bloomberg terminal in Python, we're going to make use of the tia package. This can be installed with pip:
pip install tia
Now we can import everything we need for Bloomberg-ing...
from tia.bbg import LocalTerminal
import tia.bbg.datamgr as dm
Plus some good friends...
import pandas as pd
import numpy as np
import datetime as dt
Now let's create a function for getting the components of a given stock index. To anyone familiar with punching keys into a terminal, you might recognize some of these commands...
def get_index_members(index_name):
components = LocalTerminal.get_reference_data(index_name,'INDX_MEMBERS')
components=components.as_frame()
components=components['INDX_MEMBERS'][0]
components = map(lambda x: x+" Equity", list(components["Member Ticker and Exchange Code"]))
components = [component[:-9] + "US Equity" for component in components]
return components
When you create a weapon you want to use it... to get the S&P 500 components ;-)
stocks=get_index_members('SPX Index')
print stocks[0:10], '...', stocks[-10:-1]
The main vector for getting data out of tia is the BbgDataManager
data_manager = dm.BbgDataManager()
We can use this object to grab the data we want: in this case the daily closing prices over the last year
prices = data_manager[stocks].get_historical('PX_LAST', '3/8/2012', '3/8/2017')
%matplotlib inline
import matplotlib.pyplot as plt
prices['AAPL US Equity'].plot(figsize = (10,6))
plt.show()
Then taking log-differences...
cols = prices.columns
prices.columns = [column.replace("US Equity", "") for column in cols]
diffs = np.log(prices).diff().dropna(axis = 0, how = "all").dropna(axis = 1, how = "any")
diffs.head()
One of the most useful ways to visualize the stock market is with Minimum Spanning Trees (MST). These are network graphs in which each vertex represents a stock symbol and where strongly related stocks are connected by edges.
One popular way to do this is by using correlation matrices. The next function constructs an MST by transforming the price correlation matrix for a group of stocks into a distance matrix using a metric function.
mst = sm.MinimumSpanningTree(dataset = diffs.T)
Then let's use the slicematrixIO-python.notebook module to visualize the Minimum Spanning Tree
from slicematrixIO.notebook import GraphEngine
viz = GraphEngine(sm)
viz.init_style()
viz.init_data()
viz.drawNetworkGraph(mst, width = 1000, height = 500, min_node_size = 10, charge = -25, color_map = "Heat", color_axis = "eccentricity", graph_layout = "force", label_color = "rgba(255,255,255,0.88)", graph_style = "dark")
Each network graph contains a number of unique factors describing the systemic importance of the stock within the market graph. These factors can be accessed directly via:
mst.rankNodes(statistic = "closeness_centrality").head(20)
Another correlation-based network graph method is called the CorrelationFilteredGraph. Like MST, the CFG starts by looking at the correlation matrix of the input data, but unlike the MST the CFG admits many more links into the graph structure:
cfg = sm.CorrelationFilteredGraph(dataset = diffs.T)
viz.drawNetworkGraph(cfg, width = 1000, height = 800, min_node_size = 8, charge = -75, color_map = "RdBuGn", color_axis = "closeness_centrality", graph_layout = "force", label_color = "rgba(255,255,255,0.88)", graph_style = "dark")
Don't have a SliceMatrix-IO api key yet? Get your api key here