Back to Community
How to automatically sell a stock if you lose or gain x%


I am brand new to the world of Quantopian. Based on my 1 week here, I have really enjoyed the functionality and community that this site

I am not a finance guy and have no formal training in finance (Im a geologist by profession). However, I find computers fascinating and I love the idea of creating automated trading strategies. That being said, please excuse my ignorance as Im sure to have some basic and probably large misunderstandings about how finance works.

I have written a code in vba that calculates stochastic oscillators (k and d values) for the entire stock market and then measures how accurately they predict positive price swings. I have had good success with this program and I would like to implement the list of stocks that perform well with stochastic oscillators into the below code (stolen from the help page).

I unfortunately do not have much experience with python. I am picking it up as I go, but wanted to ask a few functionality questions.

I would like to add the functionalities of the following to the code

I would like to sell my current position if I have lost 5% on my initial investment
I would like to sell my current position if I have gained 10% on my initial investment
I would like to sell my current position if I have held it for the equivalent of 15 business days.

Is this possible?

import talib  
import numpy as np  
import pandas as pd

# Setup our variables  
def initialize(context):  
    context.stocks = symbols('GOODO')  

    # Set the percent of the account to be invested per stock  
    context.long_pct_per_stock = 1.0 / len(context.stocks)  

    schedule_function(rebalance, date_rules.every_day(), time_rules.market_open())

# Rebalance daily.  
def rebalance(context, data):  
    # Load historical data for the stocks  
    hist = data.history(context.stocks, ['high', 'low', 'close'], 30, '1d')  
    # Iterate over our list of stocks  
    for stock in context.stocks:  
        current_position = context.portfolio.positions[stock].amount  
        slowk, slowd = talib.STOCH(hist['high'][stock],  

        # get the most recent value  
        slowk = slowk[-1]  
        slowd = slowd[-1]  

        if slowd < 20 and current_position <= 0 and data.can_trade(stock):  
            order_target_percent(stock, context.long_pct_per_stock)  
        # If either the slowk or slowd are larger than 90, the stock is  
        # 'overbought' and the position is closed.  
        elif slowd > 80 and current_position >= 0 and data.can_trade(stock):  
            order_target(stock, 0)  
1 response

context.portfolio.positions[sec].cost_basis gives you the price that you bought the stock at