First, do some initialization and set debugging level to debug
to see progress of computation.
%matplotlib inline
%load_ext autoreload
%autoreload 2
%config InlineBackend.figure_format = 'svg'
import numpy as np
import pandas as pd
import seaborn as sns
import datetime as dt
import matplotlib.pyplot as plt
import universal as up
from universal import tools, algos
from universal.algos import *
sns.set_context("notebook")
plt.rcParams["figure.figsize"] = (16, 8)
# ignore logged warnings
import logging
logging.getLogger().setLevel(logging.ERROR)
Let's try to replicate the results of B.Li and S.Hoi from their article On-Line Portfolio Selection with Moving Average Reversion. They claim superior performance on several datasets using their OLMAR algorithm. These datasets are available in data/
directory in .pkl
format. Those are all relative prices (start with 1.) and artificial tickers. We can start with NYSE stocks from period 1/1/1985 - 30/6/2010.
# load data using tools module
data = tools.dataset('nyse_o')
# plot first three of them as example
data.iloc[:,:3].plot()
Now we need an implementation of the OLMAR algorithm. Fortunately, it is already implemented in module algos
, so all we have to do is load it and set its parameters. Authors recommend lookback window $w = 5$ and threshold $\epsilon = 10$ (these are default parameters anyway). Just call run
method on our data to get results for analysis.
# set algo parameters
algo = algos.OLMAR(window=5, eps=10)
# run
result = algo.run(data)
Ok, let's see some results. First print some basic summary metrics and plot portfolio equity with UCRP (uniform constant rebalanced portfolio).
print(result.summary())
result.plot(weights=False, assets=False, ucrp=True, logy=True);
That seems really impressive, in fact it looks too good to be true. Let's see how individual stocks contribute to portfolio equity and disable legend to keep the graph clean.
result.plot_decomposition(legend=False, logy=True)
As you can see, almost all wealth comes from single stock (don't forget it has logarithm scale!). So if we used just 5 of all these stocks, we would get almost the same equity as if we used all of them. To stress test the strategy, we can remove that stock and rerun the algorithm.
# find name of the most profitable asset
most_profitable = result.equity_decomposed.iloc[-1].idxmax()
# rerun an algorithm on data without it
result_without = algo.run(data.drop([most_profitable], 1))
# and print results
print(result_without.summary())
result_without.plot(weights=False, assets=False, ucrp=True, logy=True);
We lost about 7 orders of wealth, but the results are more realistic now. Let's move on and try adding fees of 0.1% per transaction (we pay \$1 for every \\$1000 of stocks bought or sold).
result_without.fee = 0.001
print(result_without.summary())
result_without.plot(weights=False, assets=False, ucrp=True, logy=True)