Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
buy one stock at specified date and sell it at some price, but algorithm always 0%, why?

I am new to quantopian. I just want to buy one stock and sell it. It should be simple example already but I cannot find it.
I have to write it myself. but why algorithm alwyas 0%.

4 responses

Try this way:

from datetime import datetime, time  
# -----------------------------------------------------------------------  
security = symbol('MPC'); start = 1530302400; end = 1530302400 + 86400*14  
# -----------------------------------------------------------------------  
def initialize(context):  
    schedule_function(trade, date_rules.every_day(), time_rules.market_open(minutes = 1) )  
    context.isPurchased = False  
    context.isSelled = False

def trade(context, data):  
    today = get_datetime('America/New_York')  
    # log.info(today)  
    todayTime = datetime.combine(today, time())  
    todayTimeEpoch = int(todayTime.strftime('%s'))  
    # log.info(todayTimeEpoch)  
    if (todayTimeEpoch >=  start) and (todayTimeEpoch <= end):  
        price = data.current(security, 'price')  
        if not context.isPurchased:  
            order_target_percent(security, 1)  
            context.isPurchased = True  
            log.info(price)  
            log.info("buy")  
        if context.isPurchased:  
            if not context.isSelled:  
                if price > 71.91:  
                    order_target_percent(security, 0)  
                    context.isSelled = True  
                    log.info(price)  
                    log.info("sell")  

Thank you Vladimir .
After replacing order with order_target_percent for buying and selling, the return is not 0.
but buy and sell happen many times now.
so, my question is:
1. why order_target_percent works, but order, order_target(I just tried) do not work
2. why the transaction happens many times, I use two bool variables(context.isPurchased, context.isSelled) to make sure the order_target_percent called once(for buy or sell)

buy and sell happen many times now.

1 Try to reduce initial capital to 10000.
2 Use schedule_function instead of handle_data as in my code.

This may help you to understand Quantopian default slippage model.

1 Try to reduce initial capital to 10000.
Yes, now the transactions happen only twice.