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)
Beispiel #2
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
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
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
Beispiel #6
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
Beispiel #7
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
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
    price_handler = YahooDailyCsvBarPriceHandler(csv_dir, events_queue,
                                                 tickers)

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

    # 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
Beispiel #10
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
Beispiel #11
0
def run(config, testing, tickers, filename):
    #build_HMM_model()
    build_HMM_model2()
    title = ["Trend Following Regime Detection without HMM"]
    #pickle_path = "hmm_model_spy.pkl"
    pickle_path = "hmm_model_spy2.pkl"
    #pickle_path = "hmm_model_fx.pkl"
    events_queue = queue.Queue()
    csv_dir = config.CSV_DATA_DIR
    initial_equity = 100000.00
    start_date = datetime.datetime(2011, 1, 1)
    end_date = datetime.datetime(2018, 3, 31)
    # Use the Moving Average Crossover trading strategy
    base_quantity = 10000
    strategy = MovingAverageCrossStrategy(tickers,
                                          events_queue,
                                          base_quantity,
                                          short_window=10,
                                          long_window=30)
    # Use Yahoo Daily Price Handler
    price_handler = YahooDailyCsvBarPriceHandler(csv_dir,
                                                 events_queue,
                                                 tickers,
                                                 start_date=start_date,
                                                 end_date=end_date,
                                                 calc_adj_returns=True)
    # Use the Naive Position Sizer
    # where suggested quantities are followed
    position_sizer = NaivePositionSizer()
    # Use an example Risk Manager
    #risk_manager = ExampleRiskManager()
    # Use regime detection HMM risk manager
    hmm_model = pickle.load(open(pickle_path, "rb"))
    risk_manager = RegimeHMMRiskManager(hmm_model)
    # Use the default Portfolio Handler
    portfolio_handler = PortfolioHandler(PriceParser.parse(initial_equity),
                                         events_queue, price_handler,
                                         position_sizer, risk_manager)
    # Use the Tearsheet Statistics class
    statistics = TearsheetStatistics(
        config,
        portfolio_handler,
        #title,benchmark = "EEM"
        title,
        benchmark="VWO")

    # Set up the backtest
    backtest = TradingSession(config,
                              strategy,
                              tickers,
                              initial_equity,
                              start_date,
                              end_date,
                              events_queue,
                              title=title,
                              price_handler=price_handler,
                              position_sizer=position_sizer,
                              risk_manager=risk_manager,
                              statistics=statistics,
                              portfolio_handler=portfolio_handler)
    results = backtest.start_trading(testing=testing)
    return results