Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Need help to code portfolio with 50% market timing

Hello,

I have a portfolio that is 50% market timing.
Does anyone have any tip how I can code the following:
Buy SPY when the month end closing price is above SMA50, and sell when month end closing is below SMA50.

Eg.
Starting cash is $20k, that means $10k is allocated to market timing.
Jan 2010, I purchase 100x SPY at $100k each.
Feb 2010, I sell 100x SPY at $110k each.
Apr 2010, I purchase 122 x SPY at $90 each.

The part I am having problem is to record the total cash I get from selling the SPY, and this amount of cash will be used to purchase SPY when the price is above SMA50.

Does anyone here have any clue how to do this?

Thank you in advanced.

2 responses

Leon Teh ,

May be this will help you:

# -----------------------------------------  
security, ma, lev = symbol('SPY'), 50, 0.5  
# -----------------------------------------  
def initialize(context):  
    schedule_function(trade, date_rules.month_end(), time_rules.market_open(minutes = 65))

def trade(context,data):  
    if get_open_orders(): return

    price = data.current(security,'price')  
    mavg = data.history(security, 'price', ma, '1d').mean()  
    current_positions = context.portfolio.positions[security].amount  
    cash = context.portfolio.cash    

    if data.can_trade(security):  
        if (price > mavg ) and current_positions == 0 :  
            number_of_shares = int(lev*cash / price )  
            order(security, number_of_shares )  
        elif (price < mavg) and current_positions != 0:  
            order_target(security, 0 )

    record(leverage = context.account.leverage)  

Thank you very much =)