In [37]:
from sysdata.csvdata import csvFuturesData
import matplotlib.pyplot as plt
%matplotlib inline
Work up a minimum example of a trend following system
In [6]:
Let's get some data
We can get data from various places; however for now we're going to use prepackaged 'legacy' data stored in csv files
In [8]:
data = csvFuturesData()
data
Out[8]:
We get stuff out of data with methods
In [9]:
print(data.get_instrument_list())
print(data.get_raw_price("EDOLLAR").tail(5))
data can also behave in a dict like manner (though it's not a dict)
In [27]:
data['SP500']
Out[27]:
In [28]:
data.keys()
Out[28]:
... however this will only access prices (note these prices have already been backadjusted for rolls)
We have extra futures data here
In [29]:
data.get_instrument_raw_carry_data("EDOLLAR").tail(6)
Out[29]:
Technical note: csvFuturesData inherits from FuturesData which itself inherits from Data The chain is 'data specific' <- 'asset class specific' <- 'generic'
So there are also
In principal there could be an equities data
Let's create a simple trading rule
No capping or scaling
In [13]:
import pandas as pd
from syscore.algos import robust_vol_calc
def calc_ewmac_forecast(price, Lfast, Lslow=None):
"""
Calculate the ewmac trading fule forecast, given a price and EWMA speeds
Lfast, Lslow and vol_lookback
"""
# price: This is the stitched price series
# We can't use the price of the contract we're trading, or the volatility
# will be jumpy
# And we'll miss out on the rolldown. See
# http://qoppac.blogspot.co.uk/2015/05/systems-building-futures-rolling.html
price = price.resample("1B").last()
if Lslow is None:
Lslow = 4 * Lfast
# We don't need to calculate the decay parameter, just use the span
# directly
fast_ewma = price.ewm(span=Lfast).mean()
slow_ewma = price.ewm(span=Lslow).mean()
raw_ewmac = fast_ewma - slow_ewma
vol = robust_vol_calc(price.diff())
return raw_ewmac / vol
Try it out
(this isn't properly scaled at this stage of course)
In [38]:
instrument_code = 'EDOLLAR'
price = data.daily_prices(instrument_code)
ewmac = calc_ewmac_forecast(price, 32, 128)
ewmac.columns = ['forecast']
ewmac.tail(5)
Out[38]:
In [39]:
ewmac.plot();
plt.title('Forecast')
plt.ylabel('Position')
plt.xlabel('Time')
Out[39]:
Did we make money?
In [45]:
accountCurve?
In [48]:
from syscore.accounting import accountCurve
account = accountCurve(price, forecast=ewmac)
account.curve().plot();
plt.title('Profit and Loss')
plt.ylabel('PnL')
plt.xlabel('Time');
In [24]:
account.percent().stats()
Out[24]:
In [ ]: