Not able to code optimal periods for ma crossover strategy

hello, i am currently coding toy strategy based on ma crossover and i want to know which 2 moving average periods are most  optimal in python ? like in excel we can check the same by using offset function and then creating data table. can we do same in python using def function?

 

Yes, definitely you can create a function using the 'def' keyword that will take the long-term and short-term moving average periods as parameters. You will call the function and analyse the strategy for multiple lookback periods.



You can check out this article

Hi Divvy



As I understand you would like to test out multiple time periods for 2 moving averages and select the combination that gives the best result. 



This can definitely be done using functions in python. You can refer to how to create a function in Section 6, Unit 4 of the Python for Trading: Basics course. 



Allow me to give you a hint on how you can go about writing the code. 

Do this:

  1. Create two lists - one for short term moving average, one for long term moving average.
  2. Populate the lists as per the respective time periods you want to test.
  3. Create a function using "def" that takes these two lists as inputs.
  4. Within the function, loop each element of the short term moving average list to the long term moving average list. So if your short term averages are: [5,10,15,20]; and long term averages are: [20, 50, 100, 200]; you have to check for the following combinations - (5, 20), (5, 50), (5, 100), (5, 200), (10, 20), (10, 50).... and so on.
  5. Compare the results of each combination and choose the best one.
Do let me know if you got it working!

Thanks, 
Rishabh
 

THANK YOU RISHABH AND VIBHU FOR HELPING ME>