I'd like to continue the question since I am developing rotation strategy based on the sample code similar to the above.
There are several things really puzzled me.
1. If you write such a rotation strategy code and run on a portfolio with 10 stocks, the above code will be executed 10 times.
To test this, add the following line before the loop starts.
CODE:
Please log in to see this code.
I have to do the following to work around this and it is ugly.
CODE:
Please log in to see this code.
How to get around this in a nicer way?
2. Now the Context issue. Because the code will always select the first stock (data set) as its first default context, if the first stock has much less date/year coverage, it is really hard to get the remaining data sets data lined up from the earliest dates possible to present. I illustrate here:
S1 - First Stock. E.g. 1/1/2008 to present
S2 - 1/1/2006 to present
S3 - 1/1/2002 to present
SPY - 1/1/2001 to present (the longest dates coverage).
If you synchronize data, you will get the rest symbols starts from 1/1/2008.
If you SetContext("SPY", false);
Every time you RestoreConext(), it goes back to the context of S1. Because you need call it when But and Sell positions. The logic getting really messy. To create a dummy data set and put it as a first stock may work but not elegant.
For Rotation Strategy, it would be ideal have a way to stop auto run through the portfolio (or stop run at the first stock), and have a way to Set Default Context other than on the first stock.
For the above example, the rotation strategy can set default context on SPY (the longest coverage). The code can check at a given bar, if a symbol has data.
Let me know if you have a solution. Thanks.