Back to Community
Algo adding target to current_price instead of subtracting...

Not sure if I have this formatted correctly, but here goes.

When we take a short position, I want to set the context.target to the current_price - context.tgtval.

But the code appears to be adding the context.tgtval instead of subtracting it.

It even adds the value when I remove the variable and type the amount directly.

I put a comment with the word BUG right above where this happens.

What am I doing incorrect?

Clone Algorithm
8
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
import pytz
EST = pytz.timezone('US/Eastern')
import datetime


# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
    context.stocks = [sid(23709)] # NFLX
    context.previous_price = 1
    context.previous_hi = 0
    context.previous_lo = 0
    context.initialize = True
    context.event_day = 0
    context.new_day = False
    context.day_counter = 0
    context.bought = False
    context.day_submitted = 0
    context.num_shares = 0
    context.gapup = False
    context.gapdown = False
    context.hi = 0
    context.lo = 0
    context.target = 0
    context.tgtval = .50  # amount of profit per share we want to target.
    context.fulltrade = False
    context.filltarget = 0
    context.stoploss = 0
    pass

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    # Implement your algorithm logic here.
   # event_datetime = data[context.stocks[0]].datetime
    current_price = data[context.stocks[0]].price
    context.hi = data[context.stocks[0]].high
    context.lo = data[context.stocks[0]].low
    event_day = data[context.stocks[0]].datetime.day
    
    if context.initialize:
        context.event_day = event_day
        context.initialize = False 
    
    if event_day != context.event_day:
        context.new_day = True
        context.gapup = False
        context.gapdown = False
    else:
        context.new_day = False
        
        
    if context.bought:
        # logic to manage profit and loss belongs here.
        
        #Risk management check for positions that need to be dropped.
        if (context.portfolio.positions[context.stocks[0]].amount < 0) and context.gapup and current_price >= context.longr1:
            order(context.stocks[0],-context.portfolio.positions[context.stocks[0]].amount)
            context.bought = False
            print 'short position sold'
        
        #
        if (context.portfolio.positions[context.stocks[0]].amount > 0) and context.gapdown and current_price <= context.shortr1:
            order(context.stocks[0],context.portfolio.positions[context.stocks[0]].amount)
            context.bought = False        
            print 'long position sold'
        
        # If our target has been met, let's reset the target and set a rolling stop.
        if (context.portfolio.positions[context.stocks[0]].amount > 0) and (current_price > context.target):
            context.stoploss = context.target - .10
            context.target = context.target + (context.tgtval / 2)
            print 'stoploss increased long'
        
        # If our stoploss is hit, lets liquidate the position
        if (context.portfolio.positions[context.stocks[0]].amount > 0) and (current_price < context.stoploss):
            context.stoploss = 0
            context.target = 0
            order(context.stocks[0],-context.portfolio.positions[context.stocks[0]].amount)
            context.bought = False
            print 'stoploss hit liquidate'
        #
        # If our target has been met, let's reset the target and set a rolling stop.
        if (context.portfolio.positions[context.stocks[0]].amount < 0) and (current_price < context.target):
            print 'current price: ' + str(current_price)
            print ' current stoploss: ' + str(context.stoploss)
            print ' current target: ' + str(context.target)
            context.stoploss = context.target + .10
            context.target = context.target - (context.tgtval / 2)
            print 'stoploss increased short'
            print ' new stoploss: ' + str(context.stoploss)        
        # If our stoploss is hit, lets liquidate the position
        if (context.portfolio.positions[context.stocks[0]].amount < 0) and (current_price > context.stoploss):
            context.stoploss = 0
            context.target = 0
            order(context.stocks[0],context.portfolio.positions[context.stocks[0]].amount)
            context.bought = False        
            print 'stoploss hit liquidate'
        
        #

    else:
        # start logic to determine if we want to take a position.
        if context.new_day and not(context.day_counter==1):
            context.day_counter = context.day_counter + 1
            # Time to set our buy ranges.
            # Long buyrange will be .10 to .20 above open.
            context.longr1 = current_price + .10
            context.longr2 = current_price + .20
            # Short buy range is .10 to .20 below open.
            context.shortr1 = current_price -.10
            context.shortr2 = current_price -.20

            
            # New day and price is higher than previous close we have a gap up.
            # Until the gap is filled, we can only trade in the direction of the fill.
            # Once filled, we can take both long and short positions.
            if current_price > context.previous_hi:
                context.fulltrade = False
                context.gapup = True
                context.filltarget = context.previous_hi
                
                
            # New day and price is lower than previous close we have a gap down.
            # Until the gap is filled, we can only trade in the direction of the fill.
            # Once filled, we can take both long and short positions.
            elif current_price < context.previous_hi:
                  context.fulltrade = False
                  context.gapdown = True
                  context.filltarget = context.previous_lo
            
        # New day, but not first day, increment counter.
        else:
             context.day_counter = context.day_counter + 1
             
        #check for fills.
        if context.gapup and (context.filltarget >= current_price):
            context.fulltrade = True
        elif context.gapdown and (context.filltarget <= current_price):
              context.fulltrade = True
            
        # Check for opportunities to take a position.
    
        # Short opportunity with gapup and cross into short buyzone.
        if context.gapup and (context.fulltrade == False):
            if context.shortr1 >= current_price >=context.shortr2:
            #Check available funds for a position.
            
                if (context.portfolio.starting_cash - context.portfolio.capital_used) > (10000):
                    context.bought = True
                    
                    print 'short sell open'
                    ## BUG - Why is the context.target adding context.tgtval instead of subtracting context.tgtval?
                    context.target = current_price - context.tgtval
                    order(context.stocks[0],-(10000/current_price))
                    print ' current price: ' + str(current_price)
                    print 'target: ' + str(context.target)
        # Long opportunity with gapdown and cross into long buyzone.
        if context.gapdown and (context.fulltrade == False):
            if context.longr1 <= current_price <=context.longr2:
            #Check available funds for a position.
            
                if (context.portfolio.starting_cash - context.portfolio.capital_used) > (10000):
                    context.bought = True
                    context.target = current_price + context.tgtval
                    order(context.stocks[0],(10000/current_price))
                    print 'long purchase open'
        # Check for fulltrade opportunities.
    
        if (context.fulltrade):
            if context.shortr1 >= current_price >=context.shortr2:
            #Check available funds for a position.
            
                if (context.portfolio.starting_cash - context.portfolio.capital_used) > (10000):
                    context.bought = True
                    context.target = current_price + context.tgtval
                    order(context.stocks[0],-(10000/current_price))
                    print 'short sell open'
        
            if context.longr1 <= current_price <=context.longr2:
            #Check available funds for a position.
            
                if (context.portfolio.starting_cash - context.portfolio.capital_used) > (10000):
                    context.bought = True
                    context.target = current_price - context.tgtval
                    order(context.stocks[0],(10000/current_price))        
                    print 'long purchase open'
                        
    #                    
            
    #        
            
    #        
            
    #
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    #set variables for next tick
    context.previous_price = current_price
    context.previous_hi = context.hi
    context.previous_lo = context.lo
    context.event_day = event_day
            
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.
1 response

Chuck, that branch of code is never executed because cash is never $10k more than capital_used in your time period.

Also you should know that both cash and capital_used are calculated as the net of long and short positions (short dollars subtracted from long dollars). You may be expecting them to be calculated as the absolute sum (I posted a recent thread on the subject).

Your use of the variables may be consistent with the net calculation but I wanted to bring it to your attention nonetheless.

Clone Algorithm
2
Loading...
Backtest from to with initial capital
Total Returns
--
Alpha
--
Beta
--
Sharpe
--
Sortino
--
Max Drawdown
--
Benchmark Returns
--
Volatility
--
Returns 1 Month 3 Month 6 Month 12 Month
Alpha 1 Month 3 Month 6 Month 12 Month
Beta 1 Month 3 Month 6 Month 12 Month
Sharpe 1 Month 3 Month 6 Month 12 Month
Sortino 1 Month 3 Month 6 Month 12 Month
Volatility 1 Month 3 Month 6 Month 12 Month
Max Drawdown 1 Month 3 Month 6 Month 12 Month
import pytz
EST = pytz.timezone('US/Eastern')
import datetime


# Put any initialization logic here.  The context object will be passed to
# the other methods in your algorithm.
def initialize(context):
    context.stocks = [sid(23709)] # NFLX
    context.previous_price = 1
    context.previous_hi = 0
    context.previous_lo = 0
    context.initialize = True
    context.event_day = 0
    context.new_day = False
    context.day_counter = 0
    context.bought = False
    context.day_submitted = 0
    context.num_shares = 0
    context.gapup = False
    context.gapdown = False
    context.hi = 0
    context.lo = 0
    context.target = 0
    context.tgtval = .50  # amount of profit per share we want to target.
    context.fulltrade = False
    context.filltarget = 0
    context.stoploss = 0
    pass

# Will be called on every trade event for the securities you specify. 
def handle_data(context, data):
    # Implement your algorithm logic here.
   # event_datetime = data[context.stocks[0]].datetime
    current_price = data[context.stocks[0]].price
    context.hi = data[context.stocks[0]].high
    context.lo = data[context.stocks[0]].low
    event_day = data[context.stocks[0]].datetime.day
    
    if context.initialize:
        context.event_day = event_day
        context.initialize = False 
    
    if event_day != context.event_day:
        context.new_day = True
        context.gapup = False
        context.gapdown = False
    else:
        context.new_day = False
        
        
    if context.bought:
        # logic to manage profit and loss belongs here.
        
        #Risk management check for positions that need to be dropped.
        if (context.portfolio.positions[context.stocks[0]].amount < 0) and context.gapup and current_price >= context.longr1:
            order(context.stocks[0],-context.portfolio.positions[context.stocks[0]].amount)
            context.bought = False
            print 'short position sold'
        
        #
        if (context.portfolio.positions[context.stocks[0]].amount > 0) and context.gapdown and current_price <= context.shortr1:
            order(context.stocks[0],context.portfolio.positions[context.stocks[0]].amount)
            context.bought = False        
            print 'long position sold'
        
        # If our target has been met, let's reset the target and set a rolling stop.
        if (context.portfolio.positions[context.stocks[0]].amount > 0) and (current_price > context.target):
            context.stoploss = context.target - .10
            context.target = context.target + (context.tgtval / 2)
            print 'stoploss increased long'
        
        # If our stoploss is hit, lets liquidate the position
        if (context.portfolio.positions[context.stocks[0]].amount > 0) and (current_price < context.stoploss):
            context.stoploss = 0
            context.target = 0
            order(context.stocks[0],-context.portfolio.positions[context.stocks[0]].amount)
            context.bought = False
            print 'stoploss hit liquidate'
        #
        # If our target has been met, let's reset the target and set a rolling stop.
        if (context.portfolio.positions[context.stocks[0]].amount < 0) and (current_price < context.target):
            print 'current price: ' + str(current_price)
            print ' current stoploss: ' + str(context.stoploss)
            print ' current target: ' + str(context.target)
            context.stoploss = context.target + .10
            context.target = context.target - (context.tgtval / 2)
            print 'stoploss increased short'
            print ' new stoploss: ' + str(context.stoploss)        
        # If our stoploss is hit, lets liquidate the position
        if (context.portfolio.positions[context.stocks[0]].amount < 0) and (current_price > context.stoploss):
            context.stoploss = 0
            context.target = 0
            order(context.stocks[0],context.portfolio.positions[context.stocks[0]].amount)
            context.bought = False        
            print 'stoploss hit liquidate'
        
        #

    else:
        # start logic to determine if we want to take a position.
        if context.new_day and not(context.day_counter==1):
            context.day_counter = context.day_counter + 1
            # Time to set our buy ranges.
            # Long buyrange will be .10 to .20 above open.
            context.longr1 = current_price + .10
            context.longr2 = current_price + .20
            # Short buy range is .10 to .20 below open.
            context.shortr1 = current_price -.10
            context.shortr2 = current_price -.20

            
            # New day and price is higher than previous close we have a gap up.
            # Until the gap is filled, we can only trade in the direction of the fill.
            # Once filled, we can take both long and short positions.
            if current_price > context.previous_hi:
                context.fulltrade = False
                context.gapup = True
                context.filltarget = context.previous_hi
                
                
            # New day and price is lower than previous close we have a gap down.
            # Until the gap is filled, we can only trade in the direction of the fill.
            # Once filled, we can take both long and short positions.
            elif current_price < context.previous_hi:
                  context.fulltrade = False
                  context.gapdown = True
                  context.filltarget = context.previous_lo
            
        # New day, but not first day, increment counter.
        else:
             context.day_counter = context.day_counter + 1
             
        #check for fills.
        if context.gapup and (context.filltarget >= current_price):
            context.fulltrade = True
        elif context.gapdown and (context.filltarget <= current_price):
              context.fulltrade = True
            
        # Check for opportunities to take a position.
    
        # Short opportunity with gapup and cross into short buyzone.
        if context.gapup and (context.fulltrade == False):
            if context.shortr1 >= current_price >=context.shortr2:
            #Check available funds for a position.
            
                record( cash = context.portfolio.starting_cash )
                record( capital_used = context.portfolio.capital_used )
                if (context.portfolio.starting_cash - context.portfolio.capital_used) > (10000):
                    context.bought = True
                    
                    print 'short sell open'
                    ## BUG - Why is the context.target adding context.tgtval instead of subtracting context.tgtval?
                    record( tgtval = context.tgtval )
                    log.debug( 'tgtval: {}'.format( context.tgtval ))
                    context.target = current_price - context.tgtval
                    order(context.stocks[0],-(10000/current_price))
                    print ' current price: ' + str(current_price)
                    print 'target: ' + str(context.target)
        # Long opportunity with gapdown and cross into long buyzone.
        if context.gapdown and (context.fulltrade == False):
            if context.longr1 <= current_price <=context.longr2:
            #Check available funds for a position.
            
                if (context.portfolio.starting_cash - context.portfolio.capital_used) > (10000):
                    context.bought = True
                    context.target = current_price + context.tgtval
                    order(context.stocks[0],(10000/current_price))
                    print 'long purchase open'
        # Check for fulltrade opportunities.
    
        if (context.fulltrade):
            if context.shortr1 >= current_price >=context.shortr2:
            #Check available funds for a position.
            
                if (context.portfolio.starting_cash - context.portfolio.capital_used) > (10000):
                    context.bought = True
                    context.target = current_price + context.tgtval
                    order(context.stocks[0],-(10000/current_price))
                    print 'short sell open'
        
            if context.longr1 <= current_price <=context.longr2:
            #Check available funds for a position.
            
                if (context.portfolio.starting_cash - context.portfolio.capital_used) > (10000):
                    context.bought = True
                    context.target = current_price - context.tgtval
                    order(context.stocks[0],(10000/current_price))        
                    print 'long purchase open'
                        
    #                    
            
    #        
            
    #        
            
    #
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    #set variables for next tick
    context.previous_price = current_price
    context.previous_hi = context.hi
    context.previous_lo = context.lo
    context.event_day = event_day
            
This backtest was created using an older version of the backtester. Please re-run this backtest to see results using the latest backtester. Learn more about the recent changes.
There was a runtime error.