示例#1
0
    def setUp(self):
        tickers = [BloombergTicker("AAPL US Equity")]
        all_fields = PriceField.ohlcv()

        self._mocked_prices_arr = self._make_mock_data_array(
            tickers, all_fields)
        self._price_provider_mock = PresetDataProvider(self._mocked_prices_arr,
                                                       self.data_start_date,
                                                       self.data_end_date,
                                                       self.frequency)

        risk_estimation_factor = 0.05

        ts = self._test_trading_session_init()
        alpha_model = self.DummyAlphaModel(risk_estimation_factor,
                                           ts.data_handler)

        # Mock the backtest result in order to be able to compare transactions
        self.transactions = []
        ts.monitor.record_transaction.side_effect = lambda transaction: self.transactions.append(
            transaction)
        self.portfolio = ts.portfolio

        strategy = AlphaModelStrategy(ts, {alpha_model: tickers},
                                      use_stop_losses=True)
        OnBeforeMarketOpenSignalGeneration(strategy)
        ts.start_trading()
示例#2
0
    def test_limiting_open_positions_2_position(self):
        max_open_positions = 2
        strategy = AlphaModelStrategy(self.ts,
                                      self.model_tickers_dict,
                                      use_stop_losses=False,
                                      max_open_positions=max_open_positions)
        OnBeforeMarketOpenSignalGeneration(strategy)
        self.ts.start_trading()

        number_of_assets = self._get_assets_number_series(self.ts.portfolio)
        number_of_assets_exceeded_the_limit = number_of_assets.where(
            number_of_assets > max_open_positions).any()

        self.assertFalse(number_of_assets_exceeded_the_limit)
示例#3
0
def get_trade_rets_values(ts: BacktestTradingSession,
                          model: AlphaModel) -> List[float]:
    model_tickers_dict = {model: [BloombergTicker('SVXY US Equity')]}

    strategy = AlphaModelStrategy(ts, model_tickers_dict, use_stop_losses=True)
    OnBeforeMarketOpenSignalGeneration(strategy)
    ts.use_data_preloading([BloombergTicker('SVXY US Equity')])
    ts.start_trading()

    trades_generator = TradesGenerator()
    trades = trades_generator.create_trades_from_backtest_positions(
        ts.portfolio.closed_positions())
    returns_of_trades = [t.pnl for t in trades]
    return returns_of_trades
示例#4
0
def main():
    initial_risk = 0.03

    start_date = str_to_date('2010-01-01')
    end_date = str_to_date('2011-12-31')

    # Use the preset daily data provider
    data_provider = daily_data_provider

    # ----- build trading session ----- #
    session_builder = container.resolve(
        BacktestTradingSessionBuilder)  # type: BacktestTradingSessionBuilder
    session_builder.set_backtest_name('Moving Average Alpha Model Backtest')
    session_builder.set_position_sizer(InitialRiskPositionSizer,
                                       initial_risk=initial_risk)
    session_builder.set_commission_model(IBCommissionModel)
    session_builder.set_data_provider(data_provider)
    session_builder.set_frequency(Frequency.DAILY)

    ts = session_builder.build(start_date, end_date)

    # ----- build models ----- #
    model = MovingAverageAlphaModel(fast_time_period=5,
                                    slow_time_period=20,
                                    risk_estimation_factor=1.25,
                                    data_provider=ts.data_handler)
    model_tickers = [
        DummyTicker('AAA'),
        DummyTicker('BBB'),
        DummyTicker('CCC'),
        DummyTicker('DDD'),
        DummyTicker('EEE'),
        DummyTicker('FFF')
    ]
    model_tickers_dict = {model: model_tickers}

    # ----- preload price data ----- #
    ts.use_data_preloading(model_tickers)
    # Verify the checksum of preloaded data with the precomputed value
    ts.verify_preloaded_data("778bbaac65cb0a5a848167999b88cf29a1cd8467")

    # ----- start trading ----- #
    strategy = AlphaModelStrategy(ts, model_tickers_dict, use_stop_losses=True)

    # Set the signal generation and orders placement to be performed at the OnBeforeMarketOpen event
    OnBeforeMarketOpenSignalGeneration(strategy)

    ts.start_trading()
示例#5
0
def main():
    # settings
    backtest_name = 'Simple MA Strategy Demo'
    start_date = str_to_date("2010-01-01")
    end_date = str_to_date("2015-03-01")
    ticker = DummyTicker("AAA")

    # configuration
    session_builder = container.resolve(BacktestTradingSessionBuilder)  # type: BacktestTradingSessionBuilder
    session_builder.set_frequency(Frequency.DAILY)
    session_builder.set_backtest_name(backtest_name)
    session_builder.set_data_provider(daily_data_provider)

    ts = session_builder.build(start_date, end_date)

    OnBeforeMarketOpenSignalGeneration(SimpleMAStrategy(ts, ticker))
    ts.start_trading()
示例#6
0
def run_strategy(data_provider: DataProvider) -> Tuple[float, str]:
    """ Returns the strategy end result and checksum of the preloaded data. """

    model_tickers = [BloombergFutureTicker("Corn", "C {} Comdty", 1, 10, 1)]
    start_date = str_to_date('2003-05-30')
    end_date = str_to_date('2009-01-01')
    initial_risk = 0.006

    # ----- build trading session ----- #
    settings = get_test_settings()
    session_builder = BacktestTradingSessionBuilder(data_provider, settings,
                                                    PDFExporter(settings),
                                                    ExcelExporter(settings))
    session_builder.set_backtest_name('Simple Futures Strategy')
    session_builder.set_position_sizer(InitialRiskPositionSizer,
                                       initial_risk=initial_risk)
    session_builder.set_frequency(Frequency.DAILY)
    session_builder.set_data_provider(data_provider)
    session_builder.set_monitor_settings(BacktestMonitorSettings.no_stats())
    ts = session_builder.build(start_date, end_date)

    # ----- build models ----- #
    model = SimpleFuturesModel(fast_time_period=50,
                               slow_time_period=100,
                               risk_estimation_factor=3,
                               data_provider=ts.data_handler)
    model_tickers_dict = {model: model_tickers}

    # ----- start trading ----- #
    strategy = AlphaModelStrategy(ts,
                                  model_tickers_dict,
                                  use_stop_losses=False)
    OnBeforeMarketOpenSignalGeneration(strategy)

    ts.use_data_preloading(model_tickers)
    ts.start_trading()

    data_checksum = ts.get_preloaded_data_checksum()
    actual_end_value = ts.portfolio.portfolio_eod_series()[-1]
    return actual_end_value, data_checksum
def main():
    initial_risk = 0.03

    start_date = str_to_date('2016-01-01')
    end_date = str_to_date('2017-12-31')

    # ----- build trading session ----- #
    session_builder = container.resolve(
        BacktestTradingSessionBuilder)  # type: BacktestTradingSessionBuilder
    session_builder.set_backtest_name('Moving Average Alpha Model Backtest')
    session_builder.set_position_sizer(InitialRiskPositionSizer,
                                       initial_risk=initial_risk)
    session_builder.set_commission_model(IBCommissionModel)
    session_builder.set_frequency(Frequency.DAILY)
    ts = session_builder.build(start_date, end_date)

    # ----- build models ----- #
    model = MovingAverageAlphaModel(fast_time_period=5,
                                    slow_time_period=20,
                                    risk_estimation_factor=1.25,
                                    data_provider=ts.data_handler)
    model_tickers = [
        QuandlTicker('AAPL', 'WIKI'),
        QuandlTicker('AMZN', 'WIKI')
    ]
    model_tickers_dict = {model: model_tickers}

    # ----- preload price data ----- #
    ts.use_data_preloading(model_tickers)

    # ----- start trading ----- #
    OnBeforeMarketOpenSignalGeneration(
        AlphaModelStrategy(ts, model_tickers_dict, use_stop_losses=True))
    ts.start_trading()

    # ----- use results ----- #
    backtest_tms = ts.portfolio.portfolio_eod_series().to_log_returns()
    print("mean daily log return: {}".format(backtest_tms.mean()))
    print("std of daily log returns: {}".format(backtest_tms.std()))