Ejemplo n.º 1
0
def test_save_orders():
    context = get_default_app_context()

    store = context.provider_mgr.get(DataStore.Mongo)
    store.start()

    ord_mrg = context.order_mgr
    ord_mrg.start()

    order = ord_mrg.send_order(
        NewOrderRequest(cl_id='test_stg', cl_ord_id=1, inst_id=1, portf_id='test_porf', action=OrdAction.BUY,
                        type=OrdType.LIMIT, qty=1000,
                        limit_price=18.5))
    order = ord_mrg.send_order(
        NewOrderRequest(cl_id='test_stg', cl_ord_id=2, inst_id=1, portf_id='test_porf', action=OrdAction.BUY,
                        type=OrdType.LIMIT, qty=1000,
                        limit_price=18.5))

    before = ord_mrg.all_items()

    ord_mrg.stop()
    ord_mrg.start()

    after = ord_mrg.all_items()

    print before
    print after

    p1 = Portfolio(portf_id='test_porf', cash=1000, app_context=context)
    p1.start()

    print "all"
    print p1.all_orders()
Ejemplo n.º 2
0
def test_save_orders():
    context = get_default_app_context()

    store = context.provider_mgr.get(DataStore.Mongo)
    store.start()

    ord_mrg = context.order_mgr
    ord_mrg.start()

    order = ord_mrg.send_order(
        NewOrderRequest(cl_id='test_stg',
                        cl_ord_id=1,
                        inst_id=1,
                        portf_id='test_porf',
                        action=OrdAction.BUY,
                        type=OrdType.LIMIT,
                        qty=1000,
                        limit_price=18.5))
    order = ord_mrg.send_order(
        NewOrderRequest(cl_id='test_stg',
                        cl_ord_id=2,
                        inst_id=1,
                        portf_id='test_porf',
                        action=OrdAction.BUY,
                        type=OrdType.LIMIT,
                        qty=1000,
                        limit_price=18.5))

    before = ord_mrg.all_items()

    ord_mrg.stop()
    ord_mrg.start()

    after = ord_mrg.all_items()

    print before
    print after

    p1 = Portfolio(portf_id='test_porf', cash=1000, app_context=context)
    p1.start()

    print "all"
    print p1.all_orders()
Ejemplo n.º 3
0
 def test_portfolio(self):
     self.assertEqual(Portfolio(cash=100000).cash, 100000)
Ejemplo n.º 4
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
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)
Ejemplo n.º 6
0
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)
Ejemplo n.º 7
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
Ejemplo n.º 8
0
 def new_portfolio(self, portf_id, cash=1000000, analyzers=None):
     portfolio = Portfolio(portf_id=portf_id,
                           cash=cash,
                           analyzers=analyzers)
     self.add(portfolio)
     return portfolio