Back to Community
How to create a simple rebalancer

I'm new to this, and I just want to make a simple rebalancer that rebalances to 60% whenever it goes ~10% out of range. I tried the code below but the backtest seems to take a long time, and I'm not convinced about the results. Does anyone see what I'm doing wrong?

I would really like to keep this simple if possible.


def initialize(context):  
    set_commission(commission.PerShare(cost=0.03, min_trade_cost=None))  
    context.security=symbol('AAPL')  
def handle_data(context, data):

    if context.account.leverage > 0.7 or context.account.leverage < 0.5:  
        order_target_percent(context.security,0.6)

3 responses

I assume you're using minutely data? Not much you can do about the backtest speed. But your code is fine, except you need to add get_open_orders to check that you've not already got an order filling, otherwise in minute mode you can get some crazy stuff going on. See if the attached makes sense.

Clone Algorithm
3
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
# Backtest ID: 55df8207e52c840d87a68b99
There was a runtime error.

Thanks, how can I set the timeframe to daily? Also do I have to run a full backtest to attach here?

Its the dropdown box just left of "Run Full Backtest", select daily. And yes you have to do a full backtest to attach here.

Note that with daily data, your orders are placed 'overnight' and you get them filled at the next day's close price. So the difference in returns can be quite big, depending on the algo.