How to use qstrader - 10 common examples

To help you get started, we’ve selected a few qstrader examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mhallsmoore / qstrader / examples / mac_backtest_tearsheet.py View on Github external
def main(config, testing, tickers, filename):
    tickers = tickers.split(",")
    config = settings.from_file(config, testing)
    run(config, testing, tickers, filename)
github mhallsmoore / qstrader / examples / test_examples.py View on Github external
def test_buy_and_hold_backtest(self):
        """
        Test buy_and_hold
        Begins at 2000-01-01 00:00:00
        End at 2014-01-01 00:00:00
        """
        tickers = ["SPY"]
        filename = os.path.join(
            settings.TEST.OUTPUT_DIR,
            "buy_and_hold_backtest.pkl"
        )
        results = examples.buy_and_hold_backtest.run(
            self.config, self.testing, tickers, filename
        )
        for (key, expected) in [
            ('sharpe', 0.25234757),
            ('max_drawdown_pct', 0.79589309),
        ]:
            value = float(results[key])
            self.assertAlmostEqual(expected, value)
github mhallsmoore / qstrader / examples / pandas_examples / test_pandas_examples.py View on Github external
def test_pandas_tick_strategy_backtest(self):
        tickers = ["GOOG"]
        filename = os.path.join(settings.TEST.OUTPUT_DIR, "pandas_tick_strategy_backtest.pkl")
        results = examples.pandas_examples.pandas_tick_strategy_backtest.run(self.config, self.testing, tickers, filename, self.n, self.n_window)
        self.assertAlmostEqual(float(results['sharpe']), -7.1351)
github mhallsmoore / qstrader / qstrader / simulation / backtest_trading_simulation.py View on Github external
def _create_broker_commission(self):
        """
        TODO: Fill in doc string!
        """
        if self.settings.BROKER['COMMISSION']['MODEL'] == "Zero Commission":
            broker_commission = ZeroBrokerCommission()
        else:
            print(
                "No supported Broker Commission "
                "model specified. Exiting."
            )
            sys.exit()
        return broker_commission
github mhallsmoore / qstrader / tests / test_position.py View on Github external
def setUp(self):
        self.position = Position(
            "SLD", "PG", 100,
            PriceParser.parse(77.69), PriceParser.parse(1.00),
            PriceParser.parse(77.68), PriceParser.parse(77.70)
        )
github mhallsmoore / qstrader / examples / mac_backtest_tearsheet.py View on Github external
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
github mhallsmoore / qstrader / tests / test_portfolio.py View on Github external
"SLD", "AMZN", 200,
            PriceParser.parse(565.59), PriceParser.parse(1.00)
        )
        # Multiple transactions bundled into one (in IB)
        # Sell 300 GOOG from the portfolio
        self.portfolio.transact_position(
            "SLD", "GOOG", 100,
            PriceParser.parse(704.92), PriceParser.parse(1.00)
        )
        self.portfolio.transact_position(
            "SLD", "GOOG", 100,
            PriceParser.parse(704.90), PriceParser.parse(0.00)
        )
        self.portfolio.transact_position(
            "SLD", "GOOG", 100,
            PriceParser.parse(704.92), PriceParser.parse(0.50)
        )
        # Finally, sell the remaining GOOG 100 shares
        self.portfolio.transact_position(
            "SLD", "GOOG", 100,
            PriceParser.parse(704.78), PriceParser.parse(1.00)
        )

        # The figures below are derived from Interactive Brokers
        # demo account using the above trades with prices provided
        # by their demo feed.
        self.assertEqual(len(self.portfolio.positions), 0)
        self.assertEqual(len(self.portfolio.closed_positions), 2)
        self.assertEqual(PriceParser.display(self.portfolio.cur_cash), 499100.50)
        self.assertEqual(PriceParser.display(self.portfolio.equity), 499100.50)
        self.assertEqual(PriceParser.display(self.portfolio.unrealised_pnl), 0.00)
        self.assertEqual(PriceParser.display(self.portfolio.realised_pnl), -899.50)
github mhallsmoore / qstrader / tests / test_portfolio.py View on Github external
self.portfolio.transact_position(
            "SLD", "GOOG", 100,
            PriceParser.parse(704.92), PriceParser.parse(1.00)
        )
        self.portfolio.transact_position(
            "SLD", "GOOG", 100,
            PriceParser.parse(704.90), PriceParser.parse(0.00)
        )
        self.portfolio.transact_position(
            "SLD", "GOOG", 100,
            PriceParser.parse(704.92), PriceParser.parse(0.50)
        )
        # Finally, sell the remaining GOOG 100 shares
        self.portfolio.transact_position(
            "SLD", "GOOG", 100,
            PriceParser.parse(704.78), PriceParser.parse(1.00)
        )

        # The figures below are derived from Interactive Brokers
        # demo account using the above trades with prices provided
        # by their demo feed.
        self.assertEqual(len(self.portfolio.positions), 0)
        self.assertEqual(len(self.portfolio.closed_positions), 2)
        self.assertEqual(PriceParser.display(self.portfolio.cur_cash), 499100.50)
        self.assertEqual(PriceParser.display(self.portfolio.equity), 499100.50)
        self.assertEqual(PriceParser.display(self.portfolio.unrealised_pnl), 0.00)
        self.assertEqual(PriceParser.display(self.portfolio.realised_pnl), -899.50)
github mhallsmoore / qstrader / tests / test_statistics.py View on Github external
def test_calculating_statistics(self):
        """
        Purchase/sell multiple lots of AMZN, GOOG
        at various prices/commissions to ensure
        the arithmetic in calculating equity, drawdowns
        and sharpe ratio is correct.
        """
        # Create Statistics object
        price_handler = PriceHandlerMock()
        self.portfolio = Portfolio(price_handler, PriceParser.parse(500000.00))

        portfolio_handler = PortfolioHandlerMock(self.portfolio)
        statistics = SimpleStatistics(self.config, portfolio_handler)

        # Check initialization was correct
        self.assertEqual(PriceParser.display(statistics.equity[0]), 500000.00)
        self.assertEqual(PriceParser.display(statistics.drawdowns[0]), 00)
        self.assertEqual(statistics.equity_returns[0], 0.0)

        # Perform transaction and test statistics at this tick
        self.portfolio.transact_position(
            "BOT", "AMZN", 100,
            PriceParser.parse(566.56), PriceParser.parse(1.00)
        )
        t = "2000-01-01 00:00:00"
        statistics.update(t, portfolio_handler)
github mhallsmoore / qstrader / tests / algo / test_equal_weight_pcm.py View on Github external
# Create assets and forecasts
        assets = [
            Equity("%s Inc." % ticker, ticker, "NYSE")
            for ticker in ["AAA", "BBB", "CCC", "DDD"]
        ]
        forecasts = [
            Forecast(assets[i], val, start_dt, forecast_dt)
            for i, val in enumerate([1.7, 2.8, 6.32, 36.8])
        ]

        # Create Exchange and SimulatedBroker
        prices = [24.68, 52.55, 63.85, 128.223]
        exchange = ExchangeMock(assets, prices)
        tdcm = TDDirectBrokerCommission()
        broker = SimulatedBroker(
            start_dt, exchange,
            account_id=1234,
            initial_funds=cash,
            broker_commission=tdcm
        )
        bpid = "5678"
        broker.create_portfolio(portfolio_id="5678")
        broker.subscribe_funds_to_portfolio("5678", cash)

        # Create portfolio construction model
        ewpcm = EqualWeightPCM(
            start_dt, broker, bpid,
            transaction_cost_model=tdcm
        )

        # Calculate order equivalence