How can I code cross-over of moving averages to trigger the order?

I have researched through some of the forums and I don't see the answers for coding trigger for crossing of averages

Comments

  • ptunneyptunney Posts: 246

    What periods of moving average crosses are you looking at.

    As a note, a moving average cross is only really useful as a training exercise. They may look good when you look at them on a chart but in real life they are lagging indicators meaning you are always late in and late out, if you try to move closer to the cross event your indicator actually crosses and uncrosses too frequently.

  • To answer your question, I currently trying to test 5 days and 8 days, 50 days and 200days interval.

    I'm trying to script a back test system where I uses moving average crosses on different days.
    My goal is to test the indicator that has best win rates.
    I may develop onto RSI and other indicator cross over as well.

  • ptunneyptunney Posts: 246

    Watch the beginner set of videos on the home tab or on our YouTube page.
    Then also watch the TALIB video if you plan to do RSI.

    But for testing, qualify one symbol, a nice big one that will always give you bars.. say SPY
    Then pull the bars for the longest period you are intersted in, pull all the bars into a variable called mybars.
    Then pull out the data and the length of data using Python list manipulation.
    There are two ways to calculate a moving average, pass it to TALIB or do it yourself.
    For moving average doing it yourself is probably easiest, but for more compicated Trading expressions TALIB will probably work better for you.

    So this would look something like this ...

    from cloudquant.interfaces import Strategy
    import talib
    import numpy
    
    class MovingAverage(Strategy):
    
        @classmethod
        def is_symbol_qualified(cls, symbol, md, service, account):
            return symbol== 'SPY'
    
        def on_start(self, md, order, service, account):
            print self.symbol
    
            # First we need some historic data so lets grab 400 daily bars
            daily_bars = md.bar.daily(start=-400,include_empty=False) 
    
            # most TALIB calls use OHLC (Open, High, Low, Close) in some form so lets pull those out so we have them ready
            open = daily_bars.open   
            high = daily_bars.high   
            low = daily_bars.low     
            close = daily_bars.close 
            volume = daily_bars.volume
    
            # TALIB.MA - Moving Average - matype=0 by default...
            # 0 = SMA (Simple Moving Average) (Default)
            # 1 = EMA (Exponential Moving Average)
            # 2 = WMA (Weighted Moving Average)
            # 3 = DEMA (Double Exponential Moving Average)
            # 4 = TEMA (Triple Exponential Moving Average)
            # 5 = TRIMA (Triangular Moving Average)
            # 6 = KAMA (Kaufman Adaptive Moving Average)
            # 7 = MAMA (MESA Adaptive Moving Average)
            # 8 = T3 (Triple Exponential Moving Average)            
    
            SMA200 = talib.MA(close,timeperiod=200)
            SMA200list = numpy.ndarray.tolist(SMA200) 
            print "Simple Moving Average 200 period",SMA200list
            print "Most recent 200 period MA value",SMA200list[-1]
    
            SMA50 = talib.MA(close,timeperiod=50)
            SMA50list = numpy.ndarray.tolist(SMA50) 
            print "Simple Moving Average 50 periods",SMA50list
            print "Most recent 50 period MA value",SMA50list[-1]
    
            EMA200 = talib.MA(close,timeperiod=200,matype=1)
            EMA200list = numpy.ndarray.tolist(EMA200) 
            print "Exponential Moving Average",EMA200list
            print "Most recent 200 period EMA value",EMA200list[-1]
    
            RSI = talib.RSI(close, timeperiod=14)
            RSIlist = numpy.ndarray.tolist(RSI) 
            print "RSI",RSIlist
            print "Most recent 14 period RSI value",RSIlist[-1]
    
    
            print "Simple Moving Average 200      (last 3 entries)",SMA200list[-3:]
            print "Simple Moving Average  50      (last 3 entries)",SMA50list[-3:]
            print "Exponential Moving Average 200 (last 3 entries)",EMA200list[-3:]
            print "Average of last 200 close prices               ",sum(close[-200:])/len(close[-200:])
            print "Last Three close prices...", round(close[-3],2), round(close[-2],2), round(close[-1],2)
            print "last 20 close prices...",close[-20:]
            print
            service.terminate()
            return 
    

    This is not trading, just calculating MA and RSI. Getting into positions, holding for x days and exiting all requires extra code. Watch the videos.

    Also do not expect MA and RSI to give you a working profitable model. If it was that easy everyone would be doing it.

  • Thank you very much for the thorough explanation, I have seen all the videos and I got the calculation part.
    I will look through the videos again.
    The reason I am working on those model so they can give somewhat direction to my trading, as of right now, I am only trading based on patterns.

  • ptunneyptunney Posts: 246

    Good, only use these kind of things to back up your decisions.
    If so do what everyone else is doing the chance is you will always be the last one to the party.
    You are a unique human being with a unique view of the world. That is your advantage.
    Develop your own unique trading style, even if it is something as seemingly crazy as knowing the behavior one symbol better than anyone else.

Sign In or Register to comment.