Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Rebalancing a portfolio every n weeks?

Greetings,
I have been lurking around and toying with the platform, but i've hit a wall.
How can i rebalance a portfolio every n weeks?
My algorithm ranks the stocks on the first day of the first week for the period and i want it to hold this portfolio for the next 2 weeks (first 2 weeks), then it should rebalance on the first day of the third week.
Would appreciate any help!
Thanks in advance!

2 responses

@Ivan

Try something like this:

# Trade every n weeks  
# ------------  
freq_week = 2  
# ------------  
def initialize(context):  
    schedule_function(rebalance, date_rules.week_start(), time_rules.market_close(minutes = 30))  
    context.counter = 0

def rebalance(context, data):  
    context.counter += 1  
    if context.counter == freq_week:  
        trade(context, data)  
        context.counter = 0 

def trade(context, data):  
    print(get_datetime('US/Eastern'))  

Thank you!
I've had something similar but it didn't register correctly, this works flawlessly!
Best,
Ivan