Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
The "Transaction Details" is differ from what the algorithm "wants"

Hi,

My algorithm is very simple as follow:

import numpy as np

# This function is run once at the beginning of the algorithm, REQUIRED  
def initialize(context):  
    context.stock = sid(24)  
# This function is run once per day before any calls to handle_data, OPTIONAL  
def before_trading_start(context, data):  
    pass  
# This function is run once per bar, REQUIRED  
def handle_data(context, data):  
    # Record leverage and number of held positions  
    record(num_position=len(context.portfolio.positions))

    # Sell all of our shares by setting the target position to zero  
    for stock in context.portfolio.positions:  
        order_target(context.portfolio.positions[stock].sid, 0)  
        log.info("Selling:%s" %(context.portfolio.positions[stock].sid.symbol))  
    for stock in data:  
        order_target(stock, 400)  
        log.info("Buying:%s, Close:%.2f" %(stock, data[stock].close_price))  
        log.info("---\n")  

What it does is simply sell and buy the stock AAPL everyday . I run a back test from 2016-02-22 to 2016-03-02. Here are the logs:

... 2016-02-22handle_data:24INFOBuying:Equity(24 [AAPL]), Close:96.89
2016-02-22handle_data:25INFO---
2016-02-23handle_data:20INFOSelling:AAPL
2016-02-23handle_data:24INFOBuying:Equity(24 [AAPL]), Close:94.69
2016-02-23handle_data:25INFO---
2016-02-24handle_data:24INFOBuying:Equity(24 [AAPL]), Close:96.10
2016-02-24handle_data:25INFO---
2016-02-25handle_data:20INFOSelling:AAPL
2016-02-25handle_data:24INFOBuying:Equity(24 [AAPL]), Close:96.75
2016-02-25handle_data:25INFO---
2016-02-26handle_data:24INFOBuying:Equity(24 [AAPL]), Close:96.91
2016-02-26handle_data:25INFO---
2016-02-29handle_data:20INFOSelling:AAPL
2016-02-29handle_data:24INFOBuying:Equity(24 [AAPL]), Close:96.65
2016-02-29handle_data:25INFO---
2016-03-01handle_data:24INFOBuying:Equity(24 [AAPL]), Close:100.53
2016-03-01handle_data:25INFO---
2016-03-02handle_data:20INFOSelling:AAPL
2016-03-02handle_data:24INFOBuying:Equity(24 [AAPL]), Close:100.73
2016-03-02handle_data:25INFO---
This backtest didn't generate any logs.
...

One can see, at the first day it buys the AAPL. The second day it sells the position. Till now everything is OK. But on the third day (2016-02-24), it didn't sell the position but buy a new one.

The same situation happens on 2016-02-26 and 2016-03-01.

If I look into the "Transaction Details", it tells even worse.

I wonder why. Could someone tell me where is the problem?

Regards

Thomas