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): # 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
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 = "/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
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
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
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(100000.00) # Use Yahoo Daily Price Handler price_handler = YahooDailyCsvBarPriceHandler(csv_dir, events_queue, tickers) # Use the KalmanPairsTrading Strategy strategy = KalmanPairsTradingStrategy(tickers, events_queue) 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) statistics.save(filename) return results
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
# Construct benchmark assets (buy & hold SPY) benchmark_symbols = ['SPY'] benchmark_assets = ['EQ:SPY'] benchmark_universe = StaticUniverse(benchmark_assets) benchmark_data_source = CSVDailyBarDataSource( csv_dir, Equity, csv_symbols=benchmark_symbols) benchmark_data_handler = BacktestDataHandler( benchmark_universe, data_sources=[benchmark_data_source]) # Construct a benchmark Alpha Model that provides # 100% static allocation to the SPY ETF, with no rebalance benchmark_alpha_model = FixedSignalsAlphaModel({'EQ:SPY': 1.0}) benchmark_backtest = BacktestTradingSession( burn_in_dt, end_dt, benchmark_universe, benchmark_alpha_model, rebalance='buy_and_hold', long_only=True, cash_buffer_percentage=0.01, data_handler=benchmark_data_handler) benchmark_backtest.run() # Performance Output tearsheet = TearsheetStatistics( strategy_equity=strategy_backtest.get_equity_curve(), benchmark_equity=benchmark_backtest.get_equity_curve(), title='US Sector Momentum - Top 3 Sectors') tearsheet.plot_results()
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
strategy_assets = ['EQ:GLD'] strategy_universe = StaticUniverse(strategy_assets) # To avoid loading all CSV files in the directory, set the # data source to load only those provided symbols csv_dir = os.environ.get('QSTRADER_CSV_DATA_DIR') data_source = CSVDailyBarDataSource(csv_dir, Equity, csv_symbols=strategy_symbols) data_handler = BacktestDataHandler(strategy_universe, data_sources=[data_source]) # Construct an Alpha Model that simply provides a fixed # signal for the single GLD ETF at 100% allocation # with a backtest that does not rebalance strategy_alpha_model = FixedSignalsAlphaModel({'EQ:GLD': 1.0}) strategy_backtest = BacktestTradingSession(start_dt, end_dt, strategy_universe, strategy_alpha_model, rebalance='buy_and_hold', cash_buffer_percentage=0.01, data_handler=data_handler) strategy_backtest.run() # Performance Output tearsheet = TearsheetStatistics( strategy_equity=strategy_backtest.get_equity_curve(), title='Buy & Hold GLD ETF') tearsheet.plot_results()
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
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
initial_cash=5e7, initial_position=0.4, cac_stat=True, daily_start_time='09:30:00', deal_volume_time=None, # None 表示不平仓 keep_order_time=10, bid_price_type='spread', ask_price_type='spread', bid_volume_type='multiple', ask_volume_type='multiple', spread_level=0.01, min_bid_unit=0.001, min_ask_unit=0.001, volume_bid=[50000, 60000, 1500000], volume_ask=[50000, 60000, 80000]) test.run() stat = test.broker.get_market_making_statistic() # Performance Output tearsheet = TearsheetStatistics( strategy_equity=test.get_equity_curve(), # benchmark_equity = benchmark_equity_df, title='', periods=test.get_period() # market_making_stat = stat['result'] ) tearsheet.plot_results() print('做市义务:') print(stat['result'])
def run(config, testing, tickers, csv_filepath, pklfile, start_date, end_date, lags, title, folder_name, model, return_win, percent_factor, salida): # Set up variables needed for backtest # title = [ # "Intraday AREX Machine Learning Prediction Strategy" # ] events_queue = queue.Queue() csv_dir = csv_filepath initial_equity = 30000.0 # Use DTN IQFeed Intraday Bar Price Handler # start_date = datetime.datetime(2016, 1, 1) # end_date = datetime.datetime(2014, 3, 11) # start_date = datetime.datetime(2013, 1, 1) # end_date = datetime.datetime(2014, 3, 11) price_handler = IQFeedIntradayCsvBarPriceHandler(csv_dir, events_queue, tickers, start_date, end_date) # Use the ML Intraday Prediction Strategy model_pickle_file = pklfile strategy = IntradayMachineLearningPredictionStrategy( tickers, events_queue, model_pickle_file, lags, model, return_win, percent_factor, salida) # 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 compliance = LiveCompliance(config, tickers) execution_handler = IBSimulatedExecutionHandler( events_queue=events_queue, price_handler=price_handler, compliance=compliance) backtest = TradingSession(config, strategy, tickers, initial_equity, start_date, end_date, events_queue, title=title, portfolio_handler=portfolio_handler, compliance=compliance, position_sizer=position_sizer, execution_handler=execution_handler, price_handler=price_handler, statistics=statistics) results = backtest.start_trading(testing=testing, folder_name=folder_name) 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 cli(start_date, end_date, allocations, strat_title, strat_id, tearsheet): csv_dir = os.environ.get('QSTRADER_CSV_DATA_DIR', '.') start_dt = pd.Timestamp('%s 00:00:00' % start_date, tz=pytz.UTC) if end_date is None: # Use yesterday's date yesterday = (datetime.now() - timedelta(1)).strftime('%Y-%m-%d') end_dt = pd.Timestamp('%s 23:59:00' % yesterday, tz=pytz.UTC) else: end_dt = pd.Timestamp('%s 23:59:00' % end_date, tz=pytz.UTC) alloc_dict = obtain_allocations(allocations) # Assets and Data Handling strategy_assets = list(alloc_dict.keys()) strategy_symbols = [ symbol.replace('EQ:', '') for symbol in strategy_assets ] strategy_universe = StaticUniverse(strategy_assets) strategy_data_source = CSVDailyBarDataSource(csv_dir, Equity, csv_symbols=strategy_symbols) strategy_data_handler = BacktestDataHandler( strategy_universe, data_sources=[strategy_data_source]) strategy_assets = alloc_dict.keys() strategy_alpha_model = FixedSignalsAlphaModel(alloc_dict) strategy_backtest = BacktestTradingSession( start_dt, end_dt, strategy_universe, strategy_alpha_model, rebalance='end_of_month', account_name=strat_title, portfolio_id='STATIC001', portfolio_name=strat_title, long_only=True, cash_buffer_percentage=0.01, data_handler=strategy_data_handler) strategy_backtest.run() # Benchmark: 60/40 US Equities/Bonds benchmark_symbols = ['SPY', 'AGG'] benchmark_assets = ['EQ:SPY', 'EQ:AGG'] benchmark_universe = StaticUniverse(benchmark_assets) benchmark_data_source = CSVDailyBarDataSource( csv_dir, Equity, csv_symbols=benchmark_symbols) benchmark_data_handler = BacktestDataHandler( benchmark_universe, data_sources=[benchmark_data_source]) benchmark_signal_weights = {'EQ:SPY': 0.6, 'EQ:AGG': 0.4} benchmark_title = '60/40 US Equities/Bonds' benchmark_alpha_model = FixedSignalsAlphaModel(benchmark_signal_weights) benchmark_backtest = BacktestTradingSession( start_dt, end_dt, benchmark_universe, benchmark_alpha_model, rebalance='end_of_month', account_name='60/40 US Equities/Bonds', portfolio_id='6040EQBD', portfolio_name=benchmark_title, long_only=True, cash_buffer_percentage=0.01, data_handler=benchmark_data_handler) benchmark_backtest.run() output_filename = ('%s_monthly.json' % strat_id).replace('-', '_') stats = JSONStatistics( equity_curve=strategy_backtest.get_equity_curve(), target_allocations=strategy_backtest.get_target_allocations(), strategy_id=strat_id, strategy_name=strat_title, benchmark_curve=benchmark_backtest.get_equity_curve(), benchmark_id='6040-us-equitiesbonds', benchmark_name=benchmark_title, output_filename=output_filename) stats.to_file() if tearsheet: tearsheet = TearsheetStatistics( strategy_equity=strategy_backtest.get_equity_curve(), benchmark_equity=benchmark_backtest.get_equity_curve(), title=strat_title) tearsheet.plot_results()
# Construct benchmark assets (buy & hold SPY) benchmark_symbols = ['SPY'] benchmark_assets = ['EQ:SPY'] benchmark_universe = StaticUniverse(benchmark_assets) benchmark_data_source = CSVDailyBarDataSource( csv_dir, Equity, csv_symbols=benchmark_symbols) benchmark_data_handler = BacktestDataHandler( benchmark_universe, data_sources=[benchmark_data_source]) # Construct a benchmark Alpha Model that provides # 100% static allocation to the SPY ETF, with no rebalance benchmark_alpha_model = FixedSignalsAlphaModel({'EQ:SPY': 1.0}) benchmark_backtest = BacktestTradingSession( start_dt, end_dt, benchmark_universe, benchmark_alpha_model, rebalance='buy_and_hold', long_only=True, cash_buffer_percentage=0.01, data_handler=benchmark_data_handler) benchmark_backtest.run() # Performance Output tearsheet = TearsheetStatistics( strategy_equity=strategy_backtest.get_equity_curve(), benchmark_equity=benchmark_backtest.get_equity_curve(), title='Long/Short Leveraged Treasury Bond ETFs') tearsheet.plot_results()
cash_buffer_percentage=0.01, data_handler=data_handler ) strategy_backtest.run() # Construct benchmark assets (buy & hold SPY) benchmark_assets = ['EQ:SPY'] benchmark_universe = StaticUniverse(benchmark_assets) # Construct a benchmark Alpha Model that provides # 100% static allocation to the SPY ETF, with no rebalance benchmark_alpha_model = FixedSignalsAlphaModel({'EQ:SPY': 1.0}) benchmark_backtest = BacktestTradingSession( start_dt, end_dt, benchmark_universe, benchmark_alpha_model, rebalance='buy_and_hold', cash_buffer_percentage=0.01, data_handler=data_handler ) benchmark_backtest.run() # Performance Output tearsheet = TearsheetStatistics( strategy_equity=strategy_backtest.get_equity_curve(), benchmark_equity=benchmark_backtest.get_equity_curve(), title='60/40 US Equities/Bonds' ) tearsheet.plot_results()
def run(config, testing, tickers, cliente, strat_set): events_queue = queue.Queue() initial_equity = 30000.0 end_session_time = datetime(2018, 2, 23, 16, 1, 00) if end_session_time < datetime.now(): print("########################################") print(" Yoe, Increase \"end_section time\" please") print("########################################") exit() start_date = None end_date = None # # Defining up to 3 contracts in case Mean Reversing Strategies were used in the future # contract_1 = Contract() contract_1.symbol = tickers[0] contract_1.secType = "STK" contract_1.currency = "USD" contract_1.exchange = "SMART" contract_1.primaryExchange = "ISLAND" contract_2 = Contract() if len(tickers) > 1: contract_2.symbol = tickers[1] contract_2.secType = "STK" contract_2.currency = "USD" contract_2.exchange = "SMART" contract_2.primaryExchange = "ISLAND" contract_3 = Contract() if len(tickers) > 2: contract_3.symbol = tickers[2] contract_3.secType = "STK" contract_3.currency = "USD" contract_3.exchange = "SMART" contract_3.primaryExchange = "ISLAND" contract = [contract_1, contract_2, contract_3] # # Defining the Conection to TWS ###################################################### # current_directory = os.getcwd() app = conexion(tickers=tickers, port=7497, cliente=cliente, currentDir=current_directory) # devuelto en: currentTime # # Checking open positions on the market ############################################ # app.reqAccountUpdates(True, "DU931045") tiempo = datetime.now() continua = False while not continua: open_position = app.open_position if open_position[0] != None or datetime.now() > tiempo + timedelta( seconds=3): continua = True time.sleep(0.5) if open_position[0] == tickers[0]: print(" *******************************************************") print("") print(" There is an open possition for %s, please check in the " % tickers[0]) print(" market whether it is convenient to proced automatically") print("") print(" *******************************************************") app.reqAccountUpdates(False, "DU931045") # # Requesting real time data from the Market ########################################## # reqId = [None for i in range(len(tickers))] for i in range(len(tickers)): reqId[i] = app.nuevoId() app.reqMarketDataType(1) app.reqMktData(reqId[i], contract[i], genericTickList='', snapshot=False, regulatorySnapshot=False, mktDataOptions=[]) print("request Id: ", reqId[i]) # # Defining modules ################################################################### # price_handler = IBAPI_yoe(events_queue, init_tickers=tickers, app=app, reqId=reqId) # start_date = datetime.datetime(2015, 1, 1) # end_date = datetime.datetime(2016, 9, 30) # price_handler = IQFeedIntradayCsvBarPriceHandler( # csv_dir, events_queue, tickers, start_date=start_date # ) contract_dict = { contract_1.symbol: contract_1, contract_2.symbol: contract_2, contract_3.symbol: contract_3 } LiveCompl = LiveCompliance(config, tickers) # Use the ML Intraday Prediction Strategy model_pickle_file = current_directory + "/" + tickers[0] + "_Full_time.pkl" strategy = IntradayMachineLearningPredictionStrategy( tickers, events_queue, model_pickle_file, strat_set, open_position) execution_handler = IB_execution_yoe(events_queue, price_handler, compliance=LiveCompl, app=app, contract_dict=contract_dict, currentDir=current_directory, Id=reqId, strategy=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(PriceParser.parse(initial_equity), events_queue, price_handler, position_sizer, risk_manager) title = [tickers[0] + "Machine Learning_Long_lags3"] # 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, session_type="live", end_session_time=end_session_time, price_handler=price_handler, portfolio_handler=portfolio_handler, compliance=None, position_sizer=position_sizer, execution_handler=execution_handler, risk_manager=None, statistics=statistics, sentiment_handler=None, title=None, benchmark=None) results = backtest.start_trading(testing=testing) return results for i in range(len(tickers)): app.cancelMktData(i) app.disconnect() app.f.close()