Sunday, November 19, 2017

Using Static Variables

In the last article we talked about the five points where you can hook into the Quantacula backtest process in your C# coded models.  We saw that the backtester first calls BacktestBegin, on the first symbol in your universe, followed by Initialize for every symbol in the universe.  You might be wondering the purpose of BeginBacktest.  Can't we just perform model initialization in the Initialize method?

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.

Summary

We saw here how static variables can be very useful in model processing, to accumulate aggregate information for all of the symbols in the universe.  Judicious use of the BacktestBegin, Initialize, and Cleanup are all you need to implement this kind of meta analysis.


No comments:

Post a Comment

Crypto Rotation Model

In a previous post I published results of an analysis I performed on oversold technical oscillators.  I ran this test on the historical dat...