True, you should perform your model initialization in the Initialize method, including creating the instances of any indicators you will be using in your logic. The BacktestBegin method is intended to be used for overall initialization, and static variables are a perfect example of when this method will come in handy.
Static Variables
Static variables exist on the .NET class level, rather than the instance level, so they are available to all instances of a class. You can use static variables in your models to track meta-information during a backtest run.Consider the model below, which implements a method of determine the "edge" of a technical indicator that I discussed in my Market Glitch YouTube channel.
The model uses static variables to count the number of observations (bars) in the entire universe of data, as well as the sum of the percentage return after 5 bars, and the same for cases where the RSI indicator is oversold. It uses the BacktestBegin to initialize the static variables to zero. Then, it uses the Initialize method (which executes once for each symbol in the backtest) to process the history and add values to the static variables. By the time the Cleanup method hits, the static variables are fully loaded with values for all of the symbols in the universe.
I decided to implement the code that renders the information onto the chart in the Cleanup method rather than the BacktestComplete method. This is because Cleanup executes for every symbol in the universe, and therefore my plotted text will be visible no matter what symbol I chart. Had I coded this in the BacktestComplete, the text would only be visible if I chart the last symbol in the universe. The time to implement BacktestComplete is when you want to do something like save the summary information to a file or other persistent storage.
No comments:
Post a Comment