예제 #1
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Monthly Liquidate/Rebalance on 60%/40% SPY/AGG Portfolio']
    initial_equity = 500000.0
    start_date = datetime.datetime(2006, 11, 1)
    end_date = datetime.datetime(2016, 10, 12)

    # Use the Monthly Liquidate And Rebalance strategy
    events_queue = queue.Queue()
    strategy = MonthlyLiquidateRebalanceStrategy(tickers, events_queue)

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    ticker_weights = {
        "SPY": 0.6,
        "AGG": 0.4,
    }
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        position_sizer=position_sizer,
        title=title,
        benchmark=tickers[0],
    )
    results = backtest.start_trading(testing=testing)
    return results
def run_monthly_rebalance(config, testing, filename, benchmark, ticker_weights,
                          title_str, start_date, end_date, equity):
    config = settings.from_file(config, testing)
    tickers = [t for t in ticker_weights.keys()]

    # Set up variables needed for backtest
    events_queue = queue.Queue()
    csv_dir = config.CSV_DATA_DIR
    initial_equity = PriceParser.parse(equity)

    # Use Yahoo Daily Price Handler
    price_handler = YahooDailyCsvBarPriceHandler(csv_dir,
                                                 events_queue,
                                                 tickers,
                                                 start_date=start_date,
                                                 end_date=end_date)

    # Use the monthly liquidate and rebalance strategy
    strategy = MonthlyLiquidateRebalanceStrategy(tickers, events_queue)
    strategy = Strategies(strategy, DisplayStrategy())

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Use an example Risk Manager
    risk_manager = ExampleRiskManager()

    # Use the default Portfolio Handler
    portfolio_handler = PortfolioHandler(initial_equity, events_queue,
                                         price_handler, position_sizer,
                                         risk_manager)

    # Use the ExampleCompliance component
    compliance = ExampleCompliance(config)
예제 #3
0
def run_monthly_rebalance(tickers, ticker_weights, title, start_date, end_date,
                          initial_equity):
    testing = False
    config = settings.from_file(settings.DEFAULT_CONFIG_FILENAME, testing)

    # Use the Monthly Liquidate And Rebalance strategy
    events_queue = queue.Queue()
    strategy = MonthlyLiquidateRebalanceStrategy(tickers, events_queue)

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        position_sizer=position_sizer,
        title=[title],
        benchmark=tickers[0],
    )
    results = backtest.start_trading(testing=testing)
    return results
def run(config, testing, tickers, filename):

    # Set up variables needed for backtest
    events_queue = queue.Queue()
    csv_dir = config.CSV_DATA_DIR
    initial_equity = PriceParser.parse(500000.00)
    start_date = datetime.datetime(2006, 11, 1)
    end_date = datetime.datetime(2016, 10, 12)

    # Use Yahoo Daily Price Handler
    price_handler = YahooDailyCsvBarPriceHandler(csv_dir,
                                                 events_queue,
                                                 tickers,
                                                 start_date=start_date,
                                                 end_date=end_date)

    # Use the monthly liquidate and rebalance strategy
    strategy = MonthlyLiquidateRebalanceStrategy(tickers, events_queue)
    strategy = Strategies(strategy, DisplayStrategy())

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    ticker_weights = {
        "SPY": 0.6,
        "AGG": 0.4,
    }
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Use an example Risk Manager
    risk_manager = ExampleRiskManager()

    # Use the default Portfolio Handler
    portfolio_handler = PortfolioHandler(initial_equity, events_queue,
                                         price_handler, position_sizer,
                                         risk_manager)

    # Use the ExampleCompliance component
    compliance = ExampleCompliance(config)

    # Use a simulated IB Execution Handler
    execution_handler = IBSimulatedExecutionHandler(events_queue,
                                                    price_handler, compliance)

    # Use the default Statistics
    title = ["US Equities/Bonds 60/40 ETF Strategy"]
    benchmark = "SPY"
    statistics = TearsheetStatistics(config, portfolio_handler, title,
                                     benchmark)

    # Set up the backtest
    backtest = Backtest(price_handler, strategy, portfolio_handler,
                        execution_handler, position_sizer, risk_manager,
                        statistics, initial_equity)
    results = backtest.simulate_trading(testing=testing)
    statistics.save(filename)
    return results
예제 #5
0
class TestLiquidateRebalancePositionSizer(unittest.TestCase):
    def setUp(self):
        price_handler_mock = PriceHandlerMock()
        ticker_weights = {"AAA": 0.3, "BBB": 0.7}
        self.position_sizer = LiquidateRebalancePositionSizer(ticker_weights)
        self.portfolio = Portfolio(price_handler_mock,
                                   PriceParser.parse(10000.00))

    def test_will_add_positions(self):
        """
        Tests that the position sizer will open up new positions with
        the correct weights.
        """
        order_a = SuggestedOrder("AAA", "BOT", 0)
        order_b = SuggestedOrder("BBB", "BOT", 0)
        sized_a = self.position_sizer.size_order(self.portfolio, order_a)
        sized_b = self.position_sizer.size_order(self.portfolio, order_b)

        self.assertEqual(sized_a.action, "BOT")
        self.assertEqual(sized_b.action, "BOT")
        self.assertEqual(sized_a.quantity, 60)
        self.assertEqual(sized_b.quantity, 70)

    def test_will_liquidate_positions(self):
        """
        Ensure positions will be liquidated completely when asked.
        Include a long & a short.
        """
        self.portfolio._add_position("BOT", "AAA", 100,
                                     PriceParser.parse(60.00), 0.0)
        self.portfolio._add_position("BOT", "BBB", -100,
                                     PriceParser.parse(60.00), 0.0)

        exit_a = SuggestedOrder("AAA", "EXIT", 0)
        exit_b = SuggestedOrder("BBB", "EXIT", 0)
        sized_a = self.position_sizer.size_order(self.portfolio, exit_a)
        sized_b = self.position_sizer.size_order(self.portfolio, exit_b)

        self.assertEqual(sized_a.action, "SLD")
        self.assertEqual(sized_b.action, "BOT")
        self.assertEqual(sized_a.quantity, 100)
        self.assertEqual(sized_a.quantity, 100)
def run_monthly_rebalance(config, testing, filename, benchmark, ticker_weights,
                          title_str, start_date, end_date, equity):
    config = settings.from_file(config, testing)
    tickers = [t for t in ticker_weights.keys()]

    # Set up variables needed for backtest
    events_queue = queue.Queue()
    csv_dir = config.CSV_DATA_DIR
    initial_equity = PriceParser.parse(equity)

    # Use Yahoo Daily Price Handler
    price_handler = YahooDailyCsvBarPriceHandler(csv_dir,
                                                 events_queue,
                                                 tickers,
                                                 start_date=start_date,
                                                 end_date=end_date)

    # Use the monthly liquidate and rebalance strategy
    strategy = MonthlyLiquidateRebalanceStrategy(tickers, events_queue)
    #strategy = Strategies(strategy, DisplayStrategy())

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Use an example Risk Manager
    risk_manager = ExampleRiskManager()

    # Use the default Portfolio Handler
    portfolio_handler = PortfolioHandler(initial_equity, events_queue,
                                         price_handler, position_sizer,
                                         risk_manager)

    # Use the ExampleCompliance component
    compliance = ExampleCompliance(config)

    # Use a simulated IB Execution Handler
    execution_handler = IBSimulatedExecutionHandler(events_queue,
                                                    price_handler, compliance)

    # Use the default Statistics
    title = [title_str]
    statistics = TearsheetStatistics(config, portfolio_handler, title,
                                     benchmark)

    # Set up the backtest
    backtest = Backtest(price_handler, strategy, portfolio_handler,
                        execution_handler, position_sizer, risk_manager,
                        statistics, initial_equity)
    results = backtest.simulate_trading(testing=testing)
    statistics.save(filename)
    return results
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Monthly Liquidate/Rebalance on 60%/40% SPY/AGG Portfolio']
    initial_equity = 500000.0
    start_date = datetime.datetime(2006, 11, 1)
    end_date = datetime.datetime(2016, 10, 12)

    # Use the Monthly Liquidate And Rebalance strategy
    events_queue = queue.Queue()
    strategy = MonthlyLiquidateRebalanceStrategy(tickers, events_queue)

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    ticker_weights = {
        "ewg.us": 0.4,
        "ewq.us": 0.6,
    }
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        position_sizer=position_sizer,
        price_handler=DailyCsvBarPriceHandler('~/Desktop/stock-data/ETFs',
                                              ext_data='txt',
                                              init_tickers=tickers,
                                              events_queue=events_queue,
                                              start_date=start_date,
                                              end_date=end_date),
        title=title,
        benchmark=tickers[0],
    )
    results = backtest.start_trading(testing=testing)
    return results
예제 #8
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = [
        'Monthly Liquidate/Rebalance on 40%/30% 30% sz50/zz500/cyb Portfolio'
    ]
    initial_equity = 300000.0
    start_date = datetime.datetime(2010, 11, 1)
    end_date = datetime.datetime(2018, 8, 18)

    # Use the Monthly Liquidate And Rebalance strategy
    events_queue = queue.Queue()
    strategy = MonthlyLiquidateRebalanceStrategy(tickers, events_queue)

    # Use the liquidate and rebalance position sizer
    # with prespecified ticker weights
    ticker_weights = {
        "510050": 0.4,
        "510500": 0.3,
        "159915": 0.3,
    }
    position_sizer = LiquidateRebalancePositionSizer(ticker_weights)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        price_handler='tushare',
        position_sizer=position_sizer,
        title=title,
        benchmark=tickers[0],
    )
    results = backtest.start_trading(testing=testing)
    return results
예제 #9
0
 def setUp(self):
     price_handler_mock = PriceHandlerMock()
     ticker_weights = {"AAA": 0.3, "BBB": 0.7}
     self.position_sizer = LiquidateRebalancePositionSizer(ticker_weights)
     self.portfolio = Portfolio(price_handler_mock,
                                PriceParser.parse(10000.00))