Ejemplo n.º 1
0
    def test_run_with_empty_strategy(self):
        # Arrange
        usdjpy = InstrumentLoader.default_fx_ccy(TestStubs.symbol_usdjpy_fxcm())

        data = BacktestDataContainer()
        data.add_instrument(usdjpy)
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.BID, TestDataProvider.usdjpy_1min_bid())
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.ASK, TestDataProvider.usdjpy_1min_ask())

        strategies = [EmptyStrategy("001")]

        config = BacktestConfig(exec_db_type="in-memory")
        engine = BacktestEngine(
            data=data,
            strategies=strategies,
            venue=Venue("FXCM"),
            oms_type=OMSType.HEDGING,
            generate_position_ids=True,
            fill_model=FillModel(),
            config=config,
        )

        start = datetime(2013, 1, 1, 22, 0, 0, 0, tzinfo=pytz.utc)
        stop = datetime(2013, 8, 10, 0, 0, 0, 0, tzinfo=pytz.utc)

        stats_file = "perf_stats_backtest_run_empty.prof"
        cProfile.runctx("engine.run(start, stop)", globals(), locals(), stats_file)
        s = pstats.Stats(stats_file)
        s.strip_dirs().sort_stats("time").print_stats()

        self.assertTrue(True)
    def setUp(self):
        self.usdjpy = InstrumentLoader.default_fx_ccy(
            TestStubs.symbol_usdjpy_fxcm())
        data = BacktestDataContainer()
        data.add_instrument(self.usdjpy)
        data.add_bars(self.usdjpy.symbol, BarAggregation.MINUTE, PriceType.BID,
                      TestDataProvider.usdjpy_1min_bid()[:2000])
        data.add_bars(self.usdjpy.symbol, BarAggregation.MINUTE, PriceType.ASK,
                      TestDataProvider.usdjpy_1min_ask()[:2000])

        config = BacktestConfig(
            tick_capacity=1000,
            bar_capacity=1000,
            exec_db_type='in-memory',
            exec_db_flush=False,
            frozen_account=False,
            starting_capital=1000000,
            account_currency=USD,
            short_term_interest_csv_path='default',
            bypass_logging=False,
            level_console=LogLevel.DEBUG,
            level_file=LogLevel.DEBUG,
            level_store=LogLevel.WARNING,
            log_thread=False,
            log_to_file=False,
        )

        self.engine = BacktestEngine(
            data=data,
            strategies=[EmptyStrategy('000')],
            venue=Venue("FXCM"),
            oms_type=OMSType.HEDGING,
            generate_position_ids=True,
            config=config,
        )
Ejemplo n.º 3
0
    def test_given_list_of_ticks_aggregates_tick_bars(self):
        # Arrange
        tick_data = TestDataProvider.usdjpy_test_ticks()
        bid_data = TestDataProvider.usdjpy_1min_bid()
        ask_data = TestDataProvider.usdjpy_1min_ask()
        self.wrangler = TickDataWrangler(
            instrument=InstrumentLoader.default_fx_ccy(
                TestStubs.symbol_usdjpy_fxcm()),
            data_ticks=tick_data,
            data_bars_bid={BarAggregation.MINUTE: bid_data},
            data_bars_ask={BarAggregation.MINUTE: ask_data})
        self.wrangler.pre_process(0)

        bar_store = ObjectStorer()
        handler = bar_store.store_2
        symbol = TestStubs.symbol_usdjpy_fxcm()
        bar_spec = BarSpecification(3, BarAggregation.TICK, PriceType.MID)
        bar_type = BarType(symbol, bar_spec)

        clock = TestClock()
        logger = TestLogger(clock)

        ticks = self.wrangler.build_ticks()
        builder = BulkTickBarBuilder(bar_type, logger, handler)

        # Act
        builder.receive(ticks)

        # Assert
        self.assertEqual(333, len(bar_store.get_store()[0][1]))
Ejemplo n.º 4
0
 def setUp(self):
     # Fixture Setup
     self.usdjpy = InstrumentLoader.default_fx_ccy(
         TestStubs.symbol_usdjpy_fxcm())
     self.data = BacktestDataContainer()
     self.data.add_instrument(self.usdjpy)
     self.data.add_bars(self.usdjpy.symbol, BarAggregation.MINUTE,
                        PriceType.BID,
                        TestDataProvider.usdjpy_1min_bid()[:2000])
     self.data.add_bars(self.usdjpy.symbol, BarAggregation.MINUTE,
                        PriceType.ASK,
                        TestDataProvider.usdjpy_1min_ask()[:2000])
     self.test_clock = TestClock()
    def test_default_fx_with_3_dp_returns_expected_instrument(self):
        # Arrange
        loader = InstrumentLoader()

        # Act
        instrument = loader.default_fx_ccy(Symbol("USD/JPY", Venue('FXCM')))

        # Assert
        self.assertEqual(Symbol("USD/JPY", Venue('FXCM')), instrument.symbol)
        self.assertEqual(3, instrument.price_precision)
        self.assertEqual(Decimal("0.001"), instrument.tick_size)
        self.assertEqual(
            Currency(code='JPY', precision=2, currency_type=CurrencyType.FIAT),
            instrument.quote_currency)
Ejemplo n.º 6
0
    def test_default_fx_with_3_dp_returns_expected_instrument(self):
        # Arrange
        loader = InstrumentLoader()

        # Act
        instrument = loader.default_fx_ccy(Symbol('USDJPY',
                                                  Venue('DUKASCOPY')))

        # Assert
        self.assertEqual(Symbol('USDJPY', Venue('DUKASCOPY')),
                         instrument.symbol)
        self.assertEqual('USD/JPY', instrument.broker_symbol)
        self.assertEqual(3, instrument.price_precision)
        self.assertEqual(Decimal(0.001, 3), instrument.tick_size)
        self.assertEqual(392, instrument.quote_currency)
Ejemplo n.º 7
0
    def test_calculate_for_usdjpy(self):
        # Arrange
        sizer = FixedRiskSizer(
            InstrumentLoader.default_fx_ccy(TestStubs.symbol_usdjpy_fxcm()))
        equity = Money(1000000, USD)

        # Act
        result = sizer.calculate(
            equity,
            10,  # 0.1%
            Price("107.703"),
            Price("107.403"),
            exchange_rate=0.0093,
            units=1,
            unit_batch_size=1000,
        )

        # Assert
        self.assertEqual(Quantity(358000), result)
    def setUp(self):
        usdjpy = InstrumentLoader.default_fx_ccy(
            TestStubs.symbol_usdjpy_fxcm())
        data = BacktestDataContainer()
        data.add_instrument(usdjpy)
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.BID,
                      TestDataProvider.usdjpy_1min_bid()[:2000])
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.ASK,
                      TestDataProvider.usdjpy_1min_ask()[:2000])

        self.engine = BacktestEngine(
            data=data,
            strategies=[EmptyStrategy("000")],
            venue=Venue("FXCM"),
            oms_type=OMSType.HEDGING,
            generate_position_ids=True,
            fill_model=FillModel(),
            config=BacktestConfig(),
        )
Ejemplo n.º 9
0
    def test_build_with_tick_data(self):
        # Arrange
        tick_data = TestDataProvider.usdjpy_test_ticks()
        bid_data = TestDataProvider.usdjpy_1min_bid()
        ask_data = TestDataProvider.usdjpy_1min_ask()
        self.tick_builder = TickDataWrangler(
            instrument=InstrumentLoader.default_fx_ccy(
                TestStubs.symbol_usdjpy_fxcm()),
            data_ticks=tick_data,
            data_bars_bid={BarAggregation.MINUTE: bid_data},
            data_bars_ask={BarAggregation.MINUTE: ask_data})

        # Act
        self.tick_builder.pre_process(0)
        ticks = self.tick_builder.tick_data

        # Assert
        self.assertEqual(BarAggregation.TICK, self.tick_builder.resolution)
        self.assertEqual(1000, len(ticks))
        self.assertEqual(Timestamp("2013-01-01 22:02:35.907000", tz="UTC"),
                         ticks.iloc[1].name)
Ejemplo n.º 10
0
    def test_run_for_tick_processing(self):
        # Arrange
        usdjpy = InstrumentLoader.default_fx_ccy(TestStubs.symbol_usdjpy_fxcm())

        data = BacktestDataContainer()
        data.add_instrument(usdjpy)
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.BID, TestDataProvider.usdjpy_1min_bid())
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.ASK, TestDataProvider.usdjpy_1min_ask())

        strategies = [EMACross(
            symbol=usdjpy.symbol,
            bar_spec=TestStubs.bar_spec_1min_bid(),
            fast_ema=10,
            slow_ema=20)]

        config = BacktestConfig(
            exec_db_type="in-memory",
            bypass_logging=True,
            console_prints=False)

        engine = BacktestEngine(
            data=data,
            strategies=strategies,
            venue=Venue("FXCM"),
            oms_type=OMSType.HEDGING,
            generate_position_ids=True,
            config=config,
            fill_model=None,
        )

        start = datetime(2013, 2, 1, 0, 0, 0, 0, tzinfo=pytz.utc)
        stop = datetime(2013, 2, 10, 0, 0, 0, 0, tzinfo=pytz.utc)

        stats_file = "perf_stats_tick_processing.prof"
        cProfile.runctx("engine.run(start, stop)", globals(), locals(), stats_file)
        s = pstats.Stats(stats_file)
        s.strip_dirs().sort_stats("time").print_stats()

        self.assertTrue(True)
Ejemplo n.º 11
0
    def test_build_ticks_with_bar_data(self):
        # Arrange
        bid_data = TestDataProvider.usdjpy_1min_bid()
        ask_data = TestDataProvider.usdjpy_1min_ask()
        self.tick_builder = TickDataWrangler(
            instrument=InstrumentLoader.default_fx_ccy(
                TestStubs.symbol_usdjpy_fxcm()),
            data_ticks=None,
            data_bars_bid={BarAggregation.MINUTE: bid_data},
            data_bars_ask={BarAggregation.MINUTE: ask_data})

        # Act
        self.tick_builder.pre_process(0)
        tick_data = self.tick_builder.tick_data

        # Assert
        self.assertEqual(BarAggregation.MINUTE, self.tick_builder.resolution)
        self.assertEqual(1491252, len(tick_data))
        self.assertEqual(
            Timestamp("2013-01-01T21:59:59.900000+00:00", tz="UTC"),
            tick_data.iloc[0].name)
        self.assertEqual(
            Timestamp("2013-01-01T21:59:59.900000+00:00", tz="UTC"),
            tick_data.iloc[1].name)
        self.assertEqual(
            Timestamp("2013-01-01T21:59:59.900000+00:00", tz="UTC"),
            tick_data.iloc[2].name)
        self.assertEqual(
            Timestamp("2013-01-01T22:00:00.000000+00:00", tz="UTC"),
            tick_data.iloc[3].name)
        self.assertEqual(0, tick_data.iloc[0]["symbol"])
        self.assertEqual(0, tick_data.iloc[0]["bid_size"])
        self.assertEqual(0, tick_data.iloc[0]["ask_size"])
        self.assertEqual(0, tick_data.iloc[1]["bid_size"])
        self.assertEqual(0, tick_data.iloc[1]["ask_size"])
        self.assertEqual(0, tick_data.iloc[2]["bid_size"])
        self.assertEqual(0, tick_data.iloc[2]["ask_size"])
        self.assertEqual(1.5, tick_data.iloc[3]["bid_size"])
        self.assertEqual(2.25, tick_data.iloc[3]["ask_size"])
    def test_timer_alert_sequencing_with_tick_execution(self):
        # Arrange
        usdjpy = InstrumentLoader.default_fx_ccy(
            TestStubs.symbol_usdjpy_fxcm())
        data = BacktestDataContainer()
        data.add_instrument(usdjpy)
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.BID,
                      TestDataProvider.usdjpy_1min_bid()[:2000])
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.ASK,
                      TestDataProvider.usdjpy_1min_ask()[:2000])

        bar_type = TestStubs.bartype_usdjpy_1min_bid()

        tick_tock = TickTock(instrument=usdjpy, bar_type=bar_type)

        engine = BacktestEngine(
            data=data,
            strategies=[tick_tock],
            venue=Venue("FXCM"),
            oms_type=OMSType.HEDGING,
            generate_position_ids=True,
            fill_model=FillModel(),
            config=BacktestConfig(),
        )

        start = datetime(2013, 1, 1, 22, 2, 0, 0)
        stop = datetime(2013, 1, 1, 22, 5, 0, 0)

        # Act
        engine.run(start, stop)

        # Assert
        self.assertEqual(Timestamp("2013-01-01 21:59:59.900000+0000"),
                         engine.data_engine.min_timestamp)
        self.assertEqual(Timestamp("2013-01-02 09:19:00+0000"),
                         engine.data_engine.max_timestamp)
        self.assertEqual([x.timestamp for x in tick_tock.store],
                         sorted([x.timestamp
                                 for x in tick_tock.store]))  # Events in order
    def setUp(self):
        # Fixture Setup
        self.clock = TestClock()
        self.uuid_factory = TestUUIDFactory()
        self.logger = TestLogger(self.clock)

        self.portfolio = Portfolio(
            clock=self.clock,
            uuid_factory=self.uuid_factory,
            logger=self.logger,
        )

        self.data_engine = DataEngine(
            tick_capacity=1000,
            bar_capacity=1000,
            portfolio=self.portfolio,
            clock=self.clock,
            uuid_factory=self.uuid_factory,
            logger=self.logger,
        )

        self.data_engine.set_use_previous_close(False)

        self.analyzer = PerformanceAnalyzer()

        trader_id = TraderId('TESTER', '000')
        account_id = TestStubs.account_id()

        self.exec_db = BypassExecutionDatabase(
            trader_id=trader_id,
            logger=self.logger,
        )

        self.exec_engine = ExecutionEngine(
            database=self.exec_db,
            portfolio=self.portfolio,
            clock=self.clock,
            uuid_factory=self.uuid_factory,
            logger=self.logger,
        )

        usdjpy = InstrumentLoader.default_fx_ccy(TestStubs.symbol_usdjpy_fxcm())

        self.market = SimulatedMarket(
            venue=Venue("FXCM"),
            oms_type=OMSType.HEDGING,
            generate_position_ids=True,
            exec_cache=self.exec_engine.cache,
            instruments={usdjpy.symbol: usdjpy},
            config=BacktestConfig(),
            fill_model=FillModel(),
            commission_model=GenericCommissionModel(),
            clock=self.clock,
            uuid_factory=TestUUIDFactory(),
            logger=self.logger,
        )

        self.exec_client = BacktestExecClient(
            market=self.market,
            account_id=account_id,
            engine=self.exec_engine,
            logger=self.logger,
        )

        self.exec_engine.register_client(self.exec_client)
        self.market.register_client(self.exec_client)
        self.exec_engine.process(TestStubs.event_account_state())

        self.market.process_tick(TestStubs.quote_tick_3decimal(usdjpy.symbol))  # Prepare market

        self.strategy = TradingStrategy(order_id_tag="001")
        self.strategy.register_trader(
            trader_id=TraderId("TESTER", "000"),
            clock=self.clock,
            uuid_factory=self.uuid_factory,
            logger=self.logger,
        )

        self.strategy.register_data_engine(self.data_engine)
        self.strategy.register_execution_engine(self.exec_engine)

        print("\n")
Ejemplo n.º 14
0
    def setUp(self):
        # Fixture Setup
        usdjpy = InstrumentLoader.default_fx_ccy(
            TestStubs.symbol_usdjpy_fxcm())
        data = BacktestDataContainer()
        data.add_instrument(usdjpy)
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.BID,
                      TestDataProvider.usdjpy_1min_bid()[:2000])
        data.add_bars(usdjpy.symbol, BarAggregation.MINUTE, PriceType.ASK,
                      TestDataProvider.usdjpy_1min_ask()[:2000])

        clock = TestClock()
        uuid_factory = TestUUIDFactory()
        logger = TestLogger(clock)
        trader_id = TraderId("TESTER", "000")
        account_id = TestStubs.account_id()

        self.portfolio = Portfolio(
            clock=clock,
            uuid_factory=uuid_factory,
            logger=logger,
        )

        data_engine = BacktestDataEngine(
            data=data,
            tick_capacity=1000,
            bar_capacity=1000,
            portfolio=self.portfolio,
            clock=clock,
            logger=logger,
        )

        self.analyzer = PerformanceAnalyzer()

        self.exec_db = BypassExecutionDatabase(
            trader_id=trader_id,
            logger=logger,
        )

        self.exec_engine = ExecutionEngine(
            database=self.exec_db,
            portfolio=self.portfolio,
            clock=clock,
            uuid_factory=uuid_factory,
            logger=logger,
        )

        self.market = SimulatedMarket(
            venue=Venue("FXCM"),
            oms_type=OMSType.HEDGING,
            generate_position_ids=True,
            exec_cache=self.exec_engine.cache,
            instruments={usdjpy.symbol: usdjpy},
            config=BacktestConfig(),
            fill_model=FillModel(),
            commission_model=GenericCommissionModel(),
            clock=clock,
            uuid_factory=TestUUIDFactory(),
            logger=logger,
        )

        self.exec_client = BacktestExecClient(
            market=self.market,
            account_id=account_id,
            engine=self.exec_engine,
            logger=logger,
        )

        self.exec_engine.register_client(self.exec_client)

        strategies = [
            EmptyStrategy("001"),
            EmptyStrategy("002"),
        ]

        self.trader = Trader(
            trader_id=trader_id,
            strategies=strategies,
            data_engine=data_engine,
            exec_engine=self.exec_engine,
            clock=clock,
            uuid_factory=uuid_factory,
            logger=logger,
        )
Ejemplo n.º 15
0
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.
# -------------------------------------------------------------------------------------------------

import unittest

from nautilus_trader.backtest.loaders import InstrumentLoader
from nautilus_trader.model.currencies import USD
from nautilus_trader.model.objects import Money
from nautilus_trader.model.objects import Price
from nautilus_trader.model.objects import Quantity
from nautilus_trader.trading.sizing import FixedRiskSizer
from tests.test_kit.stubs import TestStubs

USDJPY = InstrumentLoader.default_fx_ccy(TestStubs.symbol_gbpusd_fxcm())


class FixedRiskSizerTests(unittest.TestCase):
    def setUp(self):
        # Fixture Setup
        self.sizer = FixedRiskSizer(USDJPY)

    def test_calculate_single_unit_size(self):
        # Arrange
        equity = Money(1000000, USD)

        # Act
        result = self.sizer.calculate(
            equity,
            10,  # 0.1%