def init_context(self, symbols, asset, app_config): self.app_context = ApplicationContext(app_config=app_config) inst_df = build_inst_dataframe_from_list(symbols) ccy_df = pd.DataFrame({ "ccy_id": ["USD", "HKD"], "name": ["US Dollar", "HK Dollar"] }) exchange_df = pd.DataFrame({ "exch_id": ["NYSE"], "name": ["New York Stock Exchange"] }) ref_data_mgr = MockRefDataManager(inst_df=inst_df, ccy_df=ccy_df, exch_df=exchange_df) self.app_context.ref_data_mgr = ref_data_mgr self.app_context.start() self.portfolio = self.app_context.portf_mgr.new_portfolio( portf_id='test2', cash=TestCompareWithFunctionalBacktest.init_cash) self.portfolio.start(self.app_context)
symbols = ['SPY', 'VXX', 'XLV', 'XIV'] inst_df = build_inst_dataframe_from_list(symbols) # ccy_id,name ccy_df = pd.DataFrame({ "ccy_id": ["USD", "HKD"], "name": ["US Dollar", "HK Dollar"] }) exchange_df = pd.DataFrame({ "exch_id": ["NYSE"], "name": ["New York Stock Exchange"] }) mgr = MockRefDataManager(inst_df, ccy_df, exchange_df) feed = PandaH5DataFeed('/Users/jchan/workspace/data/Equity/US/etf.h5', ref_data_mgr=mgr) today = date.today() startDate = date(2011, 1, 1) sub_key0 = HistDataSubscriptionKey(inst_id=0, provider_id=PandaH5DataFeed.ID, data_type=Bar, bar_size=BarSize.D1, from_date=startDate, to_date=today) sub_key1 = HistDataSubscriptionKey(inst_id=1, provider_id=PandaH5DataFeed.ID,
def main(): symbols = ['SPY', 'VXX', 'XLV', 'XIV'] inst_df = build_inst_dataframe_from_list(symbols) ccy_df = pd.DataFrame({ "ccy_id": ["USD", "HKD"], "name": ["US Dollar", "HK Dollar"] }) exchange_df = pd.DataFrame({ "exch_id": ["NYSE"], "name": ["New York Stock Exchange"] }) mgr = MockRefDataManager(inst_df=inst_df, ccy_df=ccy_df, exch_df=exchange_df) portfolio = Portfolio(portf_id='test', cash=100000) start_date = datetime(2000, 1, 1) num_days = 3000 dates = [start_date + timedelta(days=i) for i in range(num_days)] sigma = 0.3 x0 = 100 dt = 1. / 252 dW = np.random.normal(0, math.sqrt(dt), num_days) asset = [] asset.append(x0) for i in xrange(1, num_days): xprev = asset[-1] x = xprev + xprev * 0.02 * dt + sigma * xprev * dW[i] asset.append(x) df = pd.DataFrame({ "dates": dates, "Open": asset, "High": asset, "Low": asset, "Close": asset, "Volume": 10000 * np.ones(num_days) }) df = df.set_index(keys="dates") dict_df = {'SPY': df, 'VXX': df, 'XLV': df, 'XIV': df} feed = PandasMemoryDataFeed(dict_df, ref_data_mgr=mgr) broker = Simulator() instrument = 0 config = BacktestingConfig(stg_id="sma", portfolio_id='test', instrument_ids=[instrument], subscription_types=[ BarSubscriptionType(bar_type=BarType.Time, bar_size=BarSize.D1) ], from_date=dates[0], to_date=dates[-1], broker_id=Simulator.ID, feed_id=PandasMemoryDataFeed.ID) close = inst_data_mgr.get_series("Bar.%s.Time.86400" % instrument) mgr.get_insts([instrument]) mgr.get_inst(instrument) # strategy = Down2PctStrategy("down2%", portfolio, # instrument=0, qty=1000, trading_config=config, ref_data_mgr=mgr) strategy = SMAStrategy("sma", stg_configs={'qty': 1}) runner = BacktestRunner(strategy) runner.start() print portfolio.get_result() # pyfolio rets = strategy.get_portfolio().get_return() # import pyfolio as pf # pf.create_returns_tear_sheet(rets) # pf.create_full_tear_sheet(rets) # build in plot plotter = StrategyPlotter(strategy) plotter.plot(instrument=0) # import matplotlib.pyplot as plt # plt.show() import talib sma10 = talib.SMA(df.Close.values, 10) sma25 = talib.SMA(df.Close.values, 25) # signal = pd.Series(1*(sma10 > sma25),index=df.index.tz_localize("UTC")) signal = pd.Series(1 * (sma10 > sma25), index=df.index) target_rets = df["Close"].pct_change() * signal.shift(1) target_rets.index = target_rets.index.tz_localize("UTC") print target_rets.values[1:] - rets.values
def main(): symbols = ['XXX', 'YYY'] inst_df = build_inst_dataframe_from_list(symbols) ccy_df = pd.DataFrame({ "ccy_id": ["USD", "HKD"], "name": ["US Dollar", "HK Dollar"] }) exchange_df = pd.DataFrame({ "exch_id": ["NYSE"], "name": ["New York Stock Exchange"] }) mgr = MockRefDataManager(inst_df=inst_df, ccy_df=ccy_df, exch_df=exchange_df) portfolio = Portfolio(cash=100000) start_date = datetime(2000, 1, 1) num_days = 300 dates = [start_date + timedelta(days=i) for i in range(num_days)] drift = lambda x, t: 0.02 * x diffusion = lambda x, t: 0.3 * x ou_k = 2.0 ou_theta = 0.25 ou_eta = 0.08 ou_drift = lambda x, t: ou_k * (ou_theta - x) ou_diffusion = lambda x, t: ou_eta * x sim_asset_paths = euler(drift, diffusion, 100.0, 1.0, num_days, 10) sim_spread_paths = euler(ou_drift, ou_diffusion, 0.1, 1.0, num_days, 10) asset_x = sim_asset_paths[1, :] spread = sim_spread_paths[1, :] asset_y = np.exp(np.log(asset_x) + spread) asset_x_df = pd.DataFrame({ "dates": dates, "Open": asset_x, "High": asset_x, "Low": asset_x, "Close": asset_x, "Volume": 10000 * np.ones(num_days) }) asset_y_df = pd.DataFrame({ "dates": dates, "Open": asset_y, "High": asset_y, "Low": asset_y, "Close": asset_y, "Volume": 10000 * np.ones(num_days) }) asset_x_df = asset_x_df.set_index(keys="dates") asset_y_df = asset_y_df.set_index(keys="dates") dict_df = {'XXX': asset_x_df, 'YYY': asset_y_df} feed = PandasMemoryDataFeed(dict_df, ref_data_mgr=mgr) broker = Simulator() config = BacktestingConfig(stg_id="pairou", portfolio_id='test', instrument_ids=[0, 1], subscription_types=[ BarSubscriptionType(bar_type=BarType.Time, bar_size=BarSize.D1) ], from_date=dates[0], to_date=dates[-1], broker_id=Simulator.ID, feed_id=PandasMemoryDataFeed.ID) ou_params = {"k": ou_k, "theta": ou_theta, "eta": ou_eta} strategy = PairTradingWithOUSpread("pairou", ou_params=ou_params, gamma=1.0, trading_config=config, ref_data_mgr=mgr) runner = BacktestRunner(strategy) runner.start() print portfolio.get_result() # pyfolio rets = strategy.get_portfolio().get_return() # import pyfolio as pf # pf.create_returns_tear_sheet(rets) # pf.create_full_tear_sheet(rets) # build in plot plotter = StrategyPlotter(strategy) plotter.plot(instrument=0)
def main(): symbols = ['SPY', 'VXX', 'XLV', 'XIV'] inst_df = build_inst_dataframe_from_list(symbols) ccy_df = pd.DataFrame({"ccy_id": ["USD", "HKD"], "name": ["US Dollar", "HK Dollar"]}) exchange_df = pd.DataFrame({"exch_id": ["NYSE"], "name": ["New York Stock Exchange"]}) mgr = MockRefDataManager(inst_df=inst_df, ccy_df=ccy_df, exch_df=exchange_df) portfolio = Portfolio(portf_id='test', cash=100000) start_date = datetime(2000, 1, 1) num_days = 3000 dates = [start_date + timedelta(days=i) for i in range(num_days)] sigma = 0.3 x0 = 100 dt = 1. / 252 dW = np.random.normal(0, math.sqrt(dt), num_days) asset = [] asset.append(x0) for i in xrange(1, num_days): xprev = asset[-1] x = xprev + xprev * 0.02 * dt + sigma * xprev * dW[i] asset.append(x) df = pd.DataFrame({"dates": dates, "Open": asset, "High": asset, "Low": asset, "Close": asset, "Volume": 10000 * np.ones(num_days)}) df = df.set_index(keys="dates") dict_df = {'SPY': df, 'VXX': df, 'XLV': df, 'XIV': df} feed = PandasMemoryDataFeed(dict_df, ref_data_mgr=mgr) broker = Simulator() instrument = 0 config = BacktestingConfig(stg_id="sma", portfolio_id='test', instrument_ids=[instrument], subscription_types=[BarSubscriptionType(bar_type=BarType.Time, bar_size=BarSize.D1)], from_date=dates[0], to_date=dates[-1], broker_id=Simulator.ID, feed_id=PandasMemoryDataFeed.ID) close = inst_data_mgr.get_series("Bar.%s.Time.86400" % instrument) mgr.get_insts([instrument]) mgr.get_inst(instrument) # strategy = Down2PctStrategy("down2%", portfolio, # instrument=0, qty=1000, trading_config=config, ref_data_mgr=mgr) strategy = SMAStrategy("sma", stg_configs={'qty':1}) runner = BacktestRunner(strategy) runner.start() print portfolio.get_result() # pyfolio rets = strategy.get_portfolio().get_return() # import pyfolio as pf # pf.create_returns_tear_sheet(rets) # pf.create_full_tear_sheet(rets) # build in plot plotter = StrategyPlotter(strategy) plotter.plot(instrument=0) # import matplotlib.pyplot as plt # plt.show() import talib sma10 = talib.SMA(df.Close.values, 10) sma25 = talib.SMA(df.Close.values, 25) # signal = pd.Series(1*(sma10 > sma25),index=df.index.tz_localize("UTC")) signal = pd.Series(1 * (sma10 > sma25), index=df.index) target_rets = df["Close"].pct_change() * signal.shift(1) target_rets.index = target_rets.index.tz_localize("UTC") print target_rets.values[1:] - rets.values