Exemplo n.º 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
Exemplo n.º 2
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Moving Average Crossover Example on AAPL: 100x300']
    initial_equity = 10000.0
    start_date = datetime.datetime(2000, 1, 1)
    end_date = datetime.datetime(2014, 1, 1)

    # Use the MAC Strategy
    events_queue = queue.Queue()
    strategy = MovingAverageCrossStrategy(tickers[0],
                                          events_queue,
                                          short_window=100,
                                          long_window=300)

    # Set up the backtest
    backtest = TradingSession(
        config,
        strategy,
        tickers,
        initial_equity,
        start_date,
        end_date,
        events_queue,
        title=title,
        benchmark=tickers[1],
    )
    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)
Exemplo n.º 4
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Aluminium Smelting Strategy - ARNC/UNG']
    initial_equity = 500000.0
    start_date = datetime.datetime(2014, 11, 11)
    end_date = datetime.datetime(2016, 9, 1)

    # Use the Cointegration Bollinger Bands trading strategy
    events_queue = queue.Queue()
    weights = np.array([1.0, -1.213])
    lookback = 15
    entry_z = 1.5
    exit_z = 0.5
    base_quantity = 10000
    strategy = CointegrationBollingerBandsStrategy(tickers, events_queue,
                                                   lookback, weights, entry_z,
                                                   exit_z, base_quantity)

    # Set the position size to use a
    # fixed base quantity of shares
    position_sizer = FixedPositionSizer(default_quantity=base_quantity)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title,
                              position_sizer=position_sizer)
    results = backtest.start_trading(testing=testing)
    return results
Exemplo n.º 5
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
Exemplo n.º 6
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Buy and Hold Example on %s' % tickers[0]]
    initial_equity = 10000.0
    start_date = datetime.datetime(2005, 1, 1)
    end_date = datetime.datetime(2018, 8, 17)

    # Use the Buy and Hold Strategy
    events_queue = queue.Queue()
    strategy = BuyAndHoldStrategy(tickers[0], events_queue)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              price_handler='tushare',
                              title=title,
                              benchmark=tickers[1])

    results = backtest.start_trading(testing=testing, filename=filename)
    return results
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Moving Average Crossover Example on %s: 100x300' % filename]
    initial_equity = 10000.0
    start_date = datetime.datetime(2013, 1, 1)
    end_date = datetime.datetime(2018, 1, 1)
    cycle = 'D'

    # Use the MAC Strategy
    events_queue = queue.Queue()
    strategy = MovingAverageCrossStrategy(tickers[0],
                                          events_queue,
                                          short_window=1,
                                          long_window=20)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              price_handler='tushare',
                              title=title,
                              benchmark=tickers[1],
                              cycle=cycle)

    results = backtest.start_trading(testing=testing, filename=filename)

    return results
Exemplo n.º 8
0
def run(config, testing, tickers, filename):
    # Backtest information

    title = ["Kalman Filter Pairs Trade on %s/%s" % (tickers[0], tickers[1])]
    initial_equity = 100000.0
    start_date = datetime.datetime(2017, 1, 1)
    end_date = datetime.datetime(2018, 8, 19)

    # Use the KalmanPairsTrading Strategy
    events_queue = queue.Queue()
    strategy = KalmanPairsTradingStrategy(tickers, events_queue)

    # Use the Naive Position Sizer where
    # suggested quantities are followed
    position_sizer = NaivePositionSizer()

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title,
                              position_sizer=position_sizer)
    results = backtest.start_trading(testing=testing)
    return results
Exemplo n.º 9
0
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(100000.00)

    # Use Yahoo Daily Price Handler
    start_date = datetime.datetime(2009, 8, 3)
    end_date = datetime.datetime(2019, 8, 1)
    price_handler = YahooDailyCsvBarPriceHandler(csv_dir,
                                                 events_queue,
                                                 tickers,
                                                 start_date=start_date,
                                                 end_date=end_date)
    # Use the KalmanPairsTrading Strategy
    strategy = KalmanPairsTradingStrategy(tickers, events_queue)
    strategy = Strategies(strategy)

    # Use the Naive Position Sizer (suggested quantities are followed)
    position_sizer = NaivePositionSizer()

    # 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 Tearsheet Statistics
    title = ["Kalman Filter Pairs Trade on TLT/IEI"]
    statistics = TearsheetStatistics(config, portfolio_handler, title)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              price_handler=price_handler,
                              portfolio_handler=portfolio_handler,
                              execution_handler=execution_handler,
                              position_sizer=position_sizer,
                              risk_manager=risk_manager,
                              statistics=statistics)

    results = backtest.start_trading(testing=testing)
    statistics.save(filename)
    return results
Exemplo n.º 10
0
def run(config, testing, tickers, filename):
    # Set up variables needed for backtest
    title = ["Intraday AREX Machine Learning Prediction Strategy"]
    events_queue = queue.Queue()
    csv_dir = "/path/to/your/csv/data/"
    initial_equity = 500000.0

    # Use DTN IQFeed Intraday Bar Price Handler
    start_date = datetime.datetime(2013, 1, 1)
    end_date = datetime.datetime(2014, 3, 11)
    price_handler = IQFeedIntradayCsvBarPriceHandler(csv_dir,
                                                     events_queue,
                                                     tickers,
                                                     start_date=start_date)

    # Use the ML Intraday Prediction Strategy
    model_pickle_file = '/path/to/your/ml_model_lda.pkl'
    strategy = IntradayMachineLearningPredictionStrategy(tickers,
                                                         events_queue,
                                                         model_pickle_file,
                                                         lags=5)

    # Use the Naive Position Sizer where
    # suggested quantities are followed
    position_sizer = NaivePositionSizer()

    # Use an example Risk Manager
    risk_manager = ExampleRiskManager()

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

    # Use the Tearsheet Statistics
    statistics = TearsheetStatistics(
        config,
        portfolio_handler,
        title=title,
        periods=int(252 * 6.5 * 60)  # Minutely periods
    )

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title,
                              portfolio_handler=portfolio_handler,
                              position_sizer=position_sizer,
                              price_handler=price_handler,
                              statistics=statistics)
    results = backtest.start_trading(testing=testing)
    return results
def run(cache_name, cache_backend, expire_after, data_source, start, end, config, testing, tickers, filename, n, n_window):

    # Set up variables needed for backtest
    events_queue = queue.Queue()
    initial_equity = PriceParser.parse(500000.00)

    session = init_session(cache_name, cache_backend, expire_after)

    period = 86400  # Seconds in a day

    if len(tickers) == 1:
        data = web.DataReader(tickers[0], data_source, start, end, session=session)
    else:
        data = web.DataReader(tickers, data_source, start, end, session=session)

    # Use Generic Bar Handler with Pandas Bar Iterator
    price_event_iterator = PandasBarEventIterator(data, period, tickers[0])
    price_handler = GenericPriceHandler(events_queue, price_event_iterator)

    # Use the Display Strategy
    strategy1 = DisplayStrategy(n=n, n_window=n_window)
    strategy2 = BuyAndHoldStrategy(tickers, events_queue)
    strategy = Strategies(strategy1, strategy2)

    # Use an example Position Sizer
    position_sizer = FixedPositionSizer()

    # 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
    statistics = SimpleStatistics(config, portfolio_handler)

    # 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):

    # 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
Exemplo n.º 13
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Buy and Hold Example on %s' % tickers[0]]
    initial_equity = 10000.0
    start_date = datetime.datetime(2000, 1, 1)
    end_date = datetime.datetime(2014, 1, 1)

    # Use the Buy and Hold Strategy
    events_queue = queue.Queue()
    strategy = BuyAndHoldStrategy(tickers[0], events_queue)
Exemplo n.º 14
0
def etf_run():  #config, testing, tickers, filename
    events_queue = queue.Queue()
    # tickers = ['EWJ']
    with open(r'..\config.json') as config_file:
        configs = json.load(config_file)
        etf_list = pd.read_csv(configs['ETF'], index_col=0).index.tolist()
        stock_list = pd.read_csv(configs['STOCK'], index_col=0).index.tolist()
    tickers = etf_list + stock_list
    tickers = ['EWZ']

    csv_dir = r'C:\temp\1minute\price'
    # start_date = 20100217
    start_date = 20160101
    end_date = 20161122
    # frog_multiplier = 0.5
    # profit_multiplier = 0.5
    # frog_multipliers = [0.5,0.6,0.7,0.8,0.9,1]
    # profit_multipliers = [0.5,0.6,0.7,0.8,0.9]
    frog_multipliers = [0.7]
    profit_multipliers = [1.0]
    is_trailing_stop = 1
    trailing_stop_multipliers = [0.5]
    for frog_multiplier in frog_multipliers:
        for profit_multiplier in profit_multipliers:
            for trailing_stop_multiplier in trailing_stop_multipliers:
                for t in tickers:
                    if is_trailing_stop:
                        trail_stop_text = '{0:.0f}'.format(
                            trailing_stop_multiplier * 100)
                    else:
                        trail_stop_text = 'None'
                    target_file = str.format(
                        r'C:\temp\FROG_TRADES_{2}_{0:d}_{1:d}_HF{3:.0f}_Profit{4:.0f}_TrailStop{5}.csv',
                        start_date, end_date, t, frog_multiplier * 100,
                        profit_multiplier * 100, trail_stop_text)
                    # if os.path.exists(target_file):
                    #     continue
                    price_handler = IqfeedCsvBarPriceHandler(
                        csv_dir, events_queue, t, 60, start_date, end_date)

                    frog_factor_folder = r'C:\temp\daily\factor'

                    frog_strategy = HybridFrogStrategy(
                        ticker=t,
                        event_queue=events_queue,
                        frog_score_folder=frog_factor_folder,
                        frog_multiplier=frog_multiplier,
                        profit_taking_multiplier=profit_multiplier,
                        is_trailing_stop=is_trailing_stop,
                        trailing_stop_multiplier=trailing_stop_multiplier)
                    frog_order = FrogOrder(target_file)

                    backtest = Backtest(price_handler, frog_strategy,
                                        frog_order)
                    backtest.simulate_trading()
Exemplo n.º 15
0
def run(config, testing, tickers, filename):

    # Set up variables needed for backtest
    events_queue = queue.Queue()
    csv_dir = "/path/to/your/csv/data/"
    initial_equity = PriceParser.parse(500000.00)

    # Use DTN IQFeed Intraday Bar Price Handler
    start_date = datetime.datetime(2013, 1, 1)
    price_handler = IQFeedIntradayCsvBarPriceHandler(csv_dir,
                                                     events_queue,
                                                     tickers,
                                                     start_date=start_date)

    # Use the ML Intraday Prediction Strategy
    model_pickle_file = '/path/to/your/ml_model_lda.pkl'
    strategy = IntradayMachineLearningPredictionStrategy(tickers,
                                                         events_queue,
                                                         model_pickle_file,
                                                         lags=5)
    strategy = Strategies(strategy, DisplayStrategy())

    # Use the Naive Position Sizer (suggested quantities are followed)
    position_sizer = NaivePositionSizer()

    # 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 Tearsheet Statistics
    statistics = TearsheetStatistics(
        config,
        portfolio_handler,
        title=["Intraday AREX Machine Learning Prediction Strategy"],
        periods=int(252 * 6.5 * 60)  # Minutely periods
    )

    # 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
Exemplo n.º 16
0
 def setUp(self):
     """
     Set up the PriceHandler object with a small
     set of initial tickers.
     """
     self.config = settings.TEST
     fixtures_path = self.config.CSV_DATA_DIR
     events_queue = queue.Queue()
     init_tickers = ["GOOG", "AMZN", "MSFT"]
     self.price_handler = HistoricCSVTickPriceHandler(
         fixtures_path, events_queue, init_tickers)
Exemplo n.º 17
0
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)

    # Use Yahoo Daily Price Handler
    start_date = datetime.datetime(2013, 7, 1)
    end_date = datetime.datetime(2019, 6, 1)
    price_handler = YahooDailyCsvBarPriceHandler(csv_dir, events_queue, tickers, start_date=start_date, end_date=end_date)

    # Use the Cointegration Bollinger Bands trading strategy
    weights = np.array([1.0, -1.213])
    lookback = 15
    entry_z = 1.5
    exit_z = 0.5
    base_quantity = 10000
    strategy = CointegrationBollingerBandsStrategy(tickers[1:], events_queue, lookback, weights, entry_z, exit_z, base_quantity)
    strategy = Strategies(strategy)

    # Use the Naive Position Sizer
    # where suggested quantities are followed
    position_sizer = NaivePositionSizer()

    # 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 Tearsheet Statistics
    title = ["Aluminum Smelting Strategy - ARNC/UNG"]
    statistics = TearsheetStatistics(config, portfolio_handler, title, benchmark=tickers[0])
    
    # Set up the backtest
    backtest = TradingSession(config, strategy, 
        tickers[1:], initial_equity, start_date, end_date,
        events_queue, price_handler=price_handler,
        portfolio_handler=portfolio_handler, 
        execution_handler=execution_handler, 
        position_sizer=position_sizer, 
        risk_manager=risk_manager, 
        statistics=statistics, benchmark=tickers[0])

    results = backtest.start_trading(testing=testing)
    statistics.save(filename)
    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)

    # 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, start_date, end_date):

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

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

    # Use the Buy and Hold Strategy
    strategy = CustomStrategy(tickers, events_queue)
    strategy = Strategies(strategy, DisplayStrategy())

    # Use an example Position Sizer
    position_sizer = CustomPositionSizer()

    # 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
    statistics = TearsheetStatistics(
        config, portfolio_handler, title=""
    )

    # 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
Exemplo n.º 20
0
def run(config, testing, tickers, filename, n, n_window):

    # Set up variables needed for backtest
    events_queue = queue.Queue()

    ig_service = IGService(config.IG.USERNAME, config.IG.PASSWORD,
                           config.IG.API_KEY, config.IG.ACCOUNT.TYPE)

    ig_stream_service = IGStreamService(ig_service)
    ig_session = ig_stream_service.create_session()
    accountId = ig_session[u'accounts'][0][u'accountId']

    ig_stream_service.connect(accountId)

    initial_equity = PriceParser.parse(500000.00)

    # Use IG Tick Price Handler
    price_handler = IGTickPriceHandler(events_queue, ig_stream_service,
                                       tickers)

    # Use the Display Strategy
    strategy = DisplayStrategy(n=n, n_window=n_window)

    # Use an example Position Sizer
    position_sizer = FixedPositionSizer()

    # 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
    statistics = SimpleStatistics(config, portfolio_handler)

    # 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
Exemplo n.º 21
0
def run(config, testing, tickers, filename):

    # Benchmark ticker
    benchmark = 'SP500TR'

    # Set up variables needed for backtest
    title = [
        'Moving Average Crossover Example', __file__,
        ','.join(tickers) + ': 100x400'
    ]
    events_queue = queue.Queue()
    csv_dir = config.CSV_DATA_DIR
    initial_equity = PriceParser.parse(500000.00)

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

    # Use the MAC Strategy
    strategy = MovingAverageCrossStrategy(tickers, events_queue)

    # Use an example Position Sizer,
    position_sizer = FixedPositionSizer()

    # 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
    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
Exemplo n.º 22
0
 def setUp(self):
     """
     Set up the PortfolioHandler object supplying it with
     $500,000.00 USD in initial cash.
     """
     initial_cash = Decimal("500000.00")
     events_queue = queue.Queue()
     price_handler = PriceHandlerMock()
     position_sizer = PositionSizerMock()
     risk_manager = RiskManagerMock()
     # Create the PortfolioHandler object from the rest
     self.portfolio_handler = PortfolioHandler(initial_cash, events_queue,
                                               price_handler,
                                               position_sizer, risk_manager)
Exemplo n.º 23
0
def run(config, testing, tickers, filename):
    # Set up variables needed for backtest
    events_queue = queue.Queue()
    csv_dir = config.CSV_DATA_DIR
    initial_invst = 1000000.00
    initial_equity = PriceParser.parse(initial_invst)

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

    # Use the KalmanPairsTrading Strategy
    strategy = KalmanPairsTradingStrategy(tickers, events_queue, initial_invst)
    strategy = Strategies(strategy, DisplayStrategy())

    # Use the Naive Position Sizer (suggested quantities are followed)
    position_sizer = NaivePositionSizer()

    # 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
    statistics = TearsheetStatistics(config, portfolio_handler, title="")

    # 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)
    hist = results['cum_returns']
    print('==:++==')
    print(hist.to_csv('6pair.csv', header=['date,total asset']))
    statistics.save('output')
    return results
Exemplo n.º 24
0
def run(config, testing, tickers, filename):
    # Backtest information
    events_queue = queue.Queue()
    title = [
        'Sentiment Sentdex Strategy - Tech Stocks'
        #'Sentiment Sentdex Strategy - Defence Stocks'
        #'Sentiment Sentdex Strategy - Energy Stocks'
    ]
    initial_equity = 500000.0
    start_date = datetime.datetime(2012, 10, 15)
    end_date = datetime.datetime(2016, 2, 2)

    # Use the Sentdex Sentiment trading strategy
    sentiment_handler = SentdexSentimentHandler(config.CSV_DATA_DIR,
                                                "sentdex_sample.csv",
                                                events_queue,
                                                tickers=tickers,
                                                start_date=start_date,
                                                end_date=end_date)

    # Use the Sentdex Sentiment trading strategy
    base_quantity = 500
    sent_buy = 6
    sent_sell = -1
    strategy = SentdexSentimentStrategy(tickers, events_queue, sent_buy,
                                        sent_sell, base_quantity)

    # Use the Fixed Position Sizer where
    # suggested quantities are followed
    position_sizer = FixedPositionSizer(default_quantity=base_quantity)

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title,
                              position_sizer=position_sizer,
                              sentiment_handler=sentiment_handler,
                              benchmark="SPY")
    results = backtest.start_trading(testing=testing)
    return results
Exemplo n.º 25
0
def run(config, testing, tickers, filename):
    # Backtest information
    title = ['Buy and Hold Example on %s' % tickers[0]]
    initial_equity = 10000.0
    start_date = datetime.datetime(2000, 1, 1)
    end_date = datetime.datetime(2014, 1, 1)

    # Use the Buy and Hold Strategy
    events_queue = queue.Queue()
    strategy = BuyAndHoldStrategy(tickers[0], events_queue)

    # Set up the backtest
    backtest = Backtest(
        config, strategy, tickers,
        initial_equity, start_date, end_date,
        events_queue, title=title
    )
    results = backtest.simulate_trading(testing=testing)
    return results
def run(config, testing, tickers, filename, n, n_window):

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

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

    # Use the Display Strategy
    strategy = DisplayStrategy(n=n, n_window=n_window)

    # Use an example Position Sizer
    position_sizer = FixedPositionSizer()

    # 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
    statistics = SimpleStatistics(config, portfolio_handler)

    # 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
Exemplo n.º 28
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
Exemplo n.º 29
0
def run(config, testing, tickers, filename):
    # Set up variables needed for backtest
    pickle_path = "/path/to/your/model/hmm_model_spy.pkl"
    events_queue = queue.Queue()
    csv_dir = config.CSV_DATA_DIR
    initial_equity = PriceParser.parse(500000.00)

    # Use Yahoo Daily Price Handler
    start_date = datetime.datetime(2005, 1, 1)
    end_date = datetime.datetime(2014, 12, 31)
    price_handler = YahooDailyCsvBarPriceHandler(csv_dir,
                                                 events_queue,
                                                 tickers,
                                                 start_date=start_date,
                                                 end_date=end_date,
                                                 calc_adj_returns=True)

    # Use the Moving Average Crossover trading strategy
    base_quantity = 10000
    strategy = MovingAverageCrossStrategy(tickers,
                                          events_queue,
                                          base_quantity,
                                          short_window=10,
                                          long_window=30)
    strategy = Strategies(strategy, DisplayStrategy())

    # Use the Naive Position Sizer
    # where suggested quantities are followed
    position_sizer = NaivePositionSizer()

    # Use regime detection HMM risk manager
    hmm_model = pickle.load(open(pickle_path, "rb"))
    risk_manager = RegimeHMMRiskManager(hmm_model)
    # 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 Tearsheet Statistics
    title = ["Trend Following Regime Detection with HMM"]
    statistics = TearsheetStatistics(config,
                                     portfolio_handler,
                                     title,
                                     benchmark="SPY")

    # 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
Exemplo n.º 30
0
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)

    # Use Yahoo Daily Price Handler
    start_date = datetime.datetime(2012, 10, 15)
    end_date = datetime.datetime(2016, 2, 2)
    price_handler = YahooDailyCsvBarPriceHandler(
        csv_dir, events_queue, tickers,
        start_date=start_date, end_date=end_date
    )

    # Use the Sentdex Sentiment trading strategy
    sentiment_handler = SentdexSentimentHandler(
        config.CSV_DATA_DIR, "sentdex_sample.csv",
        events_queue, tickers=tickers,
        start_date=start_date, end_date=end_date
    )

    base_quantity = 2000
    sent_buy = 6
    sent_sell = -1
    strategy = SentdexSentimentStrategy(
        tickers, events_queue,
        sent_buy, sent_sell, base_quantity
    )
    strategy = Strategies(strategy, DisplayStrategy())

    # Use the Naive Position Sizer
    # where suggested quantities are followed
    position_sizer = NaivePositionSizer()

    # 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 Tearsheet Statistics
    title = ["Sentiment Sentdex Strategy"]
    statistics = TearsheetStatistics(
        config, portfolio_handler, title,
        benchmark="SPY"
    )

    # Set up the backtest
    backtest = Backtest(
        price_handler, strategy,
        portfolio_handler, execution_handler,
        position_sizer, risk_manager,
        statistics, initial_equity,
        sentiment_handler=sentiment_handler
    )
    results = backtest.simulate_trading(testing=testing)
    statistics.save(filename)
    return results