Timeframe Optimisation

mastermind007

Well-Known Member
#1
Hello Experts

I recently decided to explore the best suitable time frame for my AFL after I realized that the internal logic of it was heavily influenced by Timeframe.

Instead of using preset timeframes, I experimented by using a loop to explore results for all timeframes

Chart's default time is set to 1 minute

Code:
	tf = 1;
	while (tf < 1440) 
	{
		TimeFrameSet(in1Minute*tf);

		Buy = .... 
		Sell = .... 
		Short = .... 
		Cover = .... 
		TimeFrameRestore();



		// 1440 is daily, after 375 minutes, we jump straight to daily
		tf++;
		if (tf > 375)
			tf = 1440;

                 
	}
 

alroyraj

Well-Known Member
#2
Hello Experts

I recently decided to explore the best suitable time frame for my AFL after I realized that the internal logic of it was heavily influenced by Timeframe.

Instead of using preset timeframes, I experimented by using a loop to explore results for all timeframes

Chart's default time is set to 1 minute

Code:
tf = 1;
while (tf < 1440) 
{
TimeFrameSet(in1Minute*tf);

Buy = .... 
Sell = .... 
Short = .... 
Cover = .... 
TimeFrameRestore();



// 1440 is daily, after 375 minutes, we jump straight to daily
tf++;
if (tf > 375)
tf = 1440;

                 
}
Awesome idea, sometimes the graph appears clearly on an unexpected timeframe like 4min or 7 min. Good initiative.
 

mastermind007

Well-Known Member
#3
Awesome idea, sometimes the graph appears clearly on an unexpected timeframe like 4min or 7 min. Good initiative.
Results at first glance are mind boggling .... For few scrips. hits to misses ratio is more than doubled.

I am actually planning to use 2 Amibroker instances on same data on different machines to see if I am not getting some fictitious reports.
 
Last edited:

mastermind007

Well-Known Member
#4
Results at first glance are mind boggling .... For few scrips. hits to misses ratio is more than doubled.

I am actually planning to use 2 Amibroker instances on same data on different machines to see if I am not giving some fictitious reports.
The code template, that I had presented earlier, had Buy Sell variables inside the time frame compressed section. After testing it for some time, I've realized that such code structure will be valid in only few limited cases.

In most cases, a different structure, that is presented below in this post, will be needed.

BEAR IN MIND, the AFL CODE below is incomplete Exploration shell that only provides one of the way to figure out the best time frame for a given buy/sell. The approach at the moment is brute force and few posts from now, it may well be looked upon as being childish.

If you do not currently have the strategy that you wish to optimize, this thread is of no immediate use to you although you are still welcome to read and ask questions as long as they do not directly or indirectly involve someone else writing your strategy code for you for free.


Code:
	MNP_BUY = 0;
	MNP_SELL = 0;
	MNP_TOT = 0;
	TFM_BUY = 0;
	TFM_SELL = 0;
	TFM_TOT = 0;

	tf = 1;
	while (tf < 1440)
	{
		TimeFrameSet(in1Minute*tf);
		/* SET1 ... Code to generate raw signals in a given time frame ...  */
		TimeFrameRestore();

		/* ... Each compressed variable in SET1 needs to uncompressed here ... */
		///////////////////////////////////////////////////////////////////////////////
		Buy  = ... // to be computed off the normal uncompressed data
		Sell = ... // to be computed off the normal uncompressed data
		BuyPrice =  ... // to be computed off the normal uncompressed data
		SellPrice = ... // to be computed off the normal uncompressed data
		BuyMode = Flip(Buy,Sell);
		///////////////////////////////////////////////////////////////////////////////
		Short = ... // to be computed off the normal uncompressed data
		Cover = ... // to be computed off the normal uncompressed data
		ShortPrice = ... // to be computed off the normal uncompressed data
		CoverPrice = ... // to be computed off the normal uncompressed data
		SellMode = Flip(Short,Cover);
		Qty   = ...
		///////////////////////////////////////////////////////////////////////////////
		SetPositionSize(Qty, spsShares);
		SetBacktestMode(backtestRegularRawMulti);
		SetOption("MaxOpenPositions", 2);
		SetOption("PriceBoundChecking", False);
		SetOption("ReverseSignalForcesExit", False);
		SetOption("SeparateLongShortRank", True);
		SetOption("MaxOpenLong", 1);
		SetOption("MaxOpenShort", 1);
		SetOption("ActivateStopsImmediately", True);

		NP_BUY =  ... // Compute Net profit of the last closed Buy Trade and add it into earlier long trades 
		NP_SELL = ... // Compute Net profit of the last closed Sell Trade and add it into earlier short trades 

		SetOption("ExtraColumnsLocation", 1 );

		if (LastValue(NP_BUY) > MNP_BUY)
		{
			MNP_BUY = LastValue(NP_BUY);
			TFM_BUY = tf;
		}

		if (LastValue(NP_SELL) > MNP_SELL)
		{
			MNP_SELL = LastValue(NP_SELL);
			TFM_SELL = tf;
		}

		if (LastValue(NP_BUY + NP_SELL) > MNP_TOT)
		{
			MNP_TOT= LastValue(NP_BUY + NP_SELL);
			TFM_TOT = tf;
		}

		tf++;
		if (tf > 375)
			tf = 1440;
	}

	Filter = Status( "lastbarinrange" );
	AddColumn(MNP_BUY,  "LONG");
	AddColumn(TFM_BUY,  "TFM_BYU");
	AddColumn(MNP_SELL, "SHORT");
	AddColumn(TFM_SELL, "TFM_SELL" );
	AddColumn(MNP_TOT, "TOTAL");
	AddColumn(TFM_TOT, "TFM_TOT" );
MNP stands for max net profit
TFM stands for Timeframe of Max ...
 
Last edited:

mastermind007

Well-Known Member
#6
So is the end result put in a log with the optimised time period listed script-wise
Yes, that is the general idea. For now, best time frame for Long trades is separate from short to overall best. In case of conflicts, I go for the best overall.

Date column in the output, that comes by default, is largely cosmetic except if you start saving explorer data for few days and then start another meta-analysis over it.
 

alroyraj

Well-Known Member
#7
Yes, that is the general idea. For now, best time frame for Long trades is separate from short to overall best. In case of conflicts, I go for the best overall.

Date column in the output, that comes by default, is largely cosmetic except if you start saving explorer data for few days and then start another meta-analysis over it.
I have another query is it possible to calculate alpha, beta and standard deviation for a group of stocks. I usually try to group stocks into different volatility brackets. But they vary around supports resistances or if split etc. Just a reverse engineering approach to identify stocks to the ideal stock for that trading method, it is similar to what you are doing just less software intensive.
 

mastermind007

Well-Known Member
#8
I have another query is it possible to calculate alpha, beta and standard deviation for a group of stocks. I usually try to group stocks into different volatility brackets. But they vary around supports resistances or if split etc. Just a reverse engineering approach to identify stocks to the ideal stock for that trading method, it is similar to what you are doing just less software intensive.
alroyraj

If you have formula, you can certainly compute anything as long as you can drill it down to an Amibroker code.

I am not exactly a stats expert. What does this alpha, beta mean anyways? More importantly, what predictive power do they provide?

A while ago, I had taken volatility formula that is mentioned in the FOVOLT*.csv file that can downloaded on daily basis from NSE site. When I got it, it was a free download. Nowadays, I believe that it is bundled into one of the EOD subscription products.

I am able to compute the volatility with very high accuracy and only use I have for this is ability to segregate stocks based on volatility.

But what next? At least, I was unable to use the volatility results of that analysis to make any clearly evident improvements in my trading.

At certain level of abstract, I don't care one bit on how stock is classified or its sectors or its price. I just want to know how can I trade it effectively.

Here is the volatility computation code.

Code:
ar = log(C/Ref(C,-1));
sq_ar = ar * ar;

dvol = sqrt( AMA2( ar ^ 2, 0.06, 0.94 ) );
avol = dvol * sqrt(365);
 

Blackhole

Well-Known Member
#9
Hello Experts

I recently decided to explore the best suitable time frame for my AFL after I realized that the internal logic of it was heavily influenced by Timeframe.

Instead of using preset timeframes, I experimented by using a loop to explore results for all timeframes

[/CODE]
Incredible work MM! Simply awesome!

Keep up the good work.
 

alroyraj

Well-Known Member
#10
alroyraj

If you have formula, you can certainly compute anything as long as you can drill it down to an Amibroker code.

I am not exactly a stats expert. What does this alpha, beta mean anyways? More importantly, what predictive power do they provide?

A while ago, I had taken volatility formula that is mentioned in the FOVOLT*.csv file that can downloaded on daily basis from NSE site. When I got it, it was a free download. Nowadays, I believe that it is bundled into one of the EOD subscription products.

I am able to compute the volatility with very high accuracy and only use I have for this is ability to segregate stocks based on volatility.

But what next? At least, I was unable to use the volatility results of that analysis to make any clearly evident improvements in my trading.

At certain level of abstract, I don't care one bit on how stock is classified or its sectors or its price. I just want to know how can I trade it effectively.

Here is the volatility computation code.

Code:
ar = log(C/Ref(C,-1));
sq_ar = ar * ar;

dvol = sqrt( AMA2( ar ^ 2, 0.06, 0.94 ) );
avol = dvol * sqrt(365);
Hi mastermind,
There are a class of traders who play both cash and fno with the same stocks they have in demat for long term.
I know my previous broker successfully invested all his capital in lnt and then used bear and bull spreads to obtain 3 times returns.
Another trader used this for range trading intraday in tech mahindra before the split.
I normally refer business standard Saturday for the readymade ratios. Normally we get a list of liquid 200 stocks.
Alpha indicates its good for investment based on its value. Beta indicates degree of correlation with the market. Both are investment based metrics.
But low beta and high standard deviation stocks allow us to have trades even when nifty is flat. Off hand I can name strides, just dial, ceat etc
Regarding the amibroker volatility code will have to explore it. Just stating out on amibroker. So far morphed i have into a portfolio manager type.

I have observed over the years very popular volatile stocks like jp asso etc gradually lost their volatility. This is partly why strategies made for these stocks tend to lose their effectiveness.
At present I have noticed our formerly premium growth stocks like Sun pharmacy, lupin are moving more than traders favorites like Tata steel. Hence in the present scenario trying something along these lines hopefully using bracket orders for this.