13.08.2022 Views

advanced-algorithmic-trading

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

360

"""

Size the order to reflect the dollar-weighting of the

current equity account size based on pre-specified

ticker weights.

"""

ticker = initial_order.ticker

if initial_order.action == "EXIT":

# Obtain current quantity and liquidate

cur_quantity = portfolio.positions[ticker].quantity

if cur_quantity > 0:

initial_order.action = "SLD"

initial_order.quantity = cur_quantity

elif cur_quantity < 0:

initial_order.action = "BOT"

initial_order.quantity = cur_quantity

else:

initial_order.quantity = 0

else:

weight = self.ticker_weights[ticker]

# Determine total portfolio value, work out dollar weight

# and finally determine integer quantity of shares to purchase

price = portfolio.price_handler.tickers[ticker]["adj_close"]

price /= PriceParser.PRICE_MULTIPLIER

equity = portfolio.equity / PriceParser.PRICE_MULTIPLIER

dollar_weight = weight * equity

weighted_quantity = int(floor(dollar_weight / price))

# Update quantity

initial_order.quantity = weighted_quantity

return initial_order

25.4.3 Backtest Interface

In order to streamline the generation of multiple separate portfolios without excessive code

duplication a new file called monthly_rebalance_run.py has been created. This contains the

backtesting "boilerplate" code necessary to carry out a monthly full liquidation and rebalanced

backtest. The full file listing can be found at the end of the chapter.

To generate the separate portfolio backtests for this chapter the function run_monthly_rebalance

is imported from monthly_rebalance_run.py. It is then called with the benchmark ticker

(SPY), the ticker_weights dictionary containing the ETF proportions, the tearsheet title

text, start/end dates and account equity.

This makes it extremely straightforward to modify portfolio composition assuming availability

of the pricing data. As an example the code for the 60/40 US equities/bond mix is given by:

# equities_bonds_60_40_etf_portfolio_backtest.py

import datetime

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!