Online Derivatives IQP
Section 1 Introduction to Social Perspective
With the advent of the Internet there has been a great expansion in the area of information availability. Those seeking to exploit this development have included those close to the stock market. An area once relegated to professionals, the floor-based trading exchanges have been opened to the public via electronic trading. The internet has yet again expanded freedoms to the multitudes where the few once dominated. Where the scope of freedom is enlarged: however, the scope of individual responsibility must too be broadened. With freedom for many comes risk for many. Some are leery of this quickly rising phenomenon, trading over the internet. The problem with this reality is that novices are involved now. The systems, the basic operations, the mechanics, the risk of the exchange are no longer completely understood by all the players. The question is now What should we do, if anything? Should government begin specific regulation of internet commerce? Are rules generally followed for the traditional floor based exchange applicable for the internet exchange market? Apart from regulators, those involved in the market that effect proceedings of internet exchange include facilitators, companies that offer this service. The evolution of this role will prove vital to the necessity for regulation.
All of these issues center around the availability of information and the ability to exchange it via technology that didnt exist until recently. With anything new there will always be fear. With the advent of the automobile age, no doubt there was fear and speculation centering around this new medium of travel. Questions of moral implications of those in relative seclusion in their ventures as to their train riding counterparts. Fears for the safety of those using cars were probably common. So it is with information. Though there are many advantages to travel by car, such as direct travel instead of having to travel to a station, there were other risks. First there is the initial expense of purchasing the car, which we can liken to the minimum investment required by many brokers. Also there was a risk in the infant world of car travel if the public sector would fiscally approve of auto travel by providing roads. This does not seem to be a problem with electronic trading as there is such a profit to be made in brokering. Regulations are what is pertinent. There is a safety that comes with traffic signs and lines in the road, but they also limit the risk and reward. For instance a car may be able to turn on to a street, but a traffic light may cost him precious time. Another question to raise is whether the availability of information actually helps those trading. The availability can help those who never would have been able to access the market before, like rural people that lived far from train stations. Also the information, such as on-line archived records, can help common people make predictions that only brokers could have made in the past. So the availability of information allows the public to be educated, but this may not help them in their trades. It is said that the best brokers can make little more than those who select their stocks by throwing darts at a newspaper. Perhaps this project that takes advantage of this new availability of information and makes use of modeling techniques allowing common people to make educated purchases, well be able to discover how the degree to which the information allows them to improve their trading ability.
Section 2 Electronic Tradings Presence:
Electronic trading is a quickly growing market. The traditional floor-based trading system is losing ground to the internet which allows those in the remotest of locations to participate in trading stocks, securities, and derivatives. Some are reluctant to see this tip of the scales in the marketplace to what seems like will inevitably be a completely electronic market. Judge Stanley Sporkin, a former division director at the Securities and Exchange Commission, recently said The New York Stock Exchange has been with us for a long time. It should not be tossed in the trash heap and replaced by a black box. Though such statements may sting the ear at first as something grandpa might say about the merits of the good old days, there may be some merit to his thought. Sporkin is not opposed to progress, he continued with a caution. It would be a mistake to start from scratch. With new electronic exchanges springing up over night and frequently merging it is hard to imagine that all of these systems have the integrity of the time-tested floor-based system. Sporkin champions proper testing of these trading systems before they are opened to the masses. Though not a proponent of extremely tight regulatory measures it is clear that those like Sporkin would hope to retain some of the wisdom that has been garnered from decades of floor-based trading in the coming complete conversion to electronic trade.(sporkin nov12 wsj)
Section 3 Regulation and its Roll:
Regulation is always a controversial issue. With names like free trade and free market there will always be those that oppose all regulation. In regard to electronic trading, there is no significant historical data to aid regulators, yet there is such a dramatic increase in participants that there seems to be a need to regulate as a public service. Many exchanges have rules that apply across the boards. James Newsome, a commissioner with the Commodity Futures Trading Commission, made some statements recently on this issue. It has become apparent to me that the umbrella approach of regulating all markets the same is antiquated. Markets have changed, competition has changed, and regulatory needs have changed. We must develop a system that recognizes levels of sophistication, levels of need, risk of manipulation, and regulate accordingly."
Though he is in favor of specifying explicitly the regulations which will apply to more specifically categorized trades, these statements were made in a plea to deregulate. It seems that blanket rules which have been used in the past are not altogether purposeful. Regulation of new markets is still a new art. Newsome admitted that better mechanisms still need to be developed to properly oversee electronic trading systems. (newso wsj 11)
Section 4 Justifications for Regulations:
Reasons for regulation are quite varied. One reason is that with easy access to trades and immediacy of results attracts those that want to make a lot of money fast. These people include inexperienced traders and other traders, sometimes professionals, that expose themselves to high risk trades because of the chance of winning their bet. Some companies, like Harbor Securities, specialize in this area. Their company basically consists of 300 day-traders. Investors sign their assets over the their day-traders to invest. Although some investments can be profitable, Harbor has been on a downward drop recently. On one day a single trader lost six hundred thousand dollars on a bad purchase. With losses of about three million dollars this year, Harbor has ceased operation. It is for the protection of their customers that regulation may benefit. In the case of Harbors losses, none of their investments in their firm were covered by Securities Investor Protection Corporation, the safety net covering losses of customers of broker-dealers that go out of business. The investments which they took in had a minimum value of twenty-five thousand dollars. This loss of investors money that one would expect to be in a more diversified combination of trades makes one question the advantage of hiring a firm like Harbor Securities to handle their money. Although the customers knew this was a high risk investment, they couldnt have been aware that a single trade could damage their standing in such a way. This case could be compared to the Orange County case where money in the public sector was invested at a high risk. Traditionally government has been known for its low risk/low reward investment, and this case only went to undermine the publics trust in government even more than it had already been damaged. (one traders loss wsj nov 19)
Another market that seems to be the growing target of regulators are the internet sites that seem to encourage day-trading. Many sites recommend even encourage the rewards of day trading. Though these advertisements are not illegal, it is difficult to ascertain if all of their claims are valid. Some opponents of day-trading will resort to trying to catch these companies with the closest eyes to assure the public that these companies are not breaking already present rules: advertisement infractions and illegal touting. (burns wsj 10.25.99)
Sporkins aforementioned hesitancy towards complete electronic markets brings other risk factors to the fore. One of his main concerns was of overconfidence in new technologies that have yet to be tested in earnest. Nasdaq had an outage recently. They couldnt post correct prices, and since it fell at the end of the trading day, closing prices were off. Nasdaq, being a major stock market, affected many people and the results were obvious. Fortunately the outage only lasted nineteen minutes. Smaller off-market exchanges would seem to be more likely victims of technology failures as they have presumably less resources to safeguard against these pitfalls. Perhaps Sporkins plea for careful conversion to electronic exchange will be heard.
Section 5 Volatility:
Our use of the Black model involves the closing prices of consecutive days in the calculation of volatility. Specifically, the standard deviation of the log of the ratios of the daily closing price to the previous days closing price on the S&P 500 mini is used to estimate market volatility. Volatility is a measure of the variability of the market. Here we have defined the intervals between observations in calculating volatility to be the time between closing times. In the Black model, this standard deviation value affects the weighting applied to the stock price and the present value of the stock price. The relationship between these adjustments is negative. The volatility thus effects the predicted options price of the model.
Section 6 Assumptions in Volatility Calculation
Recently, this standard use of closing times to calculate volatility has been challenged. As information availability has been expanded through electronic media, researchers, traders, and those in academia have gained the ability to reasonably expect current prices to be made known. With this expectation and resources that allow for easy access to these prices, observations can be made much more readily than everyday. The interval between price searches in this project was ten minutes. The discrepancy between observation interval and volatility calculation interval is what raises eyebrows. The calculation would not be compatible with current equations for daily observation. With intra-day observations, differences in price could be assumed to be smaller and this would certainly effect the ratios described in our definition of volatility.
Section 7 Why Derivatives are Feared
The derivatives market has gained the reputation of being a high risk and difficult area to exist in recent times. In the wake of a day traders multiple murders and eventual suicide, the seriousness of implications to society are not to be ignored. Also, the Orange County incident of 1994 with a loss of 1.6 billion dollars eventually bankrupting a county because of options purchasing gone awry would indicate that managing a portfolio including derivatives is not a simple task. In Orange County, the treasurer of the city, presumably a financially savvy individual, could not effectively operate in nearly a satisfactory manner. Several attempts at developing regulation specific to this area have been suggested. While regulation is championed by some, others insist that the free market will turn out order in a survival of the fittest mode. While derivatives are not a new financial concept, participation in their trade has been elevated in recent years because of information availability and electronic trading. This makes the subject of addressing societal risk and control of the options market even more pressing because of the myriad that are effected.
Section 8 Regulators Stirred to Action by Disasters:
Turning again to Orange County, we should observe the actual dilemma that faces us. At Orange County, the treasurer, Bob Citron, invested in government securities. He bought 5 year notes that were government sponsored. His portfolio banked on interest rates being low. This was a big bet. Although his track record shows that he averaged better returns than the state of California in his investment pool by two percent, the erratic nature of the returns was not suitable for government spending and planning. (?? Is this true?? See http://www.gsm.uci.edu/~jorion/oc/track.gif ?? . if this is true, then this is not a case of derivatives being risky, but expectations and spending that went along with these expectations being in err in fact if they sold off a bit later they could have gotten back up to 1.4 billion of it)
Section 9 Truths of Derivatives
Although in reaction to such public disasters as these, regulators are being heard, derivatives are not nearly as complex as one would imagine. Most derivatives available for trade are can be described as swaps, forwards, futures, or options or combinations of these. These taken individually are fairly simple to understand. The amount of risk involved is the contract price. If the derivative contract expires, the right to do what ever was entailed is waived along with the purchase price. When purchasing more than one contract and hedging against losses, potential risks and rewards can be more difficult to foresee. As in anything the more complex the strategy, the more likely one is to overlook a flaw in logic thus increasing hidden risk.
Another crowd that isnt necessarily out for regulation simply calls all derivatives purchasing gambling. Especially recently as novices have entered the options market through electronic trade the practice has been viewed as mere speculation. While true gambling has increased as on-line access has broadened the audience that finds a legal means to participate, so have all sorts of trading from stocks to commodities to collectible plates. It is not because the activities are related that they have seen similar, but because the actual markets for both have been broadened. Opening the market to a whole new group of participants can be likened to deregulation. As regulation or control of telephone long distance service limited the companies involved, so did the lack of direct access to the market before electronic means. Another parallel to be drawn is the subsequent increase in volatility when the constraints were discontinued. This increased volatility (need to research actual volatility history in these highly traded derivatives) may be a reason for the appearance of such investments looking more like wagers.
While using derivatives as part of a portfolio does not necessarily make an investor a gambler or add unparalleled risk it certainly does not go unnoticed. Some would say that individual investors have no reason to trade derivatives. They establish that only large banks can make affective use of them for hedging purposes. While it is more likely that a large bank would make affective use of derivatives in hedging, small investors can benefit as well. When used properly, financial derivatives can help organizations to meet their risk-management objectives so that funds are available for making worthwhile investments. Again, a firm's decision to use derivatives should be driven by a risk-management strategy that is based on broader corporate objectives. (myth 5 http://www.cato.org/pubs/pas/pa-283.html ) Private investors may not have a developed scheme or strategy that allows for appropriate use of derivatives. Exclusive trading of derivatives make for unnecessary risk. Although firms use derivatives to assure themselves that risk is controlled in existing investments, they can also be used in a more proactive way. Using derivatives to guard against potential risk allows companies to make bolder moves toward productive ends.
It is clear that involving ones assets with derivatives does not come without some risk. It is also clear that the degree to which this risk is realised depends on many issues. Among these issues would be the size of the portfolio versus the potential losses. Another is the overall strategy of investment and the appropriateness of derivative purchases. There is risk, but to what degree if any is regulations called for? Does the amount of knowledge one has about the derivatives market affect risk? (i.e. Is there less risk for the professionals?) Should such findings be considered as valuable information by regulators?
Section 10 Methodology
10.1 Technologies We Used
The process of collecting data off of the web and later using it is a three-stage process. First we must pull the data down off of the web. Next we must store it into some database format. And finally we must retrieve and use that data.
To retrieve the data from the web, we are using a couple of programs written in C. These programs run on Unix servers and are scheduled by a standard Cron daemon. These programs use the GNU (www.gnu.org)Wget facilities written by Hrvoje Niksic to retrieve the web pages. Once the web page is retrieved, each one must be separately parsed. This parsing is specific to a web page, and therefore a different C routine is used for each. This has the unfortunate side effect that if the format of the web page changes, our C programs will need to be modified to accept the new format. The parsing is done using standard C functions to open the html files and go through them. When the web pages are retrieved the text-source of them must be gone through. This text is the html source of the web pages that you and I view through a web browser every day. These text files contain far more useless information than relevant data, this is where the C routines come into play. They take a html source file and extract the data from it. A sample of one of these source files can be seen below.
<HTML>
<HEAD>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<TITLE>Federal Reserve Statistical Release H.15 - Daily Update</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF">
<BASE TARGET="_top">
<A HREF="/Releases/"><IMG SRC="../H15.gif" ALT="H.15 - Daily Updates" WIDTH="56$
<BR CLEAR=ALL>
<FONT SIZE=+1><I>Release Date: October 7, 1999</I></FONT><BR>
The C routines must understand the format of HTML and be able to identify and extract the correct information.
The Cron daemon is a program which runs on Unix machines. It is used as a scheduler for many system maintenance functions, we were able to use it to schedule the data collection programs to run periodically. The interest program runs at 12:29:00am every day to collect the interest rates, and the futures and options programs run every ten minutes to collect the futures/options data.
WGet is part of the GNU set of programs. This is a utility for retrieving files over the internet. It is capable of a wide variety of options, and can download files from both http and ftp sites. We were able to call this utility from inside out C programs to retrieve the html files from the CME web site.
A database is a collection of tables and the attributes of those tables. A table is a collection of formatted data. The table has a structure that is set when the table is created. This structure then does not change. The structure consists of the fields that make up the table. Each field is given a name and a type. Each database format has different rules for naming fields. Each database also has various types of fields that can be used. Some common types of fields include Integer, String, Floating Point, Date, and boolean fields. The size of each field is also set at the creation of the table. The data of tables is organized into rows. These rows have one entry for each of the various fields in the table.
The storage of the data is accomplished by utilizing a mySql database server. This database server was chosen on it's availability, and it's power over other technologies. The server is running on bert.wpi.edu, another Unix server on the WPI campus run by the campus CCC department. There were several other options available to us for data storage, these included DBase, MS Access, MS Excel, flat text files, and PERL dbd. MS Access and MS Excel do not offer open standards, so talking to them from anything other than Microsoft programming languages is impossible. Flat text files are great for being able to edit by hand, but they lack much of the relational properties of a modern database. The mySql database server can be accessed through both C and PERL, yet another requirement of our system.
MySql is a database server written by T.c.X. It is a full featured SQL server and supports most of the SQL standard. SQL, or Standard Query Language, is a language that defines how query's should be sent to the database server. A query can be anything from selecting rows from a table or inserting rows to a table, to deleting an entire database. A sample query is as follows:
select * from Interest
This query would select all (*) of the fields from the "Interest" table. This result set in itself does not have a visual representation, but many programs represent the data in a visual form such as this:
|
Date |
Rate |
|
19991005112646 19991008002901 19991007002912 19991006095016 |
4.88000 4.81000 4.86000 4.87000 |
As you can see, the Interest table has two fields in it, date and rate. For our purposes the date field is in Julian format (yyyymmddhhmmss). As you can see, there is one entry for each date from 10/5/99 to 10/8/99. Unfortunately you can not be assured of the sort order in a query like this. Therefore we should include the order that we want the data to be sorted in the query.
select * from Interest order by date
|
Date |
Rate |
|
19991005112646 19991006095016 19991007002912 19991008002901 |
4.88 4.87 4.86 4.81 |
And now the data make a bit more sense. You can see the downward trend in the interest rates.
We have quite a few tables. You can view the complete listing of those tables in appendix 2.
Data sitting in a database is nice, but rather useless without some tools to manipulate that data. Originally we were going to write these tools in Microsoft Visual Basic due to it's rapid development properties. We found Visual Basic to be too restrictive, and slow. Also, each client computer would have required the mySql database drivers to be installed on it. This would have seriously impacted who could use the system. When then switched to Borland's Delphi for the strong database connectivity, but we still had the issue of database drivers on the client side. We then finally decided on PERL, the Practical Extraction and Report Language, this enabled us to make the entire system available online. By making the system completely web based, more people could use it, and there is no setup on the client computer. PERL was a logical choice because of the fast development and the world wide acceptance of PERL as a language to write internet applications in. The listing of the PERL programs may be found in appendix 2.
Section 10.2 Data Collection
Several pieces of data are necessary for this project. Luckily, we were able to find all of this information on various web sites. We constructed several C programs that were capable of retrieving this information, and then storing it in the database.
We were able to get the Futures and Options pricing from the CME web site. The interest rate information was gathered from the federal reserve web site. The specific web pages can be found here:
|
Information Gained |
Web Page |
|
Futures Pricing Options Pricing Interest Rate |
http://www.cme.com/cgi-bin/prices.cgi?prices/g_es.html http://www.cme.com/cgi-bin/prices.cgi?prices/g_ez.html http://www.bog.frb.fed.us/releases/h15/update/ |
Section 10.3 The Web Site
The bulk of the project consisted in the set up and running of the web site. The site was a simulation of trading Futures on Options of the S&P500 E-Mini. You can read complete details about these contracts at the CME website. These contracts are equivalent to the contracts on the S&P 500, but at only a fraction of the price. This way, the smaller trader can afford to trade. We chose these contracts both for the availability of data, and that data was at a reasonable frequency.
Our site required users to create an account with a minimal amount of user information. The user could create an account through an interface on the site. A screen shot of this interface can bee seen in appendix 3 as figure 1. This information was also stored in the SQL database.
Once the user had an account, they could log into the system. The login would consist of a username and a password that the user had previously entered. The user would be brought to a page containing all the current news of the site. This included announcements on new features, bug fixes, etc. The user could then proceed to the main page.
The main page listed the users' current funds, their current contract holdings, and listed a transaction log of their past transactions. The only data stored in the sql database was the transactions, so the current holdings and funds were calculated from these. See Figure 2 in appendix 3 for a sample screen shot. From here, the user can access all of the different functions of the site. The user may Buy contracts, Sell Contracts, model Contracts, and get info on Contracts.
To Buy a contract, the user would click on the Buy link. They would then be presented with a listing of available contracts (Figure 3, appendix 3). This list is generated from the data collected earlier. The user can select one or more contracts, and then click the buy button. The user is then shown a web page that queries the user how many of each site they wish to purchase (Figure 4, appendix 3). Then, assuming the user has enough funds available, those contracts are add to his holdings. The users were not charged any kind of a transaction fee. We decided this because of the wide variety of brokers and pricing for trading.
The sell function is very similar to buying. The user is presented with a list of contracts to sell. This list comes from his current holdings. Then the user is queried for the quantity to sell. Once the user selects how many, the transaction is completed.
When a user chooses to get info on a contract, they are presented with a listing of useful information on that contract. These include things like expiration date, current trading price, and the trading price of the underlying asset.
The model is by far the most complex function the user could select. This function allows a user to perform a Black model on the contract. The black model is a specialization of the Black-Scholes model for pricing options. This model predicts the theoretical price of a call option. The model can be seen in equation form as:
![]()
where:

![]()
(### HANDOUT? P. 563)
Pf = the price of the underlying Future
r = the risk free rate.
T = time to expiration in years.
K = the option exercise price
N(X) = The normal distribution of X
O = the Standard deviation of the returns of the underlying asset
We made several assumptions in the model. The first is that the risk free rate is the same as the 90 Day Treasury Bills. We also assumed that the price of the contract is simply the last price that we were able to retrieve. We took the last (closing) price from each day to calculate the standard deviation. We also tried using the average trading price throughout the day, but we found the model performed better by using the closing price. In hindsight, the model performed rather well at some points, and rather poorly at others.
The model itself also makes sever assumptions. These can be summarized as:
Asset price corresponds to the lognormal model
There are no transaction costs or taxes
There are no dividends during the option's life
There are no riskless arbitrage opportunities
Security trading is continuous
Investors can borrow or lend at the same risk free rate of interest
The short term risk free rate is constant
(Hull P. 237)
If the model was perfect, it could be used exclusively to determine when to buy and when to sell. Unfortunately, the model is not perfect. The further away the strike price is from the actual price, the less accurate the model. Likewise, the further away the expiration, the less accurate the model. There is a certain amount of trader bias towards or against certain options that affect the price which the model can not take into account. The students who participated in the project only ran the Black model 276 times. This suggests that they either viewed the model as not being very important, or perhaps they simply did not understand what it was telling them.
Section 10.4 Class Participation
Once the web site was set up, the obvious problem is trying to get people to use it. This was easily remedied by professor Wilkens who generously decided to award up to 5 bonus points in her MG502 class for people who participated. One point was given for simply participating, and the other four would be earned depending on how well you did relative to the rest of the class. Forty six of her students participated. We recorded the complete trading history of each student, the pricing of each option, and the prices of the futures. With all of this information, the holdings, cash value of those holdings, and the amount of cash could be calculated for any point in time for each student.
Each student was given $10000.00 in trading power on the system. The students made a total of 584 trades. Some made significant amounts of money, some lost significant amounts of money, and most hovered around the starting point.
Section 10.5 Extraction of Results
After the cut off date of the last trading day, the results were tallied. The PERL script that was used to do this can be found in appendix 2. The format in which the data was stored made it possible to select any arbitrary time slice and display the results for that time slice. We decided to split the trading period into two equal length halves before the results were known as to not bias our results. We then attempted to determine if the students did better after having learned more about option pricing theory.
Section 11 Results
Setting out on this project we hoped to prove that there was a
positive correlation between knowledge of derivatives trading and the performance
of the derivatives trader. We ran our simulation for several weeks, split the time into two, and compared the two results for each student. You can see the complete numbers in appendix 4.
Some students gained a lot, some students lost a lot, but most were grouped in the middle, either gaining or losing minimal amounts of money. Two of the students fell far out of the range of the normal class. In our calculations these two outliers have been removed so as not to incorrectly bias the numbers. These outliers, are, however present in appendix 4 and have been labeled as such.
Unfortunately our data did not show that the more the students knew, the better they would perform, in fact the data suggested the complete opposite. In the first period the average gain of the students was 17% of the initial funds. The second period had an average loss of 10%. Overall after the entire trading period, the students saw an average loss of about 4%. Intuition tells us that more experience shouldn't cause an investor to do worse, so we have come up with several explanations for this discrepancy.
We believe one of these explanations to be the efficiency of the market. In a completely efficient market, it should be impossible to make any money at all. This is because the prices for the contracts will be set so that at expiration, it won't be possible to make or loose any money. Obviously markets aren't prefect, because people do loose and gain money. However, it may be that the markets are so efficient, that the likelihood of gaining or loosing anything is very slim.
Another possible explanation is that it simply requires a lot more understanding of the markets then we could provide. Even very experienced traders often find it difficult to make money. Perhaps if we extended this experiment over the course of several years, we would have seem the students continuously improving.
During the first half of trading, the market continuously climbed. About half way through the trading, early in the second period, the S&P 500 dropped in value. The students had experience only with an upward trend in the market until then, and may not have had the necessary experience to know what to do in a downward slopping market. Very different strategies are required depending on what the general trend of the market is. If the market had continued the climb throughout the entire project, the students may have done better the second half.
Most brokers charge a per transaction fee, we had not such fee in our system. Since there were no transaction costs, the results of all the students were better than real world situations. The transaction fees from broker to broker vary widely. Usually, the more the fee, the more services the broker provides. There are some brokers who simply charge a yearly membership fee, and allow the members to trade as much as they like. In real life these fees can drastically impact the gains of the trader.
Section 12 Conclusions
The average person can not become a successful derivatives trader without a significant amount of knowledge and training. Our project shows that a month and a half of experience usually is not enough to produce intelligent traders.
Appendix 1 Database Table Structures
A listing of all of the mysql database tables, their fields, and the field types used in this project.
Table: Accounts
username varchar(30)
email varchar(60)
password varchar(30)
cash decimal(15,2)
sDate datetime
lDate datetime
ID int(11)
firstName varchar(30)
lastName varchar(30)
Table: Futures
datetime timestamp(14)
exp char(10)
val decimal(15,5)
ID int(11)
Table: Interest
date timestamp(14)
rate decimal(10,5)
Table: Options
datetime timestamp(14)
exp char(6)
callOption int(1)
price decimal(8,2)
last decimal(8,3)
Table: contracts
Ticker char(4)
tickDate datetime
price float(10,3)
expires datetime
Table: expiration
ID int(11)
code char(6)
expires datetime
Table: transactions
ID int(11)
contractCode varchar(20)
when timestamp(14)
qty int(11)
net decimal(14,2)
userID int(11)
Appendix 2 PERL Source Code Listing
Complete listing of CGI scripts used in the online simulation. Each script is seperated from the others with a short description explaining it's use.
#!/usr/local/bin/perl
#############################################################
# Author: Marc Hughes
# Date: 10/12/1999
# FileName: buy.cgi
# Purpose: This is the script that starts the buying process
# by prompting for the contract to buy.
#
#############################################################
use iqp;
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
$cgi = CGI::new();
$sql = &iqp::openDB();
#$q = $sql->prepare("select * from Accounts where username='$user'");
open BUY, "../Buy.html";
eval
{
%cookies = fetch CGI::Cookie;
$user = $cookies{'USERNAME'}->value;
};
if( !$user)
{
print $cgi->redirect("../login.shtml");
exit 0;
}
print $cgi->header();
&iqp::header();
$q = $sql->prepare('select exp,price,callOption,max(datetime),expiration.expires from Options join expiration where expiration.code=exp AND expiration.expires>=NOW() group by exp,callOption,price order by expiration.expires,exp,callOption,price');
#select exp,price,callOption,max(datetime) from Options group by exp,callOption,price order by exp,callOption,price
$q->execute;
@options = ();
while (@results = $q->fetchrow_array)
{
if( $results[2] == 1)
{
$code = $results[0] . ' C $' . $results[1];
}
else
{
$code = $results[0] . ' P $' . $results[1];
}
push(@options, $code);
}
#sort %options;
while( <BUY> )
{
if( /\*\*\*LIST\*\*\*/ )
{
foreach $k (@options)
{
print '<OPTION>';
print $k;
print "</OPTION>\n";
}
}
else
{
print $_;
}
}
7
#!/usr/local/bin/perl
#############################################################
# Author: Marc Hughes
# Date: 10/12/1999
# FileName: calcModel.cgi
# Purpose: This is the script that actually does the
# black-model calculations
#
#############################################################
use iqp;
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
$cgi = CGI::new();
$sql = &iqp::openDB();
$e = 2.71828182846;
%futuresPrice = ();
#$q = $sql->prepare("select * from Accounts where username='$user'");
eval
{
%cookies = fetch CGI::Cookie;
$user = $cookies{'USERNAME'}->value;
};
if( !$user)
{
print $cgi->redirect("../login.shtml");
exit 0;
}
print $cgi->header();
print "<HTML><BODY bgcolor=#FFFFFF>";
&iqp::header();
@contracts = $cgi->param("Contracts");
$interest = &iqp::getInterest($sql) / 100;
$now = int (time() / (24 * 3600) + 719523);
foreach $a (@contracts)
{
$a =~ /(.....) (.) (.*)/;
$price = $3;
$optionPrice = &iqp::calcPrice($sql,$a);
$strikeDate = &getStrike($sql,$1);
$underLying = 0;
$vol = &calcVol($sql,$a);
$t = ($strikeDate - $now) / 365.25;
$pf = &getFuturePrice($sql,$1);
#**********************
# $price = 445;
# $vol = 0.21;
# $t = .22466;
# $pf = 442.15;
# $interest = 0.033;
# With these inputs we would get $16 and change...
# ************************
print "<HR>";
print "<CENTER>$a</CENTER><BR>";
print "Current Option Price: \$$optionPrice<BR>";
print "Risk Free Rate: " . $interest . '%<BR>';
print "Current Future Price: \$$pf<BR>";
print "Strike Price: " . $price . "<BR>";
print "Days until maturity: " . ($strikeDate - $now) . " [$t years]<BR>";
print "Vol: $vol<BR>\n";
if( $2 eq 'P')
{
$price =~ s/\$//;
$q = $pf;
$pf = $price;
$price = $q;
$d1 = (log($pf / $price) + (0.5 * ($vol**2)) * $t) / ($vol * sqrt($t));
$d2 = $d1 - $vol * sqrt($t);
$m = ($pf * &calcNormal($d1) ) - ($price * &calcNormal($d2));
$P = $e**(-1 * $interest * $t) * $m;
print "Model Price: <B>\$$P</B><BR>\n";
}
else
{
$price =~ s/\$//;
$d1 = (log($pf / $price) + (0.5 * ($vol**2)) * $t) / ($vol * sqrt($t));
$d2 = $d1 - $vol * sqrt($t);
$m = ($pf * &calcNormal($d1) ) - ($price * &calcNormal($d2));
$P = $e**(-1 * $interest * $t) * $m;
print "Model Price: <B>\$$P</B><BR>\n";
}
}
print "</BODY></HTML>";
sub calcNormal
{
local $i;
local $x;
local $d = $_[0];
if ($d <-3) {return 0;}
if ($d > 3) {return 1;}
if ($d == 0){ return 0.5;}
if ($d > 0)
{
$x = 0 ;
for($i = 0.006 ; $i <= $d ; $i += 0.006)
{
$x += 0.0023983*
$e**(-1 * $i * $i/2) ;
}
$x+= 0.5;
return $x;
}
if ($d < 0)
{
$d = -1 * $d ;
$x = 0 ;
for($i = 0 ; $i <= $d ; $i += 0.006)
{
$x += 0.0023983 *
$e**(-1 * $i * $i/2) ;
}
$x = 0.5 - $x ;
return $x ;
}
0;
}
sub calcVol
{
local $contract=$_[1];
local $sql=$_[0];
local @prices, @diffs, @dev, @dev2;
$contract =~ /(.....) (.) (.*)/;
local $exp = $1;
local $avg=0, $count=0;
# local $q = $sql->prepare("select val from Futures where exp='$exp' order by datetime");
local $q = $sql->prepare("select avg(val),TO_DAYS(datetime) AS A from Futures where exp='MAR00' GROUP BY A");
$q->execute;
@prices=();
while(@results = $q->fetchrow_array)
{
push(@prices,$results[0]);
}
$oldValue=-1;
@diffs=();
foreach $x (@prices)
{
if( $oldValue > 0)
{
if( $x > 0)
{
$lop = log( $oldValue / $x);
push(@diffs, $lop);
$avg = $avg + ( $lop);
$count++;
}
}
$oldValue = $x;
}
@dev=();
if( $count==0){$count=1;}
$avg = $avg / $count;
foreach $x (@diffs)
{
push(@dev, $x - $avg);
}
@dev2 = ();
$sum=0;
foreach $x (@dev)
{
push(@dev2,$x * $x);
$sum = $sum + ($x * $x);
}
# print '<TABLE BORDER=1><TR><TD>' . $prices[0] . '</TD></TR>';
# for( $x=0;$x<$count;$x++)
# {
# print '<TR><TD>';
# print $prices[$x+1];
# print '</TD><TD>';
# print $diffs[$x];
# print '</TD><TD>';
# print $dev[$x];
# print '</TD><TD>';
# print $dev2[$x];
# print "</TD></TR>\n";
# }
# print '</TABLE>';
# print "AVG=$avg";
# print '$var = $sum / ($count-1)' . "$var = $sum / ($count-1)<BR>";
$var = 250 * ($sum / ($count-1));
$std = sqrt($var);
$std;
}
sub getFuturePrice
{
local $sql = $_[0];
local $f=$_[1];
if( $f =~ /JAN(..)/ ){$f = "MAR$1";}
if( $f =~ /FEB(..)/ ){$f = "MAR$1";}
if( $f =~ /APR(..)/ ){$f = "JUN$1";}
if( $f =~ /MAY(..)/ ){$f = "JUN$1";}
if( $f =~ /JUL(..)/ ){$f = "SEP$1";}
if( $f =~ /AUG(..)/ ){$f = "SEP$1";}
if( $f =~ /OCT(..)/ ){$f = "DEC$1";}
if( $f =~ /NOV(..)/ ){$f = "DEC$1";}
local $q = $sql->prepare("select val from Futures" .
" where exp='$f' ORDER BY datetime");
local $r=0;
if ($futuresPrice{$f}>0)
{
return $futuresPrice{$f};;
}
$q->execute;
while(@results = $q->fetchrow_array)
{
$r=$results[0];
}
$futuresPrice{$f}=$r;
$r;
}
sub getStrike
{
local $exp = $_[1];
local $sql = $_[0];
local @results;
local $q = $sql->prepare("select TO_DAYS(expires) from expiration" .
" where code='$exp'");
$q->execute;
@results = $q->fetchrow_array;
$results[0];
}
#!/usr/local/bin/perl
#############################################################
# Author: Marc Hughes
# Date: 10/12/1999
# FileName: clearcookies.cgi
# Purpose: This is just a simple script to remove any cookies
# that were set for the user.
#
#############################################################
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
$cgi = CGI::new();
$cookie1 = new CGI::Cookie(-name=>'USERNAME',-value=>"");
print $cgi->header(-cookie=>$cookie1);
print "Personal Information Cleared";
#!/usr/bin/perl
#############################################################
# Author: Marc Hughes
# Date: 10/14/1999
# FileName: completeBuy.cgi
# Purpose: This script asks for the qty of each contract
# that the user would like to buy.
#
#############################################################
use iqp;
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
$cgi = CGI::new();
$sql = &iqp::openDB();
#$q = $sql->prepare("select * from Accounts where username='$user'");
open MAIN, "../main.shtml";
eval
{
%cookies = fetch CGI::Cookie;
$user = $cookies{'USERNAME'}->value;
};
$q = $sql->prepare("select * from Accounts where username='$user'");
$q->execute;
if (@results = $q->fetchrow_array)
{
$userId = $results[6];
$cash = $results[3];
}
else
{
print $cgi->redirect("../login.shtml");
exit 0;
}
print $cgi->header();
print '<HTML><HEAD><TITLE>Buy Confirmation</TITLE></HEAD><BODY BGCOLOR=#FFFFFF>';
print "Welcome $user how many of these contracts do you wish to buy? You currently have <B>\$$cash</B>.<BR><BR>";
@contracts = $cgi->param('Contracts');
$qty = $cgi->param('Quantity');
print '<FORM action=doBuy.cgi>';
print '<TABLE WIDTH=100% BORDER=1><TR><TD>Contract Code</TD><TD>Qty To Buy</TD><TD>Cost</TD></TR>';
$x=0;
foreach $a (@contracts)
{
$x++;
print '<TR><TD>';
$p = &iqp::calcPrice($sql,$a);
print $a;
print "<INPUT TYPE=HIDDEN NAME=CODE$x VALUE=\"$a\">";
print '</TD><TD>';
print "<INPUT TYPE=TEXT NAME=QTY$x VALUE=0 SIZE=5>";
print "<INPUT TYPE=HIDDEN NAME=PRICE$x VALUE=$p>";
print '</TD><TD>';
print $p;
print '</TD></TR>';
print "\n";
}
print '</TABLE><BR>';
print '<INPUT TYPE=SUBMIT NAME="Cb1" VALUE="Submit">';
print '</FORM>';
print '</BODY></HTML>';
#!/usr/bin/perl
#############################################################
# Author: Marc Hughes
# Date: 10/12/1999
# Purpose: This script gets the qty of the contracts for the
# user to sell
#
#############################################################
use iqp;
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
$cgi = CGI::new();
$sql = &iqp::openDB();
eval
{
%cookies = fetch CGI::Cookie;
$user = $cookies{'USERNAME'}->value;
};
$q = $sql->prepare("select * from Accounts where username='$user'");
$q->execute;
if (@results = $q->fetchrow_array)
{
$userId = $results[6];
}
else
{
print $cgi->redirect("../login.shtml");
exit 0;
}
print $cgi->header();
print '<HTML><HEAD><TITLE>Sell Confirmation</TITLE></HEAD><BODY BGCOLOR=#FFFFFF>';
print "<B>Welcome $user would you like to sell these contracts?</B><BR><BR>";
@contracts = $cgi->param('contracts');
print '<FORM action=doSell.cgi>';
print '<TABLE WIDTH=100% BORDER=1><TR><TD>Contract Code</TD><TD>Qty To Sell</TD><TD>Qty You Own</TD><TD>Current Price</TD></TR>';
$x=0;
foreach $a (@contracts)
{
$p = &iqp::calcPrice($sql,$a);
$q = &iqp::getQty($sql,$userId,$a);
$x++;
print '<TR><TD>';
print $a;
print "<INPUT TYPE=HIDDEN NAME=CODE$x VALUE=\"$a\">";
print '</TD><TD>';
print "<INPUT TYPE=TEXT NAME=QTY$x VALUE=0 SIZE=5>";
print "<INPUT TYPE=HIDDEN NAME=PRICE$x VALUE=$p>";
print '</TD><TD>';
print $q;
print '</TD><TD>';
print $p;
print '</TD></TR>';
print "\n";
}
print '</TABLE><BR>';
print '<INPUT TYPE=SUBMIT NAME="Cb1" VALUE="Submit">';
print '</FORM>';
print '</BODY></HTML>';
#!/usr/local/bin/perl
#############################################################
# Author: Marc Hughes
# Date: 10/12/1999
# Purpose: This script gets the qty of the contracts for the
# user to buy
#
#############################################################
use iqp;
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
$cgi = CGI::new();
$sql = &iqp::openDB();
eval
{
%cookies = fetch CGI::Cookie;
$user = $cookies{'USERNAME'}->value;
};
$q = $sql->prepare("select * from Accounts where username='$user'");
$q->execute;
if (@results = $q->fetchrow_array)
{
$userId = $results[6];
$cash = $results[3];
}
else
{
print $cgi->redirect("../login.shtml");
exit 0;
}
print $cgi->header();
print '<HTML><BODY bgcolor=#ffffff>';
print '<BR>The following transactions have been made<BR>';
@p = $cgi->param;
print '<TABLE BORDER=1 WIDTH=75%>';
print '<TR><TD>Qty</TD><TD>Contract</TD><TD>Cost</TD></TR>';
$x=0;
foreach (@p)
{
if( /QTY(.*)/)
{
$x++;
$contract = $cgi->param('CODE' . $1);
$qty = $cgi->param($_);
$price = $cgi->param('PRICE' . $1);
$price =~ s/\$//;
if($qty > 0)
{
if($x % 2)
{
print '<TR bgcolor=#EEFFFF>';
}
else
{
print '<TR bgcolor=#FFFFEE>';
}
print "<TD>$qty</TD>";
print "<TD>$contract</TD>";
print "<TD>\$" . $price * $qty . "</TD>";
$cost =$price * $qty;
if( $cash < $cost)
{
print '<TD>You can not afford this line item.</TD>';
print '</TR>';
}
else
{
print '<TD>Bought!</TD>';
print '</TR>';
$q2=$sql->prepare("insert into transactions (contractCode,qty,net,userID)" .
" values ('$contract',$qty," . ($price * $qty * -1) .
",$userId)");
$q2->execute();
$q3=$sql->prepare("update Accounts set cash=(cash-$cost) where ".
"username='$user'");
$q3->execute;
}
}
}
}
print '</TABLE>';
print '<BR><A HREF=main.cgi?>Return to main</A>';
print '</BODY></HTML>';
#!/usr/local/bin/perl
#############################################################
# Author: Marc Hughes
# Date: 11/12/1999
# Purpose: Confirmation for the purchase of contracts
#
#
#############################################################
use iqp;
use DBI;
use CGI;
use CGI::Carp qw(fatalsToBrowser);
use CGI::Cookie;
$cgi = CGI::new();
$sql = &iqp::openDB();
eval
{
%cookies = fetch CGI::Cookie;
$user = $cookies{'USERNAME'}->value;
};
$q = $sql->prepare("select * from Accounts where username='$user'");
$q->execute;
if (@results = $q->fetchrow_array)
{
$userId = $results[6];
}
else
{
print $cgi->redirect("../login.shtml");
exit 0;
}
print $cgi->header();
print '<HTML><BODY bgcolor=#ffffff>';
print '<BR>The following transactions have been made<BR>';
@p = $cgi->param;
print '<TABLE BORDER=1 WIDTH=75%>';
print '<TR><TD>Qty</TD><TD>Contract</TD><TD>Net</TD></TR>';
$x=0;
foreach (@p)
{
if( /QTY(.*)/)
{
$x++;
$contract = $cgi->param('CODE' . $1);
$qty = $cgi->param($_);
$price = $cgi->param('PRICE' . $1);
$price =~ s/\$//;
$m = &iqp::getQty($sql,$userId,$contract);
if( $qty > $m )
{
$qty = $m;
}
if($qty > 0)
{
if($x % 2)
{
print '<TR bgcolor=#EEFFFF>';
}
else
{
print '<TR bgcolor=#FFFFEE>';
}
print "<TD>$qty</TD>";
print "<TD>$contract</TD>";
print "<TD>\$" . $price * $qty . "</TD>";
print '</TR>';
$q2=$sql->prepare("insert into transactions (contractCode,qty,net,userID)" .
" values