Quantopian's community platform is shutting down. Please read this post for more information and download your code.
Back to Community
Apply ADX and crossover between +DI and -DI

After reading the article from https://www.tradingview.com/script/VTPMMOrx-ADX-and-DI/ , I learned something of APX(average directional index), raised by Welles Wilder.
I've never learned any code before, so I cloned from the others' code and I think understanding the strategy is also important.
Summarizing how to calculate ADX:
Normally take 14 days as a unit
1.Calculate +DM&-DM(both larger or equal to 0)
+DM= Current's highest price - Previous's highest price(CH-PH)
-DM= PL - CL
If +DM>-DM & +DM>0, then +DM=+DM, else +DM=0
If +DM<-DM & -DM>0, then -DM=-DM, else-DM=0
DM14= previous DM *13/14+ current DM*1/14
2.Calculate TR(True Range)
TR= max(CH, previous closing price) - min(CL, PC)
TR 14 calculation is similar to DM14
3.Calculate DI
+DI14=(+DM14/TR14)*100
-DI14=(-DM14/TR14)*100
4.Calculate DX
DX14=ABS((+DM14--DM14)/(+DM14+-DM14))*100
5.ADX
ADX14=previous DX14*13/14+ current DX*1/14

If ADX is larger than 20(or maybe 25), the stock shows trends, it doesn't clarify upward or downward trend. So I decided to buy or sell securities only if ADX>20.
When +DI crossover -DI, it means price is going to go up afterwards, I buy at the moment, vice versa.
I tried to observe the relationship between EMA30 and ADX, DI on tradingview charts, but it doesn't have the indicators +DI and -DI. But I choose the period of AAPL security when most of time APX is very high, which shows strong tendency, and finally the return looks good.

But I have a small question about the code, why do we have to write "2*period" instead of just "period" in the data.history()?