Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Question: basic buy and sell strategy

Hey
I am currently trying to test a very basic buying and selling strategy.
What I want to do is buying when price is at lower Bollinger band and selling as soon as there is an increase of 0.5% or more.
I the price drops the strategy should buy the same amount again. For instance buy with 20% of the capital price drops and touches lower Bollinger agin therefore the code should buy with another 20% of the capital. As soon as the overall price increase is greater than 0.5% sell everything....

The problem is that it only buys when it sold something before, how can I get it to buy every time it is below the lower bb?

any help would be appreciated!

import talib

# Setup our variables  
def initialize(context):  
    context.stock = symbol('AAPL')  
    set_benchmark(symbol('AAPL'))  
    # Create a variable to track the date change  
    context.date = None

def handle_data(context, data):  
    current_position = context.portfolio.positions[context.stock].amount  
    price=data[context.stock].price  
    costBasis = context.portfolio.positions[context.stock].cost_basis  
    # Load historical data for the stocks  
    prices = history(30, '1m', 'price')  
    #price_history = data.history(security, 'price', 2, '1m')  
    upper, middle, lower = talib.BBANDS(  
        prices[context.stock],  
        timeperiod=20,  
        # number of non-biased standard deviations from the mean  
        nbdevup=2,  
        nbdevdn=1,  
        # Moving average type: simple moving average here  
        matype=0)

   # If price is below the recent lower band  
    if price <= lower[-1] and current_position <= 1.0:  
        order_target_percent(context.stock, 0.2)  
        print "buyprice", price  
    # If price is higher than 1.005 sell  
    # exit position  
    elif price > 1.005 * costBasis and current_position > 0:  
        order_target_percent(context.stock, 0.0)  
        print "sellprice", price  
        #print price  
    record(upper=upper[-1],  
           lower=lower[-1],  
           mean=middle[-1],  
           price=price,  
           position_size=current_position)  

Thanks for your help!!

2 responses

"The problem is that it only buys when it sold something before, how can I get it to buy every time it is below the lower bb?"

The code above will only buy if there are no current holdings.

    if price <= lower[-1] and current_position <= 1.0:  

'current_position' is the current number of shares held. So, this will only be true if there are no shares held. This is what keeps the algo from ordering every time the price is below the lower band. Probably what was intended is to order as long as the current holdings are less than 100% of the portfolio. One could do something like this

    position_value = context.portfolio.positions_value  
    portfolio_value = context.portfolio.portfolio_value

    if price <= lower[-1] and (position_value < portfolio_value):  

One issue you will need to address is outstanding orders. You will want to take into account the impact of any orders which haven't yet filled. At the very least don't place any orders if there are any outstanding orders open. A simple approach is something like this.

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

Hope that helps.

Thanks a lot Dan!
I tried it and it seems to work. One more thing that I would like to know is whether

context.portfolio.positions[context.stock].cost_basis  

is now giving me the average buying price or would I have to implement this separately ?

Another thing is that I would like the strategy not to buy again right after the last buy happened but instead add something like at least 30 minutes no buying after the last buy happened plus add a maximum of possible buys before selling it again. Any idea how I could do that?

Thanks a lot for your help!