def test_stitch(): stitch_points = ["2015-03-13", "2015-04-15"] dfs = [] ctd = {} base = "test/data_stitch/vix%s.csv" for f in ["may", "june", "july"]: tmp = pd.read_csv(base % f, index_col=0, parse_dates=True) dfs.append(tmp) ctd[f] = tmp res = futures.stitch_prices(dfs, "Settle", stitch_points, ctd) exp = pd.read_csv("test/data_stitch/stitch_expected.csv", index_col=0, parse_dates=True) exp["res"] = res assert np.sum(exp.res - exp.Settle) < 1
def test_stitch(): stitch_points = ['2015-03-13', '2015-04-15'] dfs = [] ctd = {} base = 'test/data_stitch/vix%s.csv' for f in ['may', 'june', 'july']: tmp = pd.read_csv(base % f, index_col=0, parse_dates=True) dfs.append(tmp) ctd[f] = tmp res = futures.stitch_prices(dfs, 'Settle', stitch_points, ctd) exp = pd.read_csv('test/data_stitch/stitch_expected.csv', index_col=0, parse_dates=True) exp['res'] = res assert (np.sum(exp.res - exp.Settle) < 1)
def stitch_contracts(cts_assigned, ctd, price_col): """ Using a date indexed contracts series and a dictionary of contracts, creates a continuous time series. Input cts_assigned: Date indexed series with each date mapped to a contract in YYYYMM format ctd: Dictionary of contracts, key is a string 'YYYYMM'. This is the universe of contracts for that instrument. Returns Pandas Series """ rolls = rolldates(cts_assigned) rolldates2 = [] for (rolldate, from_con, to_con) in rolls: if str(from_con) in ctd.keys() and str(to_con) in ctd.keys(): rolldates2.append((rolldate, from_con, to_con)) rolldates3 = [] for i,(rolldate, from_con, to_con) in enumerate(rolldates2): # it is possible the rollover date is not present in both # contracts. This rolldate is calculated arithmetically, # remember, so it could fall on a weekend, etc. So we need to # seek a date that is in both contracts, starting from the # calculated rollover date. The algorithm is go back 0, go # forward 1, back 2, so an expanding window of possible dates # centered around the first suggestion are all tried. Since # the first try is 0, that represents no change i.e. is the # first suggestion itself. Whichever date works, the loop will # exit immediately and no other tries need to be made. for j in range(300): rolldate += np.power(-1,j)*datetime.timedelta(days=j) if rolldate in ctd[str(from_con)].index and rolldate in ctd[str(to_con)].index: break assert (j != 299) rolldates3.append((rolldate, from_con, to_con)) rolldates4 = []; contract_ids = [] for d,f,t in rolldates3: contract_ids.append(f) contract_ids.append(t) rolldates4.append(d) contracts = [ctd[x].copy() for x in list(np.unique(contract_ids))] df_stitched = futures.stitch_prices(contracts, 's', rolldates4, ctd) return df_stitched