In [1]:
# import libraries
%pylab inline
import tradingWithPython as twp
import pandas as pd
twp.extra.setNotebookStyle()
figsize(10,5)
Working at Oce since 2005
Trading stocks as a hobby since 2009
(see http://github.com/jrjohansson/scientific-python-lectures for more)
( previously called IPython notebook ) Project found on jupyter.org
Spyder is a MATLAB-like IDE for scientific computing with python. It has the many advantages of a traditional IDE environment, for example that everything from code editing, execution and debugging is carried out in a single environment, and work on different calculations can be organized as projects in the IDE environment.
Some advantages of Spyder:
In [2]:
# matplotlib example
# plot 5-sec data
price = pd.DataFrame.from_csv('data/SPY_20160411205955.csv')
price.close.plot()
Out[2]:
In [3]:
# bokeh example
from bokeh.io import output_notebook, show
from bokeh.plotting import figure
from bokeh.charts import Line
output_notebook()
line = Line(price.close, plot_width=800, plot_height=400)
show(line)
In [4]:
# get data from yahoo finance
price = twp.yahooFinance.getHistoricData('SPY')
price['adj_close'].plot()
Out[4]:
In [5]:
# get data
import tradingWithPython.lib.cboe as cboe # cboe data
symbols = ['SPY','VXX','VXZ']
priceData = twp.yahooFinance.getHistoricData(symbols).minor_xs('adj_close')
volData = cboe.getHistoricData(['VIX','VXV']).dropna()
In [6]:
volData.plot();
In [7]:
delta = volData.VIX - volData.VXV
delta.plot()
title('delta')
Out[7]:
In [8]:
# prepare data
df = pd.DataFrame({'VXX':priceData.VXX, 'delta':delta}).dropna()
df.plot(subplots='True');
In [9]:
# strategy simulation function
def backtest(thresh):
""" backtest strategy with a threshold value"""
df['dir'] = 0 # init with zeros
df['ret'] = df.VXX.pct_change()
long = df.delta > thresh
short = df.delta < thresh
#df.ix[long,'dir'] = 1 # set long positions
df.ix[short,'dir'] = -1 # set short positions
df['dir'] = df['dir'].shift(1) # dont forget to shift one day forward!
df['pnl'] = df['dir'] * df['ret']
return df
df = backtest(0)
df
Out[9]:
In [10]:
# check relationship delta-returns
df.plot(kind='scatter',x='delta',y='ret')
Out[10]:
In [11]:
T = np.linspace(-3,0,10)
h = ['%.2f' % t for t in T] # make table header
pnl ={} # pnl dict
PNL = pd.DataFrame(index=df.index, columns=h)
for i, t in enumerate(T):
PNL[h[i]] = backtest(thresh=t)['pnl']
PNL.cumsum().plot()
Out[11]:
In [12]:
# evaluate performance
twp.sharpe(PNL).plot(kind='bar')
xlabel('threshold')
ylabel('sharpe')
title('strategy performance')
Out[12]:
In [13]:
# plot best strategy
PNL['-2.00'].cumsum().plot()
Out[13]: