-1

I am backtesting a simple moving average strategy, using price (for example daily bars) and a simple moving average. I want to find out how often the price crossed over or below the moving average over my historical data for stock X. In other words I want to find out the total number of crossovers.

I also want to find out the maximum / minimum point between each crossover. As price moves around the moving average it is sometimes above the average and sometimes below. I want to measure theese alterations. By this I mean the highest distance in ticks or percent between crossover A and crossover B, using crossover A as the baseline.

Please look at this picture to clarify what I mean:

enter image description here

I would appreciate any help that can point me in the right direction on how to code this in Python :-)

Dave
  • 5,108
  • 16
  • 30
  • 40

1 Answers1

0

As a first step, to calculate the number of crosses and when they occur, you can do something like the below. Treat it as pseudocode to get an idea..

# MA: list containing the values of the moving average for each time period
# High: list containing the highs of each bar 
# Low: list containing the lows of each bar
MA = [...]
High = [...]
Low = [...]
count = 0  # the number of crosses
index_cross = []  # the indices where crosses occur
for i in range(len(MA)):
    if Low[i] < MA[i] and High[i] > MA[i]:
        index_cross.append(i)
        count += 1 

Now you have the number of crosses and when they occurred. This assumes that the bars cross the MA. (i.e. there are no gaps, where the previous bar's low is above the MA and the current bar's high is below the MA). Then you can proceed by using the index_cross indices to find the maximum deviation of the price from where the cross happened. You have to consider if you will use closing prices or in the case of uptrends-highs and in the case of downtrends-lows..

As a side note, to annotate a graph with the points of interest, you can look into pandas (library for data analysis). Also such annotations tend to get quite messy when the markets are ranging. Hope this gives some direction..

gxpr
  • 836
  • 9
  • 12