CoCalc Public FilesVXX_Backtest.ipynbOpen with one click!
Authors: Erik Brandberg, Paul Cao
Views : 108
In [1]:
from pyalgotrade.bar import Bar from pyalgotrade import barfeed class PandasBar(Bar): def __init__(self, df, ix, bars): self.df = df self.ix = ix self.bars = bars def getRow(self): rowkey = self.df.index[self.ix] return self.df.ix[rowkey] def getDateTime(self): """Returns the :class:`datetime.datetime`.""" return self.bars.date def getOpen(self, adjusted=False): """Returns the opening price.""" ret = ( float(self.getRow()["Ask"]) + float(self.getRow()["Bid"]) ) / 2 if ret > 0: return ret else: return 0.01 #fix for worthless options def getHigh(self, adjusted=False): """Returns the highest price.""" return float(self.getRow()["Ask"]) def getLow(self, adjusted=False): """Returns the lowest price.""" return float(self.getRow()["Bid"]) def getClose(self, adjusted=False): """Returns the closing price.""" return self.getOpen() def getVolume(self): """Returns the volume.""" return 500000 def getAdjClose(self): """Returns the adjusted closing price.""" return self.getOpen() def getFrequency(self): """The bar's period.""" return barfeed.Frequency.DAY def getPrice(self): """Returns the closing or adjusted closing price.""" return self.getOpen() def setUseAdjustedValue(self, useAdjusted): pass def getUseAdjValue(self): return False
In [2]:
class PandasBars(object): """A group of :class:`Bar` objects. :param barDict: A map of instrument to :class:`Bar` objects. :type barDict: map. .. note:: All bars must have the same datetime. """ def __init__(self, df, date, arr_ix=[]): self.date = date self.df = df self.arr_ix = arr_ix #key_val_arr = map(lambda ix: (df.ix[df.index[ix]]["Symbol"], PandasBar(df, ix, self)), self.arr_ix) #self.bar_dict = dict(key_val_arr) def set_bars_dict(self, bar_dict): self.bar_dict = bar_dict def keys(self): return self.bar_dict.keys() def __getitem__(self, instrument): """Returns the :class:`pyalgotrade.bar.Bar` for the given instrument. If the instrument is not found an exception is raised.""" return self.bar_dict[instrument] def __contains__(self, instrument): """Returns True if a :class:`pyalgotrade.bar.Bar` for the given instrument is available.""" return instrument in self.bar_dict def items(self): return self.bar_dict.items() def keys(self): return self.bar_dict.keys() def getInstruments(self): """Returns the instrument symbols.""" return self.bar_dict.keys() def getDateTime(self): """Returns the :class:`datetime.datetime` for this set of bars.""" return self.date def setDateTime(self, date): self.date = date def getBar(self, instrument): """Returns the :class:`pyalgotrade.bar.Bar` for the given instrument or None if the instrument is not found.""" return self.bar_dict.get(instrument, None)
In [3]:
from more_itertools import peekable from pyalgotrade.bar import Bar from pyalgotrade import barfeed import datetime class PandasBarFeed(barfeed.BaseBarFeed): def __init__(self, dataframe, instrument, frequency): super(PandasBarFeed, self).__init__(frequency) self.registerInstrument(instrument) self.__df = dataframe self.__instrument = instrument self.__next = 0 self.started = False self.signal_bar = None self.__lastBars = {} groups = self.__df.groupby(["DateType","Symbol"]).groups timestamp_dict = {} bars_dict = {} def loadBars(timestamp, symbol, index): if timestamp not in timestamp_dict: timestamp_dict[timestamp] = {} bars_dict[timestamp] = PandasBars(self.__df, timestamp) timestamp_dict[timestamp][symbol] = PandasBar(self.__df, index, bars_dict[timestamp]) map(lambda ((timestamp, symbol),index):loadBars(timestamp, symbol, index), groups.iteritems()) map(lambda (timestamp, bars):bars.set_bars_dict(timestamp_dict[timestamp]), bars_dict.iteritems()) dates = sorted(timestamp_dict.keys()) bars = map(lambda d:bars_dict[d], dates) self.bars = [] for bar in bars: self.bars.append(bar) #trade_bar = PandasBars(bar.df, bar.date+datetime.timedelta(minutes=30),bar.arr_ix) #trade_bar.set_bars_dict(bar.bar_dict) #self.bars.append(trade_bar) self.bar_iter = peekable(self.bars) def reset(self): super(PandasBarFeed, self).reset() self.bar_iter = peekable(self.bars) self.started = False self.__lastBars = {} def peekDateTime(self): return self.getCurrentDateTime() def getCurrentDateTime(self): try: return self.bar_iter.peek().date except StopIteration: return None def barsHaveAdjClose(self): return True def getNextBars(self): try: return self.bar_iter.next() except StopIteration: return None def start(self): #super(PandasBarFeed, self).start() self.__started = True def stop(self): pass def join(self): pass def eof(self): try: if self.bar_iter.peek() and not self.bar_iter.peek() == self.bars[-1]: return False else: return True except StopIteration: return True def getCurrentBars(self): try: return self.bar_iter.peek() except StopIteration: return None def getNextValuesAndUpdateDS(self): dateTime, values = self.getNextValues() return (dateTime, values)
In [4]:
import pandas as pd df = pd.read_csv("vxx_csv3.csv", parse_dates=['DateType']) feed = PandasBarFeed(df, "VXX", barfeed.Frequency.TRADE)
In [7]:
df.info()
<class 'pandas.core.frame.DataFrame'> RangeIndex: 868602 entries, 0 to 868601 Data columns (total 11 columns): Unnamed: 0 868602 non-null int64 Symbol 868602 non-null object DateType 868602 non-null datetime64[ns] Type 867324 non-null object ExpDate 867324 non-null object Strike 867324 non-null float64 Last 868602 non-null float64 Bid 868602 non-null float64 Ask 868602 non-null float64 Volume 868602 non-null int64 UnderlyingPrice 867324 non-null float64 dtypes: datetime64[ns](1), float64(5), int64(2), object(3) memory usage: 72.9+ MB
In [8]:
#!/usr/bin/python # This file contains functions to help with detecting trading holidays # It relies on Pandas, Numpy (via Pandas) and Datetime import datetime as dt from pandas.tseries.holiday import AbstractHolidayCalendar, Holiday, nearest_workday, USMartinLutherKingJr, USPresidentsDay, USMemorialDay, USLaborDay, USThanksgivingDay # Import seperately to define GoodFriday due to old pandas version from pandas.tseries.offsets import Easter, Day class USTradingCalendar(AbstractHolidayCalendar): def __init__(self): # This is needed for older versions of Pandas pre-v15 and is forward compatible: GoodFriday = GoodFriday = Holiday("Good Friday", month=1, day=1, offset=[Easter(), Day(-2)]) USTradingCalendar.rules.append(GoodFriday) rules = [ Holiday('NewYearsDay', month=1, day=1, observance=nearest_workday), USMartinLutherKingJr, USPresidentsDay, USMemorialDay, Holiday('USIndependenceDay', month=7, day=4, observance=nearest_workday), USLaborDay, USThanksgivingDay, Holiday('Christmas', month=12, day=25, observance=nearest_workday) ] def is_market_closed(self,dto): # True if a given dt object is a trading holiday inst = USTradingCalendar() cal = inst.holidays(dt.datetime(dto.year-1, 12, 31), dt.datetime(dto.year, 12, 31)) if dto in cal: return True else: return False def get_trading_holidays(year, n_years=0): # Returns a list of trading holidays for a given year inst = USTradingCalendar() return inst.holidays(dt.datetime(year-1, 12, 31), dt.datetime(year + n_years, 12, 31)) def is_trading_holiday(dto): # True if a given dt object is a trading holiday inst = USTradingCalendar() cal = inst.holidays(dt.datetime(dto.year-1, 12, 31), dt.datetime(dto.year, 12, 31)) if dto in cal: return True else: return False cal = get_trading_holidays(2014, n_years=2) def get_last_trading_day(expiration_date): if expiration_date in cal or expiration_date.weekday() == 6 or expiration_date.weekday() == 5: return get_last_trading_day(expiration_date - dt.timedelta(days=1)) return expiration_date def get_next_trading_day(date): next_date = date + dt.timedelta(days=1) if next_date in cal or next_date.weekday() == 6 or next_date.weekday() == 5: return get_next_trading_day(next_date) return next_date
In [9]:
from pyalgotrade import strategy from pyalgotrade.broker import backtesting from vollib.black_scholes.implied_volatility import implied_volatility from vollib.black_scholes.greeks.numerical import delta import math import datetime class MyStrategy(strategy.BacktestingStrategy): def __init__(self, feed, instrument, useAdjustedClose=True, max_allocation=0.32, cash=100000): strategy.BacktestingStrategy.__init__(self, feed, cash) self.setUseAdjustedValues(useAdjustedClose) self.__instrument = instrument self.max_allocation = max_allocation self.chain = None self.liquidated = False self.expiration_date = None self.getBroker().setCommission(backtesting.TradePercentage(0.0)) def check_split(self, current_date): """ Return true if a split occurs next trading day """ vxx_splits = [datetime.date(2010,11,9), datetime.date(2012, 10, 5), datetime.date(2013, 11, 8), datetime.date(2016,8,9), datetime.date(2017,1,27)] next_trading_day = get_next_trading_day(current_date) previous_day = current_date - datetime.timedelta(days=1) for d in vxx_splits: if next_trading_day == d or current_date == d or previous_day == d: self.info("A split will occur on {0}.".format(current_date)) return True return False def calc_delta(self, filtered_option_chain, bars, t): chains = [] for option in filtered_option_chain: price = float(bars[option['OptionSymbol']].getClose()) cp = option['Type'].lower() K = float(option['Price']) S = float((bars['VXX']).getClose()) r = 0.028 iv = implied_volatility(price, S, K, t, r, str(cp)) calc_delta = delta(str(cp), S, K, t, r, float(iv)) option["IV"] = iv option["Delta"] = calc_delta chains.append(option) return chains def get_closet_expiration(self, n_days, chain): current_datetime = (self.getCurrentDateTime()).date() expiration_datetime = current_datetime + datetime.timedelta(days=n_days) option_chain = filter(lambda option:option['Expiration'] > expiration_datetime, chain) expiration_dates = map(lambda option:option['Expiration'], option_chain) if len(expiration_dates) > 1: return min(expiration_dates) else: return None def get_chain(self, bars): def parse_option_symbol(symbol): try: opra_symbol = symbol[:-15] opra_expiry = datetime.datetime.strptime(symbol[-15:-9], '%y%m%d').date() opra_cp = symbol[-9] opra_price = int(symbol[-8:]) * .001 return {"Symbol":opra_symbol, "Expiration":opra_expiry, "Type":opra_cp, "Price":opra_price, "OptionSymbol":symbol} except: print "Symbol:" + symbol print "OpraSymbol:" + symbol[:-15] print "OpraExpiry:" + symbol[-15:-9] print "OpraCp:" + symbol[-9] print "OpraPrice:" + symbol[-8] chain = [] for symbol in bars.keys(): if symbol == "VXX": continue chain.append(parse_option_symbol(symbol)) return chain def enterPosition(self, bars): portfolioAmt = self.getBroker().getEquity() atm_delta = 0.55 otm_delta = 0.42 close = bars["VXX"].getClose() original_option_chain = self.get_chain(bars) self.expiration_date = self.get_closet_expiration(14, original_option_chain) short_expiration_date = self.get_closet_expiration(7, original_option_chain) self.short_expiration_date = short_expiration_date if self.expiration_date == None: return None option_chain = filter(lambda option:option['Expiration'] == self.expiration_date, original_option_chain) short_chain = filter(lambda option:option['Expiration'] == short_expiration_date, original_option_chain) current_datetime = (self.getCurrentDateTime()).date() t = float(((self.expiration_date - current_datetime).total_seconds()) / (60 * 60 * 24 * 365)) put_option_chain = filter(lambda option:option['Type'] == 'P', option_chain) short_put_option_chain = filter(lambda option:option['Type'] == 'P', short_chain) self.calc_delta(put_option_chain, bars, t) self.calc_delta(short_put_option_chain, bars, t) try: self.atm_put_option = min(put_option_chain, key=lambda option:math.fabs(atm_delta - math.fabs(float(option['Delta'])))) self.otm_put_option = min(short_put_option_chain, key=lambda option:math.fabs(otm_delta - math.fabs(float(option['Delta'])))) except: return None if float((bars[self.atm_put_option['OptionSymbol']]).getClose()) - float((bars[self.otm_put_option['OptionSymbol']]).getClose()) <= 0: return None self.put_debit = float((bars[self.atm_put_option['OptionSymbol']]).getClose()) - float((bars[self.otm_put_option['OptionSymbol']]).getClose()) self.info("Portfolio Amount:" + str(portfolioAmt) + " Allotted Portfolio Amount: " + str(portfolioAmt * 0.10)) self.shares = (portfolioAmt * 0.10) / self.put_debit if self.shares <= 0: return None self.positions = [] self.positions.append(self.enterLong(self.atm_put_option['OptionSymbol'], self.shares, goodTillCanceled=True)) self.positions.append(self.enterShort(self.otm_put_option['OptionSymbol'], self.shares, goodTillCanceled=True)) self.info("Enter Position: +" + str(self.shares) + " " + self.atm_put_option['OptionSymbol'] + " -" + str(self.shares) + " " + self.otm_put_option['OptionSymbol'] + " at price " + str(self.put_debit) + "; VXX: " + str(close)) return self.positions def onBars(self, bars): if "VXX" not in bars.keys(): return if self.liquidated == False and self.expiration_date != None: if self.getCurrentDateTime() == None: return current_datetime = self.getCurrentDateTime().date() #current_datetime = dateTime.date() percentage = 0 current_put_credit = 0 if hasattr(self, "atm_put_option"): #current P/L try: current_put_credit = float((bars[self.atm_put_option['OptionSymbol']]).getClose()) - float((bars[self.otm_put_option['OptionSymbol']]).getClose()) percentage = math.fabs(current_put_credit / self.put_debit) except: self.info("Key Error") #Sometimes HOD doesn't have the data; skip this time and hope we find it the next day return last_trading_day = get_last_trading_day(self.short_expiration_date) - datetime.timedelta(days=1) if (self.expiration_date != None) and (current_datetime >= last_trading_day or percentage >= 1.30 or percentage <= 0.75 or self.check_split(current_datetime)): exit_spread_str = "" exit_pnl = 0 for position in self.positions: exit_spread_str = exit_spread_str + str(position.getShares()) + " " + str(position.getInstrument()) + " " exit_pnl = exit_pnl + position.getPnL() #self.marketOrder(position.getInstrument(), -position.getShares(), onClose=True) position.exitMarket() self.info("Exit " + exit_spread_str +" at price " + str(current_put_credit) + "; PnL: " + str(exit_pnl) + "; VXX: " + str(bars["VXX"].getClose())) #self.info("Exit " + self.atm_put_option['OptionSymbol']) self.liquidated = True if (self.liquidated == True) or self.expiration_date == None: current_datetime = (self.getCurrentDateTime() - datetime.timedelta(minutes=30)).date() if self.check_split(current_datetime) == False: success = self.enterPosition(bars) if success: self.liquidated = False
In [10]:
from pyalgotrade.stratanalyzer import returns from pyalgotrade import plotter from pyalgotrade.utils import stats from pyalgotrade.stratanalyzer import drawdown from pyalgotrade.stratanalyzer import trades #feed.reset() myStrategy = MyStrategy(feed, "VXX", useAdjustedClose=True) returnsAnalyzer = returns.Returns() myStrategy.attachAnalyzer(returnsAnalyzer) drawDownAnalyzer = drawdown.DrawDown() myStrategy.attachAnalyzer(drawDownAnalyzer) tradesAnalyzer = trades.Trades() myStrategy.attachAnalyzer(tradesAnalyzer) # Attach the plotter to the strategy. plt = plotter.StrategyPlotter(myStrategy, plotAllInstruments=False, plotBuySell=False) myStrategy.run()
2011-09-01 00:00:00 strategy [INFO] Portfolio Amount:100000 Allotted Portfolio Amount: 10000.0 2011-09-01 00:00:00 strategy [INFO] Enter Position: +7434.94423792 VXX110917P00041000 -7434.94423792 VXX110917P00039000 at price 1.345; VXX: 39.49 2011-09-06 00:00:00 strategy [INFO] Exit 7434 VXX110917P00041000 -7434 VXX110917P00039000 at price 0.825; PnL: -1672.65; VXX: 42.72 2011-09-06 00:00:00 strategy [INFO] Portfolio Amount:99739.81 Allotted Portfolio Amount: 9973.981 2011-09-06 00:00:00 strategy [INFO] Enter Position: +1673.48674497 VXX111022P00047000 -1673.48674497 VXX110917P00042000 at price 5.96; VXX: 42.72 2011-09-14 00:00:00 strategy [INFO] Exit 1673 VXX111022P00047000 -1673 VXX110917P00042000 at price 6.135; PnL: -41.825; VXX: 44.6 2011-09-14 00:00:00 strategy [INFO] Portfolio Amount:101203.685 Allotted Portfolio Amount: 10120.3685 2011-09-14 00:00:00 strategy [INFO] Enter Position: +3892.44942308 VXX111022P00048000 -3892.44942308 VXX111022P00044000 at price 2.6; VXX: 44.6 2011-09-22 00:00:00 strategy [INFO] Exit 3892 VXX111022P00048000 -3892 VXX111022P00044000 at price 1.89; PnL: -3930.92; VXX: 49.84 2011-09-22 00:00:00 strategy [INFO] Portfolio Amount:96883.565 Allotted Portfolio Amount: 9688.3565 2011-09-22 00:00:00 strategy [INFO] Enter Position: +2958.27679389 VXX111022P00054000 -2958.27679389 VXX111022P00049000 at price 3.275; VXX: 49.84 2011-10-03 00:00:00 strategy [INFO] Exit 2958 VXX111022P00054000 -2958 VXX111022P00049000 at price 1.925; PnL: -3475.65; VXX: 56.84 2011-10-03 00:00:00 strategy [INFO] Portfolio Amount:95596.835 Allotted Portfolio Amount: 9559.6835 2011-10-03 00:00:00 strategy [INFO] Enter Position: +3901.91163265 VXX111022P00060000 -3901.91163265 VXX111022P00056000 at price 2.45; VXX: 56.84 2011-10-05 00:00:00 strategy [INFO] Exit 3901 VXX111022P00060000 -3901 VXX111022P00056000 at price 3.3; PnL: 877.725; VXX: 50.26 2011-10-05 00:00:00 strategy [INFO] Portfolio Amount:97157.235 Allotted Portfolio Amount: 9715.7235 2011-10-05 00:00:00 strategy [INFO] Enter Position: +3840.206917 VXX111022P00053000 -3840.206917 VXX111022P00049000 at price 2.53; VXX: 50.26 2011-10-12 00:00:00 strategy [INFO] Exit 3840 VXX111022P00053000 -3840 VXX111022P00049000 at price 3.675; PnL: 4032.0; VXX: 42.97 2011-10-12 00:00:00 strategy [INFO] Portfolio Amount:101381.235 Allotted Portfolio Amount: 10138.1235 2011-10-12 00:00:00 strategy [INFO] Enter Position: +1834.95447964 VXX111119P00047000 -1834.95447964 VXX111022P00042000 at price 5.525; VXX: 42.97 2011-10-19 00:00:00 strategy [INFO] Exit 1834 VXX111119P00047000 -1834 VXX111022P00042000 at price 5.415; PnL: -596.05; VXX: 45.87 2011-10-19 00:00:00 strategy [INFO] Portfolio Amount:100610.955 Allotted Portfolio Amount: 10061.0955 2011-10-19 00:00:00 strategy [INFO] Enter Position: +3119.71953488 VXX111119P00050000 -3119.71953488 VXX111119P00045000 at price 3.225; VXX: 45.87 2011-10-27 00:00:00 strategy [INFO] Exit 3119 VXX111119P00050000 -3119 VXX111119P00045000 at price 4.575; PnL: 4366.6; VXX: 36.45 2011-10-27 00:00:00 strategy [INFO] Portfolio Amount:104977.555 Allotted Portfolio Amount: 10497.7555 2011-10-27 00:00:00 strategy [INFO] Enter Position: +5275.2540201 VXX111119P00039000 -5275.2540201 VXX111119P00036000 at price 1.99; VXX: 36.45 2011-10-31 00:00:00 strategy [INFO] Exit 5275 VXX111119P00039000 -5275 VXX111119P00036000 at price 1.34; PnL: -3877.125; VXX: 40.11 2011-10-31 00:00:00 strategy [INFO] Portfolio Amount:97645.305 Allotted Portfolio Amount: 9764.5305 2011-10-31 00:00:00 strategy [INFO] Enter Position: +5394.76823204 VXX111119P00042000 -5394.76823204 VXX111119P00039000 at price 1.81; VXX: 40.11 2011-11-01 00:00:00 strategy [INFO] Exit 5394 VXX111119P00042000 -5394 VXX111119P00039000 at price 1.045; PnL: 0.0; VXX: 45.92 2011-11-01 00:00:00 strategy [INFO] Portfolio Amount:98184.705 Allotted Portfolio Amount: 9818.4705 2011-11-01 00:00:00 strategy [INFO] Enter Position: +3850.38058824 VXX111119P00049000 -3850.38058824 VXX111119P00045000 at price 2.55; VXX: 45.92 2011-11-08 00:00:00 strategy [INFO] Exit 3850 VXX111119P00049000 -3850 VXX111119P00045000 at price 3.425; PnL: 2406.25; VXX: 40.82 2011-11-08 00:00:00 strategy [INFO] Portfolio Amount:95181.705 Allotted Portfolio Amount: 9518.1705 2011-11-08 00:00:00 strategy [INFO] Enter Position: +1760.99361702 VXX111217P00045000 -1760.99361702 VXX111119P00040000 at price 5.405; VXX: 40.82 2011-11-09 00:00:00 strategy [INFO] Exit 1760 VXX111217P00045000 -1760 VXX111119P00040000 at price 3.795; PnL: 0.0; VXX: 48.52 2011-11-09 00:00:00 strategy [INFO] Portfolio Amount:96660.105 Allotted Portfolio Amount: 9666.0105 2011-11-09 00:00:00 strategy [INFO] Enter Position: +1453.53541353 VXX111217P00054000 -1453.53541353 VXX111119P00048000 at price 6.65; VXX: 48.52 2011-11-16 00:00:00 strategy [INFO] Exit 1453 VXX111217P00054000 -1453 VXX111119P00048000 at price 7.84; PnL: 1111.545; VXX: 46.29 2011-11-16 00:00:00 strategy [INFO] Portfolio Amount:98040.455 Allotted Portfolio Amount: 9804.0455 2011-11-16 00:00:00 strategy [INFO] Enter Position: +3807.39631068 VXX111217P00050000 -3807.39631068 VXX111217P00046000 at price 2.575; VXX: 46.29 2011-12-01 00:00:00 strategy [INFO] Exit 3807 VXX111217P00050000 -3807 VXX111217P00046000 at price 3.5; PnL: 4568.4; VXX: 40.82 2011-12-01 00:00:00 strategy [INFO] Portfolio Amount:102704.03 Allotted Portfolio Amount: 10270.403 2011-12-01 00:00:00 strategy [INFO] Enter Position: +8930.78521739 VXX111217P00042000 -8930.78521739 VXX111217P00040000 at price 1.15; VXX: 40.82 2011-12-08 00:00:00 strategy [INFO] Exit 8930 VXX111217P00042000 -8930 VXX111217P00040000 at price 0.755; PnL: -3705.95; VXX: 43.71 2011-12-08 00:00:00 strategy [INFO] Portfolio Amount:103195.18 Allotted Portfolio Amount: 10319.518 2011-12-08 00:00:00 strategy [INFO] Enter Position: +1750.55436811 VXX120121P00048000 -1750.55436811 VXX111217P00043000 at price 5.895; VXX: 43.71 2011-12-14 00:00:00 strategy [INFO] Exit 1750 VXX120121P00048000 -1750 VXX111217P00043000 at price 6.62; PnL: 341.25; VXX: 40.77 2011-12-14 00:00:00 strategy [INFO] Portfolio Amount:103151.43 Allotted Portfolio Amount: 10315.143 2011-12-14 00:00:00 strategy [INFO] Enter Position: +3967.36269231 VXX120121P00044000 -3967.36269231 VXX120121P00040000 at price 2.6; VXX: 40.77 2011-12-21 00:00:00 strategy [INFO] Exit 3967 VXX120121P00044000 -3967 VXX120121P00040000 at price 3.65; PnL: 3371.95; VXX: 33.76 2011-12-21 00:00:00 strategy [INFO] Portfolio Amount:106225.855 Allotted Portfolio Amount: 10622.5855 2011-12-21 00:00:00 strategy [INFO] Enter Position: +5245.72123457 VXX120121P00036000 -5245.72123457 VXX120121P00033000 at price 2.025; VXX: 33.76 2012-01-10 00:00:00 strategy [INFO] Exit 5245 VXX120121P00036000 -5245 VXX120121P00033000 at price 2.64; PnL: 3750.175; VXX: 30.64 2012-01-10 00:00:00 strategy [INFO] Portfolio Amount:109582.655 Allotted Portfolio Amount: 10958.2655 2012-01-10 00:00:00 strategy [INFO] Enter Position: +3135.41216023 VXX120218P00033000 -3135.41216023 VXX120121P00030000 at price 3.495; VXX: 30.64 2012-01-18 00:00:00 strategy [INFO] Exit 3135 VXX120218P00033000 -3135 VXX120121P00030000 at price 4.075; PnL: 2147.475; VXX: 30.15 2012-01-18 00:00:00 strategy [INFO] Portfolio Amount:112074.98 Allotted Portfolio Amount: 11207.498 2012-01-18 00:00:00 strategy [INFO] Enter Position: +8363.80447761 VXX120218P00032000 -8363.80447761 VXX120218P00030000 at price 1.34; VXX: 30.15 2012-01-25 00:00:00 strategy [INFO] Exit 8363 VXX120218P00032000 -8363 VXX120218P00030000 at price 1.75; PnL: 2759.79; VXX: 26.65 2012-01-25 00:00:00 strategy [INFO] Portfolio Amount:114625.695 Allotted Portfolio Amount: 11462.5695 2012-01-25 00:00:00 strategy [INFO] Enter Position: +8716.78288973 VXX120218P00028000 -8716.78288973 VXX120218P00026000 at price 1.315; VXX: 26.65 2012-02-03 00:00:00 strategy [INFO] Exit 8716 VXX120218P00028000 -8716 VXX120218P00026000 at price 1.745; PnL: 3529.98; VXX: 23.9869 2012-02-03 00:00:00 strategy [INFO] Portfolio Amount:118635.055 Allotted Portfolio Amount: 11863.5055 2012-02-03 00:00:00 strategy [INFO] Enter Position: +4995.16021053 VXX120317P00026000 -4995.16021053 VXX120218P00024000 at price 2.375; VXX: 23.9869 2012-02-10 00:00:00 strategy [INFO] Exit 4995 VXX120317P00026000 -4995 VXX120218P00024000 at price 1.67; PnL: -3971.025; VXX: 27.872 2012-02-10 00:00:00 strategy [INFO] Portfolio Amount:118235.455 Allotted Portfolio Amount: 11823.5455 2012-02-10 00:00:00 strategy [INFO] Enter Position: +6158.09661458 VXX120317P00030000 -6158.09661458 VXX120317P00027000 at price 1.92; VXX: 27.872 2012-02-23 00:00:00 strategy [INFO] Exit 6158 VXX120317P00030000 -6158 VXX120317P00027000 at price 2.6; PnL: 2155.3; VXX: 24.13 2012-02-23 00:00:00 strategy [INFO] Portfolio Amount:119467.055 Allotted Portfolio Amount: 11946.7055 2012-02-23 00:00:00 strategy [INFO] Enter Position: +17698.822963 VXX120317P00025000 -17698.822963 VXX120317P00024000 at price 0.675; VXX: 24.13 2012-03-06 00:00:00 strategy [INFO] Exit 17698 VXX120317P00025000 -17698 VXX120317P00024000 at price 0.37; PnL: -3539.6; VXX: 26.03 2012-03-06 00:00:00 strategy [INFO] Portfolio Amount:119644.035 Allotted Portfolio Amount: 11964.4035 2012-03-06 00:00:00 strategy [INFO] Enter Position: +4147.10693241 VXX120421P00028000 -4147.10693241 VXX120317P00026000 at price 2.885; VXX: 26.03 2012-03-14 00:00:00 strategy [INFO] Exit 4147 VXX120421P00028000 -4147 VXX120317P00026000 at price 2.85; PnL: -808.665; VXX: 21.9395 2012-03-14 00:00:00 strategy [INFO] Portfolio Amount:118420.67 Allotted Portfolio Amount: 11842.067 2012-03-14 00:00:00 strategy [INFO] Enter Position: +8643.84452555 VXX120421P00024000 -8643.84452555 VXX120421P00022000 at price 1.37; VXX: 21.9395 2012-03-21 00:00:00 strategy [INFO] Exit 8643 VXX120421P00024000 -8643 VXX120421P00022000 at price 1.8; PnL: 3327.555; VXX: 18.36 2012-03-21 00:00:00 strategy [INFO] Portfolio Amount:121748.225 Allotted Portfolio Amount: 12174.8225 2012-03-21 00:00:00 strategy [INFO] Enter Position: +18446.7007576 VXX120421P00019000 -18446.7007576 VXX120421P00018000 at price 0.66; VXX: 18.36 2012-03-26 00:00:00 strategy [INFO] Exit 18446 VXX120421P00019000 -18446 VXX120421P00018000 at price 0.98; PnL: 6548.33; VXX: 15.6685 2012-03-26 00:00:00 strategy [INFO] Portfolio Amount:124146.205 Allotted Portfolio Amount: 12414.6205 2012-03-26 00:00:00 strategy [INFO] Enter Position: +9196.01518519 VXX120421P00017000 -9196.01518519 VXX120421P00015000 at price 1.35; VXX: 15.6685 2012-03-27 00:00:00 strategy [INFO] Exit 9196 VXX120421P00017000 -9196 VXX120421P00015000 at price 0.885; PnL: 0.0; VXX: 17.2 2012-03-27 00:00:00 strategy [INFO] Portfolio Amount:123686.405 Allotted Portfolio Amount: 12368.6405 2012-03-27 00:00:00 strategy [INFO] Enter Position: +18323.9118519 VXX120421P00018000 -18323.9118519 VXX120421P00017000 at price 0.675; VXX: 17.2 2012-04-09 00:00:00 strategy [INFO] Exit 18323 VXX120421P00018000 -18323 VXX120421P00017000 at price 0.36; PnL: -4763.98; VXX: 18.982 2012-04-09 00:00:00 strategy [INFO] Portfolio Amount:115441.055 Allotted Portfolio Amount: 11544.1055 2012-04-09 00:00:00 strategy [INFO] Enter Position: +4943.94239829 VXX120519P00021000 -4943.94239829 VXX120421P00019000 at price 2.335; VXX: 18.982 2012-04-18 00:00:00 strategy [INFO] Exit 4943 VXX120519P00021000 -4943 VXX120421P00019000 at price 2.785; PnL: 2520.93; VXX: 18.25 2012-04-18 00:00:00 strategy [INFO] Portfolio Amount:118233.85 Allotted Portfolio Amount: 11823.385 2012-04-18 00:00:00 strategy [INFO] Enter Position: +8725.74538745 VXX120519P00020000 -8725.74538745 VXX120519P00018000 at price 1.355; VXX: 18.25 2012-05-01 00:00:00 strategy [INFO] Exit 8725 VXX120519P00020000 -8725 VXX120519P00018000 at price 1.79; PnL: 3708.125; VXX: 16.01 2012-05-01 00:00:00 strategy [INFO] Portfolio Amount:121767.475 Allotted Portfolio Amount: 12176.7475 2012-05-01 00:00:00 strategy [INFO] Enter Position: +18174.25 VXX120519P00017000 -18174.25 VXX120519P00016000 at price 0.67; VXX: 16.01 2012-05-04 00:00:00 strategy [INFO] Exit 18174 VXX120519P00017000 -18174 VXX120519P00016000 at price 0.465; PnL: -3816.54; VXX: 17.23 2012-05-04 00:00:00 strategy [INFO] Portfolio Amount:118768.765 Allotted Portfolio Amount: 11876.8765 2012-05-04 00:00:00 strategy [INFO] Enter Position: +5602.30023585 VXX120616P00019000 -5602.30023585 VXX120519P00017000 at price 2.12; VXX: 17.23 2012-05-16 00:00:00 strategy [INFO] Exit 5602 VXX120616P00019000 -5602 VXX120519P00017000 at price 1.375; PnL: -4733.69; VXX: 20.07 2012-05-16 00:00:00 strategy [INFO] Portfolio Amount:112130.395 Allotted Portfolio Amount: 11213.0395 2012-05-16 00:00:00 strategy [INFO] Enter Position: +8430.85676692 VXX120616P00022000 -8430.85676692 VXX120616P00020000 at price 1.33; VXX: 20.07 2012-05-18 00:00:00 strategy [INFO] Exit 8430 VXX120616P00022000 -8430 VXX120616P00020000 at price 0.965; PnL: -1854.6; VXX: 22.36 2012-05-18 00:00:00 strategy [INFO] Portfolio Amount:113732.095 Allotted Portfolio Amount: 11373.2095 2012-05-18 00:00:00 strategy [INFO] Enter Position: +8816.44147287 VXX120616P00024000 -8816.44147287 VXX120616P00022000 at price 1.29; VXX: 22.36 2012-05-29 00:00:00 strategy [INFO] Exit 8816 VXX120616P00024000 -8816 VXX120616P00022000 at price 1.75; PnL: 1322.4; VXX: 19.22 2012-05-29 00:00:00 strategy [INFO] Portfolio Amount:113379.455 Allotted Portfolio Amount: 11337.9455 2012-05-29 00:00:00 strategy [INFO] Enter Position: +17578.2100775 VXX120616P00020000 -17578.2100775 VXX120616P00019000 at price 0.645; VXX: 19.22 2012-05-30 00:00:00 strategy [INFO] Exit 17578 VXX120616P00020000 -17578 VXX120616P00019000 at price 0.46; PnL: 0.0; VXX: 20.55 2012-05-30 00:00:00 strategy [INFO] Portfolio Amount:112588.445 Allotted Portfolio Amount: 11258.8445 2012-05-30 00:00:00 strategy [INFO] Enter Position: +19752.3587719 VXX120616P00021000 -19752.3587719 VXX120616P00020000 at price 0.57; VXX: 20.55 2012-06-01 00:00:00 strategy [INFO] Exit 19752 VXX120616P00021000 -19752 VXX120616P00020000 at price 0.34; PnL: -4147.92; VXX: 22.58 2012-06-01 00:00:00 strategy [INFO] Portfolio Amount:109329.365 Allotted Portfolio Amount: 10932.9365 WARNING: Some output was deleted.
In [11]:
plt.plot()

TO-DO: Verify the spread; add a hedge order

In [ ]: