Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Help with code

How to code this simple system for daily bars?

High of 5 bars ago > high of 3 bars ago AND low of 4 bars ago < low 2 bars ago AND close > high of yesterday then
buy at next open 100 shares with 5% profit target and 3% stop-loss

8 responses

Hi Ricardo,

Here is sample code for your strategy. I didn't include the condition when close > high of yesterday because this would be forward-bias. In the middle of the day today you cannot know what will be the stock's close price.

This strategy will exit after a 3% loss or a 5% profit. Meanwhile, it will keep buying 100 shares of the stock.

For your reference, there are also other ordering methods available, such as stop-order, limit order, and stop-limit orders.

Cheers,
Alisa

Disclaimer

The material on this website is provided for informational purposes only and does not constitute an offer to sell, a solicitation to buy, or a recommendation or endorsement for any security or strategy, nor does it constitute an offer to provide investment advisory services by Quantopian. In addition, the material offers no opinion with respect to the suitability of any security or specific investment. No information contained herein should be regarded as a suggestion to engage in or refrain from any investment-related course of action as none of Quantopian nor any of its affiliates is undertaking to provide investment advice, act as an adviser to any plan or entity subject to the Employee Retirement Income Security Act of 1974, as amended, individual retirement account or individual retirement annuity, or give advice in a fiduciary capacity with respect to the materials presented herein. If you are an individual retirement or other investor, contact your financial advisor or other fiduciary unrelated to Quantopian about whether any given investment idea, strategy, product or service described herein may be appropriate for your circumstances. All investments involve risk, including loss of principal. Quantopian makes no guarantees as to the accuracy or completeness of the views expressed in the website. The views are subject to change, and may have become unreliable for various reasons, including changes in market conditions or economic circumstances.

Hey Ricardo,

I made a few additions to Alisa's algorithm. I assume by close > high of yesterday then buy at next open 100 shares you mean that if today's close is greater than the high of yesterday buy 100 shares of NFLX at the open tomorrow. I implemented functions to check if the current time is at the open/close of the day. Let us know if you have any more questions!

Ryan

Thank you both but the codes above do not reflect my conditions. By the way, close > high of yesterday, means that the close of today is higher then the high of yesterday and it is not forward looking in any sense but I should have made that clear I guess. If I assume correctly that in highPrice.ix[0, context.nflx] > highPrice.ix[2, context.nflx] the former is the high of today and the latter the high of 2 days ago, then this is not related to my conditions.

Hello Ricardo,

highPrice = history(6,'1d', 'high')  

produces a DataFrame of results with a column for each security. The value of '6' periods specifies that 6 rows of results are returned i.e. for 5 days plus the current minute. Then

highPrice.ix[0, security]  

denotes the first/oldest value i.e. 5 days ago and

highPrice.ix[2, security]  

denotes the value for 3 days ago.

P.

Thank you for your answers but I wonder why is this here done opposite to the way the majority of other platforms do it with 0 representing the most recent value. I find it very confusing trying to convert my algos to this notation. Has the developer looked at how this is done the last 25 years by most trading platforms or it was deliberately done this way for purpose of differentiation? I mean essentially it does not matter but it would make life easier to maintain some consistency with other platforms.

Hello Ricardo,

I would have thought numbering from 0 (ignoring R and FORTRAN) for the first/oldest element of a time series was the norm? The only time I can recall 0 indexing the most recent element in a time series is MQL i.e. "Series array elements are indexed in the reverse order, i.e., from the last one to the first one. The current bar which is the last in the array is indexed as 0." See: http://docs.mql4.com/predefined/close

Where else have you seen the 0th element as the most recent?

P.

Tradestation, Amibroker, Ninja Trader, Meta Trader, Metastock and in a few more I now do not recall the names. An index of 0 for the most recent element is natural because if the lookback period changes, when for example when one wants to add a rule referencing elements beyond the current lookback period, the code need not change. The way the elements are indexed in Quantopian means that the indexing must completely change. Maybe this was done for some other good reason I cannot think of at the moment but it is not the way everyone else does it (or most of the platforms I have seen) and to me it appears like a limitation unless there is a good justification for it.

Hey Ricardo,

If you would prefer to have have the indices reversed, feel free to use the function I wrote here. I demonstrate it using price and volume historical data.

from pandas import DataFrame as df  
import numpy as np

def initialize(context):  
    context.securities = [sid(24), sid(2673), sid(5061)]

def handle_data(context, data):  
    prices = history(11, '1d', 'price').ix[:-1]  
    new_prices = reverse(context, prices)  
    print('New data frame of prices:' + '\n' +  '%s' % new_prices)  
    volumes = history(11, '1d', 'volume').ix[:-1]  
    new_volume = reverse(context, volumes)  
    print('New data frame of volume:' + '\n' +  '%s' % new_volume)

def reverse(context, prices):  
    symbols = []  
    for sec in context.securities:  
        symbols.append(sec.symbol)  
    df3 = df(np.zeros((len(prices), 3)), columns = symbols, index = prices.index.values[::-1])  
    df3.ix[:,symbols] = prices  
    for i in range(0,len(context.securities)):  
        df3.ix[:,i] = np.array(prices)[:,i][::-1]  
    return df3