How to understand and master the def functions & for loops

Course Name: Day Trading Strategies for Beginners, Section No: 11, Unit No: 21, Unit type: Notebook



Hi,



I am in the chapters where the scalping strategy is developed. The theory and concepts I understand very well thanks to the introductory videos on the subject (congratulations for the excellent material).



Unfortunately I am getting "stuck" when in the code of the strategy begin to appear definitions of functions and for loops. My Python base is not null, I understand much of the code but it is not broad enough to understand why they are made, what is the logic behind them and how to develop them.



Just looking at them is complex for me (like when I saw my first python programming class).



In all the strategies (from this and other Quantra courses) I have taken the time (and luxury) to recreate line by line the strategies in my own IDE, writing them myself and I have had no problems, but in this Scalping strategy with manual thresholds and Scalping with optimized thresholds I have had to cheat and apply "copy/paste" which leaves me with a bitter taste.



Could you give me more information, explaining the way in which the functions of these strategies are thought and developed?



Also, can you recommend any resources to learn how to develop functions and for loops applied to this field (trading)?

Hi Guillermo,



The reason for using functions in our strategy is it makes our code more reusable, Comprehensibility, and modular. We are making long_exit and short_exit functions inside the scalping_strategy function because we are going to exit positions multiple times and defining functions for this purpose makes our code modular. We also have to test our strategy on different stop-loss levels and profit ranges. We make the scalping_strategy function in which we define all our strategy logic and call this function multiple times inside a loop giving different values of stop_loss_threshold, and take_profit_threshold



Why are we using loops?

Here we have minute data with datetime index. We can use datetime index to iterate over the whole data set. Inside the scalping_strategy function, we are doing exactly that, loop helps us simulate the live trading environment because you get one datetime in each iteration of the loop like in the real world. 



If you want to learn more about python functions and the basics of python you can check this free course https://quantra.quantinsti.com/course/python-trading-basic



You can also refer to this python basic handbook

https://www.quantinsti.com/Python-Basics-Handbook.pdf