Gamestudio Links
Zorro Links
Newest Posts
Blobsculptor tools and objects download here
by NeoDumont. 03/28/24 03:01
Issue with Multi-Core WFO Training
by aliswee. 03/24/24 20:20
Why Zorro supports up to 72 cores?
by Edgar_Herrera. 03/23/24 21:41
Zorro Trader GPT
by TipmyPip. 03/06/24 09:27
VSCode instead of SED
by 3run. 03/01/24 19:06
AUM Magazine
Latest Screens
The Bible Game
A psychological thriller game
SHADOW (2014)
DEAD TASTE
Who's Online Now
2 registered members (AndrewAMD, Imhotep), 567 guests, and 4 spiders.
Key: Admin, Global Mod, Mod
Newest Members
sakolin, rajesh7827, juergen_wue, NITRO_FOREVER, jack0roses
19043 Registered Users
Previous Thread
Next Thread
Print Thread
Rate Thread
Basic Options TS developed so far - Open to feedback and improvs #465142
04/04/17 23:56
04/04/17 23:56
Joined: Oct 2016
Posts: 8
R
robotekkers Offline OP
Newbie
robotekkers  Offline OP
Newbie
R

Joined: Oct 2016
Posts: 8
To pass the time until jcl posts the new 'Algorithmic Options Trading' article on the Financial Hacker, I've so far come up with this:

Code:
#include <r.h>
#include <contract.c>

void run() 
{
	BarPeriod = 1440;
	LookBack = 255; // Look back 52 weeks - a year lookback	
	//StartDate = 2013;
	//EndDate = 2016; 	// fixed simulation period	
	
	assetList("assetsIB");
	assetHistory("SPY",FROM_YAHOO|UNADJUSTED);
	asset("SPY");
	if(is(INITRUN)){
		initRQL();
		dataLoad(1,"SPY_Options.t8",9);
	}

	Multiplier = 100;
	contractUpdate("SPY",1,CALL|PUT);	
	int Type = ifelse(random() > 0,CALL,PUT);// ****
	var delta_check = 0;
	var strike_price = 0; 
	int i = 0;
	bool test;
	int maximum = 1000;
	var con_value;
	var current_IV;
	var Dividend = 0.02;
	var HistVolOV = VolatilityOV(20);
	var Interest = 0.01*yield();

	// Here, based on whether the contract we want is CALL or PUT. Aim is to find the first contract that is just under (or above) 0.3 delta
	if(Type == CALL){ // If type equals CALL - When you increase Call strike price, you reduce delta
		for(i=0; i<maximum; i++){ 
			strike_price = priceClose() + (0.1*i);
			CONTRACT* dtest = contract(CALL,30,strike_price); // Find the option from the option chain based on current strike price
			con_value = contractVal(dtest,priceClose(),HistVolOV,Dividend,Interest,&delta_check);// Find the contract value and delta of contract at strike price
			current_IV = contractVol(dtest,priceClose(),HistVolOV,con_value,Dividend,Interest);
			
			if(con_value < 0) break;	// Validaiton test - You can not have a negative contract value so breaks when fails
			else test = true; // Passes validation test - used for display purposes
			if(delta_check < 0.3) break;}} // Will show the first value that is just under 0.3 - therefore the closest possible & under!			
	
	else{ // If type equals PUT - When you increase Call strike price, you increase delta (magnitude as this has minus sign)
		for(i=0; i<maximum; i++){ 
			strike_price = priceClose() - (0.1*i);
			CONTRACT* dtest = contract(PUT,30,strike_price); // Find the option from the option chain based on current strike price
			con_value = contractVal(dtest,priceClose(),HistVolOV,Dividend,Interest,&delta_check);// Find the contract value and delta of contract at strike price
			current_IV = contractVol(dtest,priceClose(),HistVolOV,con_value,Dividend,Interest);
			
			if(con_value < 0) break;	// Validaiton test - You can not have a negative contract value
			else test = true; // Passes validation test - used for display purposes
			if(delta_check > -0.3) break;}} // Will show the first value that is just under 0.3 - therefore the closest possible & under!


	// Outside of for loop, we then use the retrieved contract to therefore calculate the Implied volatility, and then the IV Rank!
	vars IV = series(current_IV); // Store calculated IV form for loop into series Will need a lookback of a year
	
	// IV percentile calculation - adapt HH function 
	var vHH = 0.; // Set to a low value as that its sensitive at the start
	var vLL = 1; // Set to a high value as its sensitive at the start
	var IV_rank; // also known as the IV percentile 
	var count;
	var yer = 255; // 52 weeks based on Zorro reports
	
	// Here, the two for loops will look back in the past year to find the maximum and minimum IV values for the asset	
	for(count = 0; count < yer; count++) // For loop to find the highest IV calculated in the past year
	vHH = max(vHH,IV[count]);
	for(count = 0; count < yer; count++) // For loop to find the Lowest IV calculated in the past year
	vLL = min(vLL,IV[count]); // to ensure that IV is never set to 0
	
	// We do not want to calculate the IV rank (or percentile) during the lookback period!!!
	if(!is(LOOKBACK)) IV_rank =  (100 * (current_IV - vLL))/(vHH - vLL);  // Equation from http://tastytradenetwork.squarespace.com/tt/blog/implied-volatility-rank

	// Plot IV and IV rank graph
	plot("IV curve",IV[0],NEW,BLUE);
	plot("IV Rank",IV_rank,NEW,BLACK);
	PlotWidth = 600;
	PlotHeight1 = 300;
	
	// Only to enter trades that are just under 0.30 delta and equal or above 50% IV percentile
	if((between(abs(delta_check),0.25,0.3))&&(IV_rank >= 50)){ // Can do optimizing here YAY!
		static int LastExpiry = 0;
		if(ContractType && LastExpiry != ContractExpiry) {
			enterShort();
			LastExpiry = ContractExpiry;
	}}

}



The last result produced (when the lookback bug wasn't messing things up - explained below) is as shown:

Code:
option_delta_check compiling................
Error 056: No Quandl Key in Zorro.ini!
Parse HistoryFRED-DTB3.csv...
Test: option_delta_check SPY 2012..2017
Assets assetsIB 
Monte Carlo Analysis... Median AR 4%
Profit 3096$  MI 61$  DD 511$  Capital 18909$
Trades 18  Win 88.9%  Avg +172.0p  Bars 23
AR 4%  PF 9.12  SR 1.24  UI 4%  R2 0.89
Time 00:13:45



Several things to note:
- This is so far a very basic option trading system, which will enter trades that have an absolute magnitude between 0.25 and 0.3 delta. As well as this, I have also implemented an IV percentile calculator, which compares the current IV of the asset with the maximum and minimum IV of the asset in the past 365 days (or 52 weeks). Here, trades need to be in the 50% or above to also be entered (without this filter, there would be over 200 trades)

A random function decides whether the contract to SELL is a CALL or PUT, exactly the same way done in the random sell strategy in 'Algorithmic Options Trading Part 1'

Hopefully this can help some of those who are getting to grips with options trading programming, as I myself have learned a ridiculous amount, and I am very keen on learning a lot more! However for those more experienced, please feel free to suggest improvements!

- There is definitely a bug when it comes to the lookback, as shown below. A couple (or maybe all?) of you will probably notice it as well. It is on and off, on one occasion that I press [test], the script will not run, but then the next time I press [test], the script will run fine...

Code:
Different messages appear on the Zorro window, even though I did not make a single change between the two tests. 

Error 056: No Quandl Key in Zorro.ini!
Parse HistoryFRED-DTB3.csv...
Test: option_delta_check SPY 2012..2017
Assets assetsIB 
Error 037: Invalid value in plot "IV Rank" bar 255

option_delta_check compiling................
Error 056: No Quandl Key in Zorro.ini!
Parse HistoryFRED-DTB3.csv...
Test: option_delta_check SPY 2012..2017
Assets assetsIB 
Copied to Clipboard!



I did not make a single change to the code on the two occasions, however when I run the test on the first occasion, the problem occurs where the TS does not go into any trades, and the enter backtest finishes within seconds. I am certain it is to do with the Lookback, simply because I never had this problem until I included lookback in the code. The lookback is vital as it is used for the IV percentile calculator. As stated before, the second time I run the code, the backtest runs fine.

Again, I would really appreciate feedback as to what may be causing this problem.

- You will notice, I used breaks in the for loops. The reason being was that I was spending too much time playing around with while and do while loops, and neither got me anywhere. If anyone can perfect/ improve the process carried out in the CALL/PUT FOR loops, again feel free to put it forward!

- I left the bool test variable as I initially used it for validation and verification purposes, but when I remove the 3 lines of relevant code, the lookback bug seems to go crazy...

- Those are the main thing folks, so please let me know of your thoughts

Re: Basic Options TS developed so far - Open to feedback and improvs [Re: robotekkers] #465226
04/13/17 08:28
04/13/17 08:28
Joined: Dec 2016
Posts: 71
F
firecrest Offline
Junior Member
firecrest  Offline
Junior Member
F

Joined: Dec 2016
Posts: 71
Did you install Package ‘RQuantLib’?

Re: Basic Options TS developed so far - Open to feedback and improvs [Re: firecrest] #465228
04/13/17 08:46
04/13/17 08:46
Joined: Jul 2000
Posts: 27,977
Frankfurt
jcl Offline

Chief Engineer
jcl  Offline

Chief Engineer

Joined: Jul 2000
Posts: 27,977
Frankfurt
No Quandl key gets you no Quandl data for the yield function.

Re: Basic Options TS developed so far - Open to feedback and improvs [Re: jcl] #465281
04/15/17 00:18
04/15/17 00:18
Joined: Oct 2016
Posts: 8
R
robotekkers Offline OP
Newbie
robotekkers  Offline OP
Newbie
R

Joined: Oct 2016
Posts: 8
Hi firecrest, I have installed the RQuantlib package and connected it to Zorro platform via the zorro.ini file. I have been able to use the contractVal and contractVol functions mostly with no problems, except for what I discuss below.

Jcl, I completely overlooked the Quandl key! I have added the key to the zorro.ini thanks.

However, the bug remains, and I believe its to do with the CALL option contract pointer and using the contractVol function to get the implied volatility of the very same contract.

This can be seen when you change the TYPE variable in the code below between CALL and PUT. The script below creates an ATM option contract based on the TYPE variable, calculates the value of the contract (con_value) and the Implied Volatility (current_IV), and displays the values using the watch function:

Code:
// The script is not set to enter any trades, just solely to observe what is retrieved from the
// contractval and contractvol functions

#include <r.h>
#include <contract.c>

void run() 
{
	BarPeriod = 1440;
	assetList("assetsIB");
	assetHistory("SPY",FROM_YAHOO|UNADJUSTED);
	asset("SPY");
	if(is(INITRUN)){
		initRQL();
		dataLoad(1,"SPY_Options.t8",9);
	}
	
	Multiplier = 100;
	contractUpdate("SPY",1,CALL|PUT);	
	int Type = PUT; // Then change to CALL to see difference ******
	var delta_check = 0;
	var strike_price = 0; 
	var con_value;
	var current_IV;
	var Dividend = 0.02;
	var HistVolOV = VolatilityOV(20);
	var Interest = 0.01*yield();

	strike_price = priceClose();
	CONTRACT* dtest = contract(Type,30,strike_price); 
	con_value = contractVal(dtest,priceClose(),HistVolOV,Dividend,Interest,&delta_check);
	current_IV = contractVol(dtest,priceClose(),HistVolOV,con_value,Dividend,Interest);

	watch("!S_$",strike_price,"C_V",con_value,"D",delta_check,"IV",current_IV);	}



When TYPE is set to PUT, I get the following results as I continue to click step (where S_$ - strike value, C_V - contract value, D - delta, IV - Implied Vol):

Quote:

Test: call_iv SPY 2012..2017
Assets assetsIB
!S_$ 127.70 C_V 2.26712 D -0.45836 IV 0.17091
!S_$ 128.04 C_V 4.04538 D -0.54228 IV 0.21022
!S_$ 127.71 C_V 2.95047 D -0.46340 IV 0.20079
!S_$ 128.02 C_V 2.77781 D -0.50093 IV 0.17576
!S_$ 129.13 C_V 3.20197 D -0.55500 IV 0.17292
!S_$ 129.20 C_V 3.04057 D -0.55369 IV 0.16776
!S_$ 129.51 C_V 3.10393 D -0.53217 IV 0.16602
!S_$ 128.84 C_V 2.39040 D -0.45350 IV 0.16774
!S_$ 129.34 C_V 2.68262 D -0.48154 IV 0.18155
!S_$ 130.77 C_V 2.42929 D -0.45620 IV 0.17985


However, when I change the TYPE to CALL, I get the following results every time I click step

Quote:

Assets assetsIB
!S_$ 127.70 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 128.04 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 127.71 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 128.02 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 129.13 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 129.20 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 129.51 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 128.84 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 129.34 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 130.77 C_V 0.00000 D 0.00000 IV 0.00000
!S_$ 131.46 C_V 0.00000 D 0.00000 IV 0.00000



When I comment out the current_IV=contractVol... line in the script, the script will correctly display the contract value and delta values for the CALL option contracts, but displays zeroes (as shown above) when uncommented.

Hope this helps explain the problem.

Re: Basic Options TS developed so far - Open to feedback and improvs [Re: robotekkers] #465292
04/15/17 20:00
04/15/17 20:00
Joined: Oct 2016
Posts: 8
R
robotekkers Offline OP
Newbie
robotekkers  Offline OP
Newbie
R

Joined: Oct 2016
Posts: 8
It seems to fix this problem, implied volatility must not be calculated in the first initial run of the simulation, as shown below

Code:
if(!is(FIRSTINITRUN)) current_IV = contractVol(dtest,priceClose(),HistVolOV,con_value,Dividend,Interest);



I do not know why the program is able to run the contractVol function fine for PUT options, but not for CALL options at the start of the simulation, but the code above fixed the problem, at least for me.

Hope this helps!

Re: Basic Options TS developed so far - Open to feedback and improvs [Re: robotekkers] #466267
06/04/17 20:56
06/04/17 20:56
Joined: Nov 2016
Posts: 66
GreenBoat Offline
Junior Member
GreenBoat  Offline
Junior Member

Joined: Nov 2016
Posts: 66
Hi robotekkers, thank you for the script!

I am trying to use the contractVal function, but obviously I am making some mistake, because it doesn't work.

So I found your script and it doesn't work too. I am trying to find out what is the problem.

I am using your code, but I deleted the yield function, because I don't have Zorro S yet.

My script:
Code:
// The script is not set to enter any trades, just solely to observe what is retrieved from the
// contractval and contractvol functions

#include <r.h>
#include <contract.c>

void run() 
{
	BarPeriod = 1440;
	assetList("assetsIB");
	assetHistory("SPY",FROM_YAHOO|UNADJUSTED);
	asset("SPY");
	
	if(is(INITRUN)){
		initRQL();
		dataLoad(1,"SPY_Options.t8",9);
	}
	
	Multiplier = 100;
	contractUpdate("SPY",1,CALL|PUT);
	int Type = PUT; // Then change to CALL to see difference
	var delta_check = 0;
	var strike_price = 0;
	var con_value;
	var current_IV;
	var Dividend = 0.02;
	var HistVolOV = VolatilityOV(20);
	var Interest = 0.01*2; // original: var Interest = 0.01*yield();

	strike_price = priceClose();
	CONTRACT* dtest = contract(Type,30,strike_price); 
	con_value = contractVal(dtest,priceClose(),HistVolOV,Dividend,Interest,&delta_check);
	if(!is(FIRSTINITRUN)) current_IV = contractVol(dtest,priceClose(),HistVolOV,con_value,Dividend,Interest);

	watch("!S_$",strike_price,"C_V",con_value,"D",delta_check,"IV",current_IV);	
}



The result is this error:
Error 111: Crash in script: contractVal()

I am not even sure, if my RQuantLib is installed properly or where might be the mistake. If you have any idea, for example how can I make sure that my RQuantLib is installed properly (test script for R works fine) or what might be the mistake, I'll be happy for any help!

Re: Basic Options TS developed so far - Open to feedback and improvs [Re: GreenBoat] #466277
06/05/17 19:11
06/05/17 19:11
Joined: Nov 2016
Posts: 66
GreenBoat Offline
Junior Member
GreenBoat  Offline
Junior Member

Joined: Nov 2016
Posts: 66
My RQuantLib wasn't installed correctly.

I had to install it this way:

Run terminal window as administrator:
C:/Program Files/R/R-3.4.0/bin/x64/Rterm.exe (run as administrator)

run these commands:
install.packages("drat")
drat::addRepo("ghrr")
install.packages("RQuantLib", type="binary")

The result in the terminal window should look somehow like this:
Code:
R> drat::addRepo("ghrr")
R> options("repos")
$repos
                          CRAN                           ghrr 
 "https://cloud.r-project.org" "https://ghrr.github.io/drat/" 

R> install.packages("RQuantLib", type="binary")
Installing package into c:/opt/R-library
(as lib is unspecified)
trying URL 'https://ghrr.github.io/drat/bin/windows/contrib/3.3/RQuantLib_0.4.3.zip'
Content type 'application/zip' length 7993848 bytes (7.6 MB)
downloaded 7.6 MB

package RQuantLib successfully unpacked and MD5 sums checked

The downloaded binary packages are in
    C:Users[redacted]AppDataLocalTempRtmpAHvBmodownloaded_packages
R>



Moderated by  Petra 

Gamestudio download | chip programmers | Zorro platform | shop | Data Protection Policy

oP group Germany GmbH | Birkenstr. 25-27 | 63549 Ronneburg / Germany | info (at) opgroup.de

Powered by UBB.threads™ PHP Forum Software 7.7.1