Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Save yesterday's low of position entry date

Hello all,

I'm pretty new to Quantopian and having a hard time figuring out how to use position entry's yesterday low as stop price.

Here's my code so far and the low day keeps changing to yesterday's low and doesn't remember the low prior to entry date.

If someone can help me it'll be greatly appreciated.

Thanks,

import talib  
import numpy as np  
from pytz import timezone  
from datetime import datetime, timedelta  
from zipline.utils.tradingcalendar import get_early_closes  
from quantopian.algorithm import attach_pipeline, pipeline_output  
from quantopian.pipeline import Pipeline  
from quantopian.pipeline.data import Fundamentals  
from quantopian.pipeline.data.builtin import USEquityPricing  
from quantopian.pipeline.factors import AverageDollarVolume  
from quantopian.pipeline.filters.morningstar import Q500US #brings top 500 us stocks  
from scipy import stats #allows use of statistical functions

def initialize(context):  
    context.stock = sid(24)  
    context.index = sid(8554)

    schedule_function(trade , date_rules.every_day() , time_rules.market_close(minutes=10))  
def trade(context,data):  
    sp = data.current(context.index, 'close')  
    sphistory = data.history(context.index,'close',200,'1d')  
    prices = data.history(context.stock, 'close', 200, '1d')  
    price = data.current(context.stock, 'close')  
    low = data.current(context.stock,'low')  
    y_low = data.history(context.stock, 'low', 2, '1d')[-2]  
    sma= prices.mean()  
    spsma = sphistory.mean()  
    rsi = talib.RSI(prices, 2)  
    RSI_Yesterday = rsi[-2]  
    RSI_Today = rsi[-1]  
    for security, position in context.portfolio.positions.items():  
        stop_price = data.history(context.stock, 'low', 2, '1d')[-2]  
        stock_basis = position.cost_basis  
    if data.can_trade(context.stock):  
        if  low > y_low and price > sma and sp > spsma and price > 50 and RSI_Yesterday < 3 and context.portfolio.positions[context.stock].amount == 0:  
            order_target_percent(context.stock, 1.0)  
            print('We Are Buying')  
            print(low)  
            print(y_low)  
        if context.portfolio.positions[context.stock].amount > 0 and RSI_Today > 90:  
            order_target_percent(context.stock, 0)  
            print('We Are Selling - RSI > 95')  
        if context.portfolio.positions[context.stock].amount > 0 and price <= stop_price:  
            order_target_percent(context.stock, 0)  
            print('We Are Selling - StopLoss')  
            print(stop_price)