Optimization moving average crossing strategy with “machine learning”

Optimization moving average crossing strategy with “machine learning”

This is a “machine learning” strategy for finding the best crossing strategy, comparing 70 different averages with each other, given a certain time frame and a certain market.

(The source of the very most of the averages is https://www.prorealcode.com/prorealtime-indicators/average-filter-regression/ posted by Laurenzo in 2017)

The strategy is simple:
If the first average crosses above the second average, go buy long
and vice versa if the first average crosses under the second average, sell short

It can be used for currencies and indices, presumably also for stocks (non-daytrading)

This strategy determines which of the 70 different averages is to be crossed with which of the same 70 different averages to give the best result in a certain market in a certain time frame, what in my opinion can be seen as a kind of  “machine learning”

Further added to this strategy:   (up to the user to adjust those variables if wanted)

  1. to protect the position, a stop loss (TSL) is added  (coded TSL = round(100/10000*close))
  2. exit a position every day at 16:00 hr (coded Defparam Flatafter = 160000) (Daytrading)
  3. limit to only one trade per day  (coded OTD = Barindex – TradeIndex(1) > IntradayBarIndex, If using “TradeIndex(3)”, it would allow 2 opening trades per day, TradeIndex(5) would allow 3 trades per day, and so on.
  4. Opening trades only between 8:00 and 11:30, for American trades other times can be set.

There are 70 different types of averages, (listed below), which are used to cross each other (the first is named MAType, to be crossing the second MATypeV2)

To limit zigzagging of the averages due to market noise, an exponential average of 30 is added before the crossing condition is measured (Coded as wAFR = exponentialaverage[30](AFR) and wAFRv2 = exponentialaverage[30](AFRv2))

To limit the possibilities, the period is set for all average-types to 15 (Coded as Period = 15, Period2 = 15), periods may be adjusted.

Different stop distances can be used or a trailing stop can be used.

Be aware that if you use this “machine learning” on a small set of data, the outcome will be over- fitted and a different optimized set of averages for a different small set of data will appear (this happens with all strategies, robustness of the strategy has to be tested).

Be aware when running the given strategy, already 70 x 70 combinations has to be optimized, which is already 4.900 combinations, which makes the optimizing process (very) slow. It might be a good idea to split the combination into 5 sets, lets say from 0 to 13 averages comparing to the 69 averages, and next 14 to 26 comparing to 69 averages, and so on, then taking the best from the 5 sets.

I run the code first without In Sample/Out of Sample, to find the  top 10 best average combinations, and around those top 10  run several In Sample/Out of Sample optimizations.

For In Sample/Out of Sample optimizations use 66% IS and 34% OOS, non repeated (not five runs)

The code is extremely long (> 3.600 lines), due to defining 70 and 70 different averages. Maybe it can be coded shorter ?

The crossing strategy itself can be found at the last rows !

I was not aware that PRT allows more then 3.600 lines of code as a strategy!

  1. Ahrens Moving Average
    1. Adjustable Lag FIR
    2. Arnaud Legoux Moving Average
    3. 2-Pole Butterworth Smoothing Filter
    4. 3-Pole Butterworth Smoothing Filter
    5. Corrected Moving Average by A.Uhl
    6. d9 Unscented Kalman Filter (Responsiveness Version)
    7. d9 Unscented Kalman Filter
    8. Double Exponential Moving Average
    9. Exponential Least Square Moving Average
    10. Exponential Moving Average
    11. Elastic Volume Weighted Moving Average
    12. Fast Adaptive Trend Line
    13. Fractional-Bar Quick Moving Average
    14. Fractal Adaptive Moving Average
    15. Generalized DEMA
    16. 1-Pole Gaussian Filter
    17. 2-Pole Gaussian Filter
    18. 3-Pole Gaussian Filter
    19. 4-Pole Gaussian Filter
    20. Hull Moving Average
    21. IE/2 Combination of LSMA and ILRS
    22. Integral of Linear Regression Slope
    23. iTrend by John Ehlers
    24. Jurik Moving Average (Responsiveness Version)
    25. Jurik Moving Average
    26. Kaufman Adaptive Moving Average
    27. Kalman Filter by John Ehlers
    28. Kalman Filter (Responsiveness Version)
    29. Kalman Filter
    30. Leader Exponential Moving Average
    31. Laguerre Filter by John Ehlers
    32. Least Square Moving Average
    33. McGinley Dynamic
    34. Middle High Low Range Moving Average
    35. McNicholl Moving Average
    36. Non Lag Moving Average (Responsiveness Version)
    37. Non Lag Moving Average
    38. One More Average
    39. Pentuple Exponential Moving Average
    40. Parabolic Weighted Moving Average
    41. Quadruple Exponential Moving Average
    42. Regularized EMA by Chris Satchwell
    43. Reference Fast Trend Line
    44. Reference Slow Trend Line
    45. Slow Adaptive Trend Line
    46. Simple Moving Average
    47. 2-Pole Super Smoothing Filter
    48. 3-Pole Super Smoothing Filter
    49. Smoothed Simple Moving Average
    50. Sine Weighted Moving Average
    51. T3 Moving Average
    52. Triple Exponential Moving Average
    53. Triangular Moving Average
    54. Time Series Average
    55. Variable Index Dynamic Average
    56. Variable Moving Average
    57. Volume Weighted Average Price
    58. Wilder Moving Average
    59. Weighted Least Square Moving Average
    60. Weighted Moving Average
    61. Zero Lag BMT
    62. Zero Lag Double Exponential Moving Average
    63. Zero Lag FIR Filter
    64. Zero Lag IIR Filter
    65. Zero Lag John Ehlers
    66. Zero Lag Weighted BMT
    67. Range based AV high + STD – low – STD
    68. Average highest [period] and lowest[period]
    69 DEMA adjusted by itself

Please download the attached itf (200308-Averages-crossing.itf) to play around with this strategy.

Share this

Risk disclosure:

No information on this site is investment advice or a solicitation to buy or sell any financial instrument. Past performance is not indicative of future results. Trading may expose you to risk of loss greater than your deposits and is only suitable for experienced investors who have sufficient financial means to bear such risk.

ProRealTime ITF files and other attachments : How to import ITF files into ProRealTime platform?

New! PRC is also now on YouTube, subscribe to our channel for exclusive content and tutorials

  1. criscolci • 27 days ago #

    Wow!

  2. MaoRai54 • 27 days ago #

    hello Jan,
    this is a fantastic idea but, as per I understood looking into the system, I think it cannot work as an automatic program. I mean that

  3. MaoRai54 • 27 days ago #

    hello Jan,
    this is a fantastic idea but, as per I understood looking into the system, I think it cannot work as an automatic program. I mean that the program is testing the 69+69 options but once it has ended you’ll have 2 fixed numbers as variables. Then you can use it in automatic run. So the variables chosen are referring only to the moment of the test. Am I right?

  4. Jan • 27 days ago #

    Yes, that is correct, it helps you select the 2 best kind of averages (out of 70), based on past data, given a market and given a time frame. Then after proper testing, you let the algo running on future market data with this setting.

  5. MaoRai54 • 27 days ago #

    OK Jan, do you see a way to let it test and run in automatic mode? something like a loop that anytime is testing the best variables

  6. Jan • 27 days ago #

    Interesting discussion.
    This algo will be based upon optimal settings, given past data, then assuming the past pattern of data will be repeated, or at least be repeated so much that it delivers profitable trades for the future.

    If the model would be using something like a loop that anytime it is testing the best variables, the measures have to be based upon the (short term) past, as future prices still have to come. . .
    The question is then of course: will the continuously (short term) past optimal crossing deliver better results for future trading than a setting based upon long term historical data or not ?

    If you want something like a loop that anytime is testing the best variables, you do NOT need to have 70 averages to test every time, a simple average compared with the close would already be sufficient and then let the system calculate the best average crossing based upon the last (for example) 40 bars every time. As said the concept is then based upon the assumption that the continuously measured (short term) price movements better predict future price movements as fixed settings, based upon many price movements over a long term. If you or anybody else know more about this, please let me know.

  7. MaoRai54 • 27 days ago #

    Jan, I’ve understood. Maybe in standard conditions it’s better to test the algo on the maximum time period. But in this period of coronavirus I think, even if we are always testing on past data, it would be better to test on a short period. In fact I’ve tested it for Eu/$ and Dax on 5 minutes base in the period 2march up today and I got gorgeous results with 100% winning trades. While I’m now testing them on 5m and 100.000 and I see only 50%-60% of winning and a low average earning value. If this volatily period will continue I think your algo is really amazing.!!!!

  8. frenqle • 27 days ago #

    Been playing around with this awesome code!!!
    where can i adjust the matype? i removed the variables allready.. but im a bit stuck.. my coding knowledge only goes soo far.
    because it wont let me prepare for auto trade?

  9. MaoRai54 • 27 days ago #

    Frenqle, if you remove the variables without fixing their values you cannot go for auto trade

  10. Jan • 27 days ago #

    Just delete MAType and MATypeV2 at Optimization parameters (straight above the first line of the code)

    Then type in the code
    Once MAType = what you want to select
    Once MATypeV2 = what you want to select

    Just a common warning, which is valid for every algo-strategy: make sure it is robust and properly tested, including In Sample and Out of Sample testing.

  11. frenqle • 26 days ago #

    dankjewel jan!!

  12. bertrandpinoy • 26 days ago #

    i can t make it work for real, can you better details the process please

    • bertrandpinoy • 25 days ago #

      hi Juan, yes of couse the file is imported. can you send sreenshoot of the process? i m blocked..

  13. Jan • 26 days ago #

    Could ypu be more specific ?
    Have you imported the itf-file already ?

    For let the strategy run (after importing the file):
    Just delete MAType and MATypeV2 at Optimization parameters (straight above the first line of the code)

    Then type in the code
    Once MAType = what you want to select
    Once MATypeV2 = what you want to select

    Hope it helps.

    • Jan • 24 days ago #

      Hi bertrandpinoy
      Where exactly are you blocked ?
      If you import the file, you can, given a time frame and a larger period, determine which crossing(s) of 2 averages gives the best results (like a top 10).
      Next step is to test this upon another set of data, see if the optimum averages varies significantly or not from the previous test.
      And then do an In Sample test of 66% and an Out of Sample Test with 34%, to determine if the best crossings of averages remain the same with the first test. You may restrict the chooseable averages to decrease the time for running this test.
      If you find your best 2 averages, follow the steps as I described below.
      Hope it helps you out.
      KR Jan

    • bertrandpinoy • 24 days ago #

      Hello Juan I manage to make very promising backtets. unfortunately I fail to launch the program in real mode, what a pity. Certainly my amateurism in the use of variables. damage.Maybe you can attach an ITF file that allows actual use on the CAC40?

    • bertrandpinoy • 20 days ago #

      hy Juan, i hope you re well. sorry to insit about this stratehy but i m really intersting. i m still bloked to run for real. can we exchange by e-mail? bertrandpinoy@hotmail.fr. best regards

  14. jevve • 25 days ago #

    Hi Jan

    How do i make it run Automatic trading. I get this message “Replace variables with specific values”?
    I guess its the the statement you made above, but i still cant get it right!?
    Thanks

  15. Jan • 25 days ago #

    Hi Jevve,
    yes, it is certainly the message above. KR Jan

  16. jevve • 25 days ago #

    Hi Jan
    After deleting the MAType and MATypev2 in the optimization, i then must type in the code
    Once MAType = what you want to select
    Once MATypeV2 = what you want to select

    But where exactly in the code should i type it in?
    thanks

  17. Jan • 25 days ago #

    Hi Jevve,
    Once MAType = 15 that is one of the moving averages of 0-69
    Once MATypev2 = 25 that is one of the second range of moving averages of 0-69

    Just a common warning, which is valid for every algo-strategy: make sure it is robust and properly tested, including In Sample and Out of Sample testing, before letting it trade automatically with real money.

    • frenqle • 25 days ago #

      which variables should i fill in for in and out of sample? i dont understand these labels and maximum and minimum area’s?

  18. Jan • 25 days ago #

    Hi Jevve,

    Sorry, just to answer your question: you can type it just below the defined periods, like line 29 in the code. (It has to be coded above all the definitions of the 70+70 averages)
    KR Jan

    • Jan • 24 days ago #

      Hi Frenqle,

      Determine which crossing(s) of 2 averages gives the best results (like a top 10), without In Sample Out of Sample turned on.
      (Next step is to test this upon another set of data, see if the optimum averages varies significantly or not from the previous test.)
      And then do an In Sample test of 66% and an Out of Sample Test with 34%, with 1 iteration) to determine if the best crossings of averages remain the same with the first test. You may restrict the chooseable averages (range 0-69 and 0-69) to a smaller range which fits around your best results, to decrease the time for running this test. (Check in the code of the chosen range are somewhere the same sort of averages as the best crossings)
      If the IS/OOS values of averages which is in fact based upon optimizing 66% of the first test set of data, varies significant from the averages chosen averages from the first set, it seems that the crossing is over fitted. This is only true,when the averages from the IS/OOS significantly differ from initial test.
      Hope it helps you out. En een goed weekend
      KR Jan

  19. darbes • 24 days ago #

    interessant : comment faire pour l’utiliser en live (message erreurs sur les variables) ?

  20. darbes • 24 days ago #

    Interesting : how to make it working in pro order (error message due to variables) ?

  21. Jan • 24 days ago #

    See comments above at answers at questions from Jevve, and I should do some additional testing and In Sample Out of Sample, as answered to questions of Frenqle, hopes it helps you out .
    A good weekend.
    KR Jan

  22. Marcus Quartus Aurius • 20 days ago #

    Thank you Sir ! it’s amazing code.

  23. frenqle • 19 days ago #

    Dear Jan, i managed to test your code and put it into automatic trading.. it runs for a few minutes and then it quits without any reason.. do you care to have a look?

    • bertrandpinoy • 19 days ago #

      Hello Frenqle, would you be so kind as to send me the working ITF file please? I can’t make it work myself…thank you in advance. here is my e-mail: bertrandpinoy@hotmail.fr
      very cordially

    • gkjefferys • 13 days ago #

      Hello Frenqle if possible please could you also send me the working ITF file please … I also can’t make mine work…Thank you very much
      gkjefferys@gmail.com

  24. Jan • 19 days ago #

    Hi Frenqle

    maybe it has to do with the stop loss setting. Normally when it stop in auto trading there is a warning sign at that strategy, if you click on that, maybe it gives a reason why it stopped.

    Generally speaking, in this volatile markets, stops of 1 % are very often stopped out too soon.
    Also in this very very volatile market, trending strategies often do not work (for example today Dow at opening – 3% and then 40 minutes later +1% is not to say trending)

    • frenqle • 18 days ago #

      Hi Jan,
      It just closes without a reason. Even in the report, it says nothing. it does not give any reason.
      Very weird, Can I send you the code?

  25. darbes • 18 days ago #

    I put line 29 the Matype and Matypv2 = to optimized level but still to go to live pro order is asking to remove variables. Which variables are involved ?

    • frenqle • 18 days ago #

      Hi Jan, It just closes without a reason.. even in the report it says nothing.. it doesnot give any reason

    • Jan • 18 days ago #

      Hi darbes,
      Did you delete MAType and MATypeV2 at “Optimization parameters” (straight above the first line of the code)

    • Jan • 18 days ago #

      The topic nontheless has opened, is https://www.prorealcode.com/topic/optimization-moving-average-crossing-strategy/

      frenqle, you can add your version of the code over there, then I will have a look why it stops in automatic trading.
      KR Jan

  26. nonetheless • 18 days ago #

    I opened a topic in the ProOrder forum to make discussion of this easier. Also uploaded 3 algos created with this amazing tool – thanks Jan!

  27. darbes • 17 days ago #

    Sorry Jan,
    Code is starting with Defparam, I do not find optmization. Where could I desactivate it ?
    Best JC

  28. darbes • 17 days ago #

    Hi Jan
    It is OK I found it
    Best

  29. gkjefferys • 15 days ago #

    Once MAType = 15 that is one of the moving averages of 0-69
    Once MATypev2 = 25 that is one of the second range of moving averages of 0-69

    Please can you tell me where i find this … what lines
    thanks very much

  30. darbes • 12 days ago #

    Hi Jan
    I have put live the strategy and so far so good 3 winning deals over 3> But why did you choose to exit position at 4PM. It is not adding an additional closing risk instead of a take profit ?
    Best
    JC

  31. Jan • 12 days ago #

    Hi gkjefferys, the lines can be found somewhere at the top cq must be added somewhere at line +/-15 if that answers your question.

    Hi Darbes, exit 16:00 hrs is daytrading, you can whipe that out, but that increase your risk, but also can increase your profit, be aware of overnight interest costs of the CFD you trade

  32. darbes • 12 days ago #

    I see. An alternative to take profit is to reduce on forex the TSL below 1% as forex vol is lower during the day. I will first work on this side to avoid closing position in a lottery way at 4PM.

  33. J. • 8 days ago #

    Very interesting Jan, thank you for sharing. This could be a template for many ‘machine learning’ solutions in PRT, I’ll go and see if I can tweak some things, maybe make the code shorter, or add in other indicators while I’m in quarantine :).

    • nilsla1981 • 2 days ago #

      Hi J., any progress? Greetings from Germany.Nils

  34. jmf125 • 5 days ago #

    Thank You for sharing that code Jan. One quick question any specific reason why you selected 15 as period and period2. Why these specific values ? And why not different values ?

  35. Jan • 2 days ago #

    The source of the very most of the averages is from Laurenzo, he used 15 as a standard average. https://www.prorealcode.com/prorealtime-indicators/average-filter-regression/ posted by Laurenzo in 2017

  36. Jan • 2 days ago #

    I have added the Close itself as an 71th “average”

  37. nilsla1981 • 1 day ago #

    Can I make the average lines visible in a chart? How can I see in the code what is the valid averages for buy and sell?

  38. sebastien4484 • 2 hours ago #

    Hi, if you fix MAType=45 and MATypeV2=1, on EUR/USD 15min, backtest on 100 000 units, you get a pretty good linear curve. And as the variables are all fixed, in theory it is possible to launch it in automatic trading.

avatar
Register or

Likes

avatar avatar avatar avatar avatar avatar avatar avatar avatar avatar avatar avatar avatar avatar avatar avatar

+2 more likes

Related users ' posts
raulmerino1988 Bonjour Nicolas, je voudrais vous poser une question technique sur les alarmes, mais je ne p...
Nicolas Les questions non liées à ce post doivent être posées sur les forums.
DaxRider Nice indicator thank you Nicolas
Maxime Baudin Thank you Vonasi
Vonasi An update to this indicator with some improvements and new features can now be found here: ...
Stockastiss Can this code be simply transferred into Backtestingcode so one doesnt need to use call ? (i...
swedshare You got some potential here. A couple of things I think about: 1, The opening hours in this...
phoentzs Ich habe hier mit Spread 2 gerechnet, also etwa dem Mittelwert zwischen Tag und Nacht. Das G...
phoentzs Hab festgestellt, das US500 fast noch besser funktioniert als der Dax. Was aber auch daran l...
leofi https://www.prorealcode.com/topic/simple-average-with-visual-color/
leofi Go visit www.prorealcode.com/topic/simple-average-with-visual-color/ and watch 2em post
Dritan Hi,I am new on Prorealtime and coding.I downloaded the indi but I have it on a separate wind...
efahmy Thanks Mate, Much appreciated.,
Alps007 Hi Nicolas. Happy New Year. Can you please program me several MACD divergence screeners ...
Arlei Zanin Hello Nicolas, would it be possible to convert the Cloud to Pascal language? Thank you.
Nicolas Use the color variables R and G to test if the trend is bullish (R=0) or bearish (R>0).
s00071609 Where can i find the syntax to test the colour of the line, I am calling the indicator value...
Nicolas You should open a new topic to discuss about the strategy and its coding.
Byggtrader Hi Nicolas! How do I get the indicator in the price chart? It only stays under i new chart.
Nicolas Just add it on the price chart by using the wrench on the left upper side of the chart (pric...
cedric croze a premiere vue la chaine youtube n'éxiste plus
Tradingrob Hi all, nice indicator, only i dont get the 'trendindicator' with the colorfull stripes work...
scarphace38 Bonsoir, je découvre PRT et je n'arrive pas a afficher le meme résultat pour l'indicateur de...
Vonasi Sure that is possible. I will code it and make a post in the English ProBuilder forum and pu...
Vonasi Vama v2 with Hull moving average included can be found here: https://www.prorealcode.com/top...
JMat45 Thank you, Vonasi.
Wilko Thanks for the idea! This type of scoring can really help in not only identifying regimes ...
Vonasi Thanks for the compliments Wilko.
Nicolas
7 months ago
Jan Wind "There are two methods of using Kagi: We buy when there is a turnaround and sell when there...
Nicolas Thanks, let us know how it is going?
Jan Wind Hallo Nicolas, I have tested the pre-mentioned concept, and had to change the concept : ...
Nicolas
7 months ago
LRMA
LRMA
0
Indicators
Alai-n @Vonasi Thanks
jiddan78 how to convert to afl amibroker ?
Nicolas We do not supply free coding assistance for AFL Amibroker on the website. You can ask for pa...
camporan You can use it 5M onwards, but the longer timeframe the more accurate it is. My preferred ar...
manchokcity can we have it in mql4 platform? or how or which platform do we use it?
camporan I don't use MetaTrader so I won't be able to do the translation myself. Sorry!
riz001 thnk u
geroniman bonjour Nicolas, j ai un indicateur le Tiger . J aiemrai placer des fleches buy et sell dire...
Nicolas Merci de formuler les demandes sur le forum. ça n'est pas le bon endroit et hors sujet ici ! ;)
GraHal Is there a switch to start / stop the Trailing SL / TP as when I GRAPH SL & TP neither a...
robertogozzi No GraHal, there's no topic open. It would be great if you could start one and post that lin...
GraHal Discussion Topic started here ... https://www.prorealcode.com/topic/discussion-re-auto-sy...
LucioleLucide Clean view, thanks for sharing
dertopen hi where i can found the window for candle configuration?
paolosab69 Ciao! . I have seen the pictures that explain this metod but i don't understand when is mome...

Top