Vous êtes sur la page 1sur 104

Stata for finance students

Mehmet F. Diclea,b
a
Loyola University New Orleans, College of Business
New Orleans, LA 70118
b
Research and Teaching Associates LLC
Mandeville, LA 70448

Abstract
While MS-Excel is a default software for finance students, command line
econometrics softwares make financial analysis easier, especially for repetitive
tasks. This study presents several user written commands for Stata that are
intended for finance students. These commands and examples show how to
access various financial data as well as how to implement common statistical
and econometric methods in financial analysis.
Keywords: Financial analysis, Stata, lecture content

Email address: mfdicle@gmail.com (Mehmet F. Dicle)

Preprint submitted to Loyola University New Orleans, College of Business, Lecture ContentOctober 28, 2018

Electronic copy available at: https://ssrn.com/abstract=2318687


Contents

1 Downloading data 5
1.1 Index components . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2 Daily prices . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
1.3 Intraday prices . . . . . . . . . . . . . . . . . . . . . . . . . . 9
1.4 Option prices . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
1.5 Key statistics . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
1.6 Financial statements . . . . . . . . . . . . . . . . . . . . . . . 15
1.7 Economic data . . . . . . . . . . . . . . . . . . . . . . . . . . 19
1.8 Daily gold fixing . . . . . . . . . . . . . . . . . . . . . . . . . 22
1.9 IPOs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
1.10 Short interest . . . . . . . . . . . . . . . . . . . . . . . . . . . 26
1.11 Institutional ownership . . . . . . . . . . . . . . . . . . . . . . 28
1.12 Earnings per share . . . . . . . . . . . . . . . . . . . . . . . . 30
1.13 Insider activity . . . . . . . . . . . . . . . . . . . . . . . . . . 32
1.14 Analyst recommendations . . . . . . . . . . . . . . . . . . . . 33
1.15 Earnings dates . . . . . . . . . . . . . . . . . . . . . . . . . . 34
1.16 Economic dates . . . . . . . . . . . . . . . . . . . . . . . . . . 35
1.17 Security profiles . . . . . . . . . . . . . . . . . . . . . . . . . . 36

2 Statistical analysis 37
2.1 Descriptive statistics . . . . . . . . . . . . . . . . . . . . . . . 37
2.2 Risk and return . . . . . . . . . . . . . . . . . . . . . . . . . . 40
2.3 Distribution of daily returns . . . . . . . . . . . . . . . . . . . 41

3 Econometric analysis 42
3.1 CAPM . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.2 CAPM using GARCH . . . . . . . . . . . . . . . . . . . . . . 43
3.3 Day-of-the-week effect . . . . . . . . . . . . . . . . . . . . . . 44

4 Technical analysis 47
4.1 Moving averages . . . . . . . . . . . . . . . . . . . . . . . . . . 47
4.2 Bollinger bands . . . . . . . . . . . . . . . . . . . . . . . . . . 49
4.3 RSI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50
4.4 MACD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

Electronic copy available at: https://ssrn.com/abstract=2318687


5 Projects 52
5.1 Risk & Return . . . . . . . . . . . . . . . . . . . . . . . . . . 52
5.2 Options: Strategies . . . . . . . . . . . . . . . . . . . . . . . . 58
5.2.1 Purchased call option . . . . . . . . . . . . . . . . . . . 58
5.2.2 Purchased put option . . . . . . . . . . . . . . . . . . . 60
5.2.3 Written call option . . . . . . . . . . . . . . . . . . . . 61
5.2.4 Written put option . . . . . . . . . . . . . . . . . . . . 62
5.2.5 Covered call option . . . . . . . . . . . . . . . . . . . . 63
5.2.6 Protective put option . . . . . . . . . . . . . . . . . . . 64
5.2.7 Credit call spread . . . . . . . . . . . . . . . . . . . . . 65
5.2.8 Debit call spread . . . . . . . . . . . . . . . . . . . . . 66
5.2.9 Credit put spread . . . . . . . . . . . . . . . . . . . . . 67
5.2.10 Debit put spread . . . . . . . . . . . . . . . . . . . . . 68
5.2.11 Credit box spread . . . . . . . . . . . . . . . . . . . . . 69
5.2.12 Debit box spread . . . . . . . . . . . . . . . . . . . . . 71
5.2.13 Butterfly call spread . . . . . . . . . . . . . . . . . . . 73
5.2.14 Butterfly put spread . . . . . . . . . . . . . . . . . . . 74
5.2.15 Straddle . . . . . . . . . . . . . . . . . . . . . . . . . . 75
5.2.16 Strip . . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
5.2.17 Strap . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77
5.2.18 Strangle . . . . . . . . . . . . . . . . . . . . . . . . . . 78
5.3 Options: Premiums . . . . . . . . . . . . . . . . . . . . . . . . 79
5.4 Options: Volatility smiles . . . . . . . . . . . . . . . . . . . . 80
5.5 Portfolio comparisons . . . . . . . . . . . . . . . . . . . . . . . 82
5.5.1 Based on price to earnings ratio (P/E) . . . . . . . . . 82
5.5.2 Based on market capitalization (mcap) . . . . . . . . . 84
5.5.3 Based on price to book ratio (PtoB) . . . . . . . . . . 87

6 Portfolio Management 90
6.1 Portfolio allocation . . . . . . . . . . . . . . . . . . . . . . . . 90
6.2 Risk - return . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90
6.3 Number of shares . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.4 Latest price, total return, standard deviation of daily returns . 91
6.5 Portfolio return, portfolio standard deviation of daily returns
and CAPM Beta . . . . . . . . . . . . . . . . . . . . . . . . . 91
6.6 Portfolio weights . . . . . . . . . . . . . . . . . . . . . . . . . 92
6.7 Portfolio weighted-IV . . . . . . . . . . . . . . . . . . . . . . . 92
6.8 Portfolio charts . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Electronic copy available at: https://ssrn.com/abstract=2318687


6.8.1 Investment allocation chart . . . . . . . . . . . . . . . 93
6.8.2 Risk - return chart . . . . . . . . . . . . . . . . . . . . 94
6.8.3 Implied volatility - return chart . . . . . . . . . . . . . 95
6.8.4 Beta-return chart . . . . . . . . . . . . . . . . . . . . . 96
6.9 Portfolio measures . . . . . . . . . . . . . . . . . . . . . . . . 97
6.9.1 Treynor ratio . . . . . . . . . . . . . . . . . . . . . . . 97
6.9.2 Sharpe ratio . . . . . . . . . . . . . . . . . . . . . . . . 98
6.9.3 Correlations matrix . . . . . . . . . . . . . . . . . . . . 99
6.9.4 Covariance matrix . . . . . . . . . . . . . . . . . . . . 100

Electronic copy available at: https://ssrn.com/abstract=2318687


1. Downloading data
1.1. Index components
One of the initial steps in financial analysis is to have access to list of
symbols for financial securities. Indexes such as S&P-500 and Dow Jones
Industrial are the most common. However, there are several indexes for
general markets as well as for sectors and for countries etc. fetchcompo-
nents downloads the list of components for an index from Yahoo! Finance,
NASDAQ and investing.com (Dicle, 2013).

Install
Download the code in text format.
net install http://researchata.com/stata/010/fetchcomponents.pkg, force

Example
The following example will download the components of the Dow Jones
Composite Average.
fetchcomponents, symbol(^DJA)

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 1: Index components: fetchcomponents

Electronic copy available at: https://ssrn.com/abstract=2318687


1.2. Daily prices
End of day prices for financial securities are the most commonly used data
in financial studies. Several web sites provide this data historically including
Yahoo! Finance, Google Finance and Nasdaq. Data include daily open, low,
high, close, (dividend and split) adjusted close and volume. Historic prices
are provided -as is- and therefore extend as long as it is available at the
providing web site database. fetchyahooquotes downloads historic prices
for a list of symbols from Yahoo! Finance (Dicle and Levendis, 2011).

Install
Download the code in text format.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force

Example
The following example will download the daily historic prices and calcu-
lates log difference daily returns for AAPL.
fetchyahooquotes AAPL, freq(d) chg(ln) start(01jan2016)
twoway (line adjclose_AAPL date), scale(0.5)

Figure 2: Daily prices: fetchyahooquotes data

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 3: Daily prices: fetchyahooquotes chart

Electronic copy available at: https://ssrn.com/abstract=2318687


1.3. Intraday prices
Yahoo! Finance provides a valuable service by making one minute interval
data available for download for many financial securities up to ten trading
days. Intraday data include, for each minute, open, low, high, close, volume
and the time stamp. fetchyahooquotes downloads intraday prices from
Yahoo! Finance (as well as daily data).

Install
Download the code in text format.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force

Example
The following example will download the intraday prices for AAPL.
fetchyahooquotes AAPL, freq(1m) start(20sep2017)
* please make sure that the start option dates 10 days prior to the current date
gen obs=_n
twoway (line close obs), scale(0.5)

Figure 4: Intraday prices: fetchyahooquotes

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 5: Intraday prices: fetchyahooquotes chart

10

Electronic copy available at: https://ssrn.com/abstract=2318687


1.4. Option prices
Option prices for stocks and ETFs are provided by many web sites in-
cluding Yahoo! Finance, Google and Nasdaq. These prices are for current
date and time. They are not available historically. Prices are available for
all maturities and for all strike prices. Data include bid, ask, last, strike
price, maturity, volume, open interest and Yahoo! Finance calculated im-
plied volatility. fetchyahoooptions downloads most recent option prices
for a list of symbols from Yahoo! Finance (Dicle, 2013).

Install
Download the code in text format.
net install http://researchata.com/stata/010/fetchyahoooptions.pkg, force

Example
The following example will download the current options prices for AAPL
with maturity 02/17/2017. Please update the maturity date as there are no
historic options prices.
fetchyahoooptions AAPL, m(2018-01-19)

11

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 6: Option prices: fetchyahoooptions data

12

Electronic copy available at: https://ssrn.com/abstract=2318687


1.5. Key statistics
Several key statistics are available for securities through several web sites
including Yahoo! Finance, Google and Nasdaq. These include, but not
limited to, current P/E ratio, market capitalizations, number of shares float-
ing, dividend yield etc. Yahoo! Finance, however, provides these statistics
through an API which makes the download process easy, fast and reliable.
These statistics are available for the current period and no historic data are
available. fetchyahookeystats downloads key statistics for a list of symbols
from Yahoo! Finance API (Dicle and Levendis, 2011).

Install
Download the code in text format.
net install http://researchata.com/stata/203/fetchyahookeystats.pkg, force
* fetchyahookeystats requires sxpose package by Nicholas J. Cox, Durham University
net install http://fmwww.bc.edu/RePEc/bocode/s/sxpose.pkg, force

Example
The following example will download the key statistics for AAPL, IBM,
XOM, GOOG, FB, TWTR and HD.
fetchyahookeystats AAPL IBM XOM GOOG FB TWTR HD

Figure 7: Key statistics: fetchyahookeystats data

13

Electronic copy available at: https://ssrn.com/abstract=2318687


Example 2
The following example will download the key statistics for all S&P-500
component companies.
net install http://researchata.com/stata/010/fetchcomponents.pkg
net install http://researchata.com/stata/203/fetchyahookeystats.pkg
fetchcomponents, symbol(ˆGSPC)
levelsof Symbol, local(symbols) clean
fetchyahookeystats `symbols'
save SP500_key_stats.dta, replace

14

Electronic copy available at: https://ssrn.com/abstract=2318687


1.6. Financial statements
Financial statements including balance sheet, income statement and cash
flow statement are available for securities through several web sites including
Yahoo! Finance, Google and Nasdaq. Nasdaq.com, however, provides these
statements for the past four periods (whereas Yahoo! Finance provides them
for three periods). fetch statements downloads financial statements from
Nasdaq.com.

Install
Download the code in text format.
net install http://researchata.com/stata/048/fetch_statements.pkg, force

Example
The following example will download the annual balance sheets for AAPL.
fetch_statements AAPL, freq(A) st(BS)

15

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 8: Financial statements: fetch statements data

16

Electronic copy available at: https://ssrn.com/abstract=2318687


Example 2
The following example will download the annual balance sheets for all
Dow-Jones Industrial index components. Then, three different basic financial
ratios will be calculated.
net install http://researchata.com/stata/048/fetch_statements.pkg
* Get the list of all DJI component companies
fetchcomponents, symbol(^DJI)
levelsof Symbol, local(tickers)

* Get the Balance Sheet for all NYSE component companies


foreach aa of local tickers {
di "`aa'"
qui: {
clear
capture: fetch_statements `aa', freq(a) st(BS)
if (_N>5) {
ds
local old_var = word("`r(varlist)'",2)
rename `old_var' most_recent
keep item most_recent
gen symbol = "`aa'"
if (_rc==0) {
qui: capture: append using NYSA_statements.dta
qui: save NYSA_statements.dta, replace
}
}
}
}

* Get the Income Statement for all NYSE component companies


foreach aa of local tickers {
di "`aa'"
qui: {
clear
capture: fetch_statements `aa', freq(a) st(IS)
if (_N>5) {
ds
local old_var = word("`r(varlist)'",2)
rename `old_var' most_recent
keep item most_recent
gen symbol = "`aa'"
if (_rc==0) {
qui: capture: append using NYSA_statements.dta
qui: save NYSA_statements.dta, replace
}
}
}
}

* RATIOS: Total liabilities / total assets


use NYSA_statements.dta, clear
keep if item == "total assets" | item== "total liabilities"
replace item = "_TA" if item == "total assets"
replace item = "_TL" if item== "total liabilities"
reshape wide most_recent, i(symbol) j(item) string
gen TL_to_TA=most_recent_TL / most_recent_TA

* RATIOS: Current assets / current liabilities


use NYSA_statements.dta, clear
keep if item == "total current assets" | item== "total current liabilities"
replace item = "_TCA" if item == "total current assets"
replace item = "_TCL" if item== "total current liabilities"
reshape wide most_recent, i(symbol) j(item) string
gen TCL_to_TCA=most_recent_TCL / most_recent_TCA

* RATIOS: Cash / total assets


use NYSA_statements.dta, clear
keep if item == "total assets" | item== "cash and cash equivalents"
replace item = "_TA" if item == "total assets"
replace item = "_Cash" if item== "cash and cash equivalents"
reshape wide most_recent, i(symbol) j(item) string
gen Cash_to_TA=most_recent_Cash / most_recent_TA

17

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 9: Financial statements: fetch statements Dow-Jones Industrial index components’
balance sheets

18

Electronic copy available at: https://ssrn.com/abstract=2318687


1.7. Economic data
Federal reserve bank of St. Louis provides valuable economic data that
are extensive and historic. Data include, not limited to, inflation rates, ex-
change rates, GDP, unemployment etc. freduse downloads Federal Reserve
economic data (Drukker, 2006).

Install
Download the code in text format.
net install freduse.pkg, force

Example
The following example will download USD-EUR daily prices from the St.
Louis Federal Reserve (fred).
freduse DEXUSEU, clear
twoway(line DEXUSEU daten), scale(0.5)

19

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 10: Economic data: freduse data

20

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 11: Economic data: freduse chart

21

Electronic copy available at: https://ssrn.com/abstract=2318687


1.8. Daily gold fixing
The London Bullion Market Association has a fixing for Gold on a twice
daily basis: in the morning and in the afternoon. These fixings are avail-
able in USD and EUR. Data are historic and include both fixings in both
currencies. fetchgold downloads gold fixing data from The London Bullion
Market Association.

Install
Download the code in text format.
net install http://researchata.com/stata/029/fetchgold.pkg, force

Example
The following example will download the daily gold fixing data.
fetchgold, year(2013 2014 2015 2016) metal(gold)
twoway (line usd_am date), scale(0.5)

22

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 12: Daily gold fixing: fetchgold data

23

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 13: Daily gold fixing: fetchgold chart

24

Electronic copy available at: https://ssrn.com/abstract=2318687


1.9. IPOs
Nasdaq’s web site provide a list of historic Initial Public Offerings (IPOs).
This list contains name of the the company, symbol, IPO date and IPO price.
The list is available by months (ex. 2017-03). List of IPOs are downloaded
one month at a time. fetch IPO downloads IPO activity data from Nasdaq
web site.

Install
Download the code in text format.
net install http://researchata.com/stata/032/fetch_IPO.pkg, force

Example
The following example will download the IPO activity.
fetch_IPO, ipo_month(2017-02)

Figure 14: IPOs: fetch IPO data

25

Electronic copy available at: https://ssrn.com/abstract=2318687


1.10. Short interest
Nasdaq provides the number of shares and duration of short positions for
Nasdaq listed companies. Short interests are available for 15 day intervals for
the past 12 months. short interest downloads short interest from Nasdaq
web site.

Install
Download the code in text format.
net install http://researchata.com/stata/033/short_interest.pkg, force

Example
The following example will download the short interest for AAPL.
short_interest AAPL

26

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 15: Short interest: short interest data

27

Electronic copy available at: https://ssrn.com/abstract=2318687


1.11. Institutional ownership
Nasdaq provides the institutional ownership data for stocks. List of stocks
available is not limited to Nasdaq traded companies. Institutional ownership
data are available for the current date and no historic data are available. in-
stitutional ownership downloads institutional ownership data from Nas-
daq web site.

Install
Download the code in text format.
net install http://researchata.com/stata/034/institutional_ownership.pkg, force

Example
The following example will download the institutional ownership data for
AAPL.
institutional_ownership AAPL

28

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 16: Institutional ownership: institutional ownership data

29

Electronic copy available at: https://ssrn.com/abstract=2318687


1.12. Earnings per share
Nasdaq provides the revenue, dividends and earnings per share for stocks.
List of stocks available is not limited to Nasdaq traded companies. Historic
data are available quarterly and annually. fetch EPS downloads historic
earnings per share (EPS), dividends and revenues data from Nasdaq web
site.

Install
Download the code in text format.
net install http://researchata.com/stata/041/fetch_EPS.pkg, force

Example
The following example will download the EPS data for AAPL.
fetch_EPS AAPL

Figure 17: Earnings per share: fetch EPS data

30

Electronic copy available at: https://ssrn.com/abstract=2318687


Example 2
The following example will download the EPS data for all S&P-500 index
component companies.
net install http://researchata.com/stata/041/fetch_EPS.pkg
clear all
cd "/users/mfd/desktop"

fetchcomponents, symbol(^GSPC)
levelsof Symbol, local(symbols) clean

foreach aa in `symbols' {
di "`aa'"
fetch_EPS `aa'
gen Symbol = "`aa'"
capture: append using SP500_EPS.dta
save SP500_EPS.dta, replace
}

use SP500_EPS.dta, clear


keep if variable=="eps"
keep if quarter=="totals"
drop released

31

Electronic copy available at: https://ssrn.com/abstract=2318687


1.13. Insider activity
Nasdaq provides the insider activity (SEC, form 4) for stocks. List of
stocks available is not limited to Nasdaq traded companies. Historic data
are available up to two years although some companies seem to have it
longer/shorter. insider activity downloads insider activity from Nasdaq
web site.

Install
Download the code in text format.
net install http://researchata.com/stata/042/insider_activity.pkg, force

Example
The following example will download the insider activity for AAPL.
insider_activity AAPL

Figure 18: Insider activity: insider activity data

32

Electronic copy available at: https://ssrn.com/abstract=2318687


1.14. Analyst recommendations
Analyst recommendations are available through many web sites. How-
ever, Investrowand provide historic data. Data include analyst actions (i.e.
downgrade, upgrade etc.), previous recommendation and the new recommen-
dation. Investrowand data also include the net return since the recommen-
dation. fetch analyst downloads analyst opinions from Investrowand web
sites.

Install
Download the code in text format.
net install http://researchata.com/stata/043/fetch_analyst.pkg, force

Example
The following example will download the analyst recommendations for
AAPL.
fetch_analyst, ticker(AAPL) file(_20161121_investorwand.dta)

Figure 19: Analyst recommendations: fetch analyst data

33

Electronic copy available at: https://ssrn.com/abstract=2318687


1.15. Earnings dates
Earnings calendar is provided by Yahoo! Finance on a daily basis. Data
are provided for each calendar day historically and include company sym-
bol, expected earnings announcement time during the day and the expected
earnings per share figure. earnings dates downloads the earnings calendar
page for a given date from Yahoo! Finance.

Install
Download the code in text format.
net install http://researchata.com/stata/044/earnings_dates.pkg, force

Example
The following example will download the earnings dates data.
earnings_dates, ymd_date(20170503)

Figure 20: Earnings dates: earnings dates data

34

Electronic copy available at: https://ssrn.com/abstract=2318687


1.16. Economic dates
Economic data calendar is provided by Yahoo! Finance on a daily basis.
Data are provided for each calendar day historically and include event (data)
label, event time, related period, actual value, expectation, prior value and
revision value.
economic dates downloads the economics data calendar page for a given
date from Yahoo! Finance.

Install
Download the code in text format.
net install http://researchata.com/stata/016/economic_dates.pkg, force

Example
The following example will download the economic dates data.
economic_dates, ymd_date(20140207)

Figure 21: Economic dates: economic dates data

Example
The following example will download the economic dates for the next ten
days.
forval aa=0/10 {
clear
local _now: display %tdCCYYNNDD date("$S_DATE","DMY")+`aa'
di "`_now'"
capture: economic_dates, ymd_date(`_now')
if (_N>0) {
gen date = date("`_now'","YMD")
format %td date
capture: append using economic_events.dta
save economic_events.dta, replace
}
}

35

Electronic copy available at: https://ssrn.com/abstract=2318687


1.17. Security profiles
Profile data for stocks are provided by Yahoo! Finance. Data are current
and not available historically. profiles downloads name, address, city, state,
zip, and country for a symbol from Yahoo! Finance.

Install
Download the code in text format.
net install http://researchata.com/stata/045/profiles.pkg, force

Example
The following example will download the security profiles for AAPL, IBM,
XOM, TWTR, FB and HD.
profiles AAPL IBM XOM FB HD

Figure 22: Security profiles: profiles data

36

Electronic copy available at: https://ssrn.com/abstract=2318687


2. Statistical analysis
This section is intended to provide examples for basic statistical analysis
including descriptive statistics, risk-return chart and daily return distribu-
tions. While these are statistical properties of daily prices and returns, they
are used for financial analysis.
Download the code in text format.

2.1. Descriptive statistics


Example 1
This example shows the total return (sum), average daily return (mean),
minimum daily return (min) and maximum daily return (max) for a list of
stocks since 2015. Daily returns are natural log differences. The results are
provided as a tabular format.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes AAPL IBM XOM TWTR FB HD, freq(d) chg(ln) start(01jan2015)
tabstat ln_AAPL ln_IBM ln_XOM ln_TWTR ln_FB ln_HD, stats(sum mean min max)

Figure 23: Statistical analysis: Descriptive statistics using tabstat

37

Electronic copy available at: https://ssrn.com/abstract=2318687


Example 2
This example shows, for each year separately, the total return (sum),
average daily return (mean), minimum daily return (min) and maximum
daily return (max) for a list of stocks since 2015. Daily returns are natural
log differences. The results are provided as a tabular format.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes AAPL IBM XOM TWTR FB HD, freq(d) chg(ln) start(01jan2015)
gen year = year(date)
tabstat ln_AAPL ln_IBM ln_XOM ln_TWTR ln_FB ln_HD, stats(sum mean min max) by(year)

Figure 24: Statistical analysis: Descriptive statistics by year using tabstat

38

Electronic copy available at: https://ssrn.com/abstract=2318687


Example 3
This example show the average daily return (mean), standard deviation
of daily returns (std. dev), minimum daily return (min) and maximum daily
return (max) for a list of stocks since 2015. This example used the command
summ instead of the command used in the previous two examples, tabstat.
Daily returns are natural log differences. The results are provided as a tabular
format.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes AAPL IBM XOM TWTR FB HD, freq(d) chg(ln) start(01jan2015)
summ ln_AAPL ln_IBM ln_XOM ln_TWTR ln_FB ln_HD

Figure 25: Statistical analysis: Descriptive statistics using summ

39

Electronic copy available at: https://ssrn.com/abstract=2318687


2.2. Risk and return
This example calculates the risk and return for a list of stocks that are
components of the Dow Jones index. Risk is defined as the standard
deviation of daily returns. Return is defined as the total return for
each stock since January 1, 2016. The results are provided as a scatter
chart.
net install http://researchata.com/stata/010/fetchcomponents.pkg, force
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchcomponents, symbol(^DJI)
levelsof Symbol, local(tickers) clean
fetchyahooquotes `tickers', freq(d) chg(ln) start(01jan2016)
drop adjclose_*
reshape long ln_, i(date) j(symbol) string
collapse (sd) sd=ln_ (sum) sum=ln_, by(symbol)
replace sum = sum * 100
twoway (scatter sum sd, mlabel(symbol) mcolor(blue)), scale(.50) legend(off)

Figure 26: Statistical analysis: Risk and return chart

40

Electronic copy available at: https://ssrn.com/abstract=2318687


2.3. Distribution of daily returns
For this example, each daily return is calculated for AAPL. Then, the
number of days that fall within a return range is counted. The resulting
frequency table is referred to as the distribution of daily returns.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes AAPL, freq(d) chg(per) start(01jan2016)
histogram per_AAPL, frequency scale(.50) legend(off)

Figure 27: Statistical analysis: Distribution of daily returns chart

41

Electronic copy available at: https://ssrn.com/abstract=2318687


3. Econometric analysis
In this sections, econometric analysis of common financial models are
illustrated. Please note however these models are grossly simplified for illus-
tration purposes. For instance, for the Capital Asset Pricing Model (CAPM),
S&P-500 is used as the market which only includes stocks and ignored all
other assets. However, while grossly simplified, similar models using S&P-
500 as the market portfolio are quite common, especially at the financial
media. Also, the following models do not use risk-free interest rate for sim-
plicity purposes. The original CAPM deducts risk-free interest rate from
daily stock returns as well as from daily market returns. However, for the
period that is included in the examples, the risk-free interest rate was very
close to zero.
Download the code in text format.

3.1. CAPM
Capital Asset Pricing Model is estimated using Ordinary Least Squares
(OLS) with no adjustment for risk.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes AAPL ^GSPC, freq(d) chg(ln) start(01jan2015)
reg ln_AAPL ln__GSPC

Figure 28: Econometric analysis: Capital Asset Pricing Model OLS estimation results

42

Electronic copy available at: https://ssrn.com/abstract=2318687


3.2. CAPM using GARCH
Capital Asset Pricing Model is estimated using Generalized Autoregres-
sive Conditional Heteroskedasticity (GARCH) which controls for risk.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes AAPL ^GSPC, freq(d) chg(ln) start(01jan2015)
arch ln_AAPL ln__GSPC, arch(1) garch(1)

Figure 29: Econometric analysis: Capital Asset Pricing Model GARCH estimation results

43

Electronic copy available at: https://ssrn.com/abstract=2318687


3.3. Day-of-the-week effect
Day-of-the-week effect is one of the most common return anomalies tested
in the literature. It stems from the hypothesis that if securities compensate
investors for risk for any holding period then a weekend return should be
higher than a daily return. Thus, based on this hypothesis, it would be
expected that returns for Fridays to Mondays should be higher than any
other mid-week daily return. However, if investors expect higher returns
for the weekends they would trade such expectation to take advantage of
it. This would eliminate the higher weekend returns. Based on the efficient
market hypothesis, such profitable pattern trading should not exist. In fact,
if it exists, it would be akin to investors not taking advantage of a profitable
trading strategy. Thus, existence of day-of-the-week is considered to be an
anomaly: why would investors leave money on the table?
Dicle and Levendis (2014) argue that investors and academics study in-
dexes as well as popular stocks. This leads to less popular stocks to be left
not studied. They find no evidence of day-of-the-week effect for indexes.
However, based on evaluation of 51 markets in 33 countries, approximately
8% of 37,631 stocks present day-of-the-week effect.
The day-of-the-week effect test is quite simple. It basically evaluates
returns for each day of the week to be statistically different from each other.
For this purposes, a binary variable is assigned to each week day. However,
in order to avoid binary variable trap (a.k.a. dummy trap) in the regression,
one of the weekdays is left out (usually Wednesday). This allows each week
day’s return to be compared to the returns on Wednesdays. The Stata code
is provided below as an example.
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes AAPL, freq(d) chg(ln) start(01jan2010)

gen Monday = 0
replace Monday = 1 if dow(date)==1

gen Tuesday = 0
replace Tuesday = 1 if dow(date)==2

gen Thursday = 0
replace Thursday = 1 if dow(date)==4

gen Friday = 0
replace Friday = 1 if dow(date)==5

reg ln_AAPL Monday Tuesday Thursday Friday

44

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 30: Econometric analysis: Day-of-the-week test data

45

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 31: Econometric analysis: Day-of-the-week test estimation results

These estimation results reveal a slight, yet statistically significant at 5%


level, positive Monday effect as well as a negative Friday effect. Please note,
however, that this is a very simplistic model. In order this estimation to be
reliable, we should estimate a market model (possibly by including S&P-500
daily returns as an independent variable). Also, it would be best to estimate
this model using a GARCH(1,1) model instead of the OLS to control for
risk.

46

Electronic copy available at: https://ssrn.com/abstract=2318687


4. Technical analysis
This section is intended to provide examples for the most common tech-
nical analysis tools used in financial analysis. Dicle and Levendis (2016)
provides a Stata user written command, tftools, for four financial technical
analysis tools including moving averages, Bollinger bands, moving average
convergence divergence (MACD) and relative strength index (RSI). Each
technical analysis tool is a subcommand under tftools.
Download the code in text format.

4.1. Moving averages


The user written command tftools movingaverage calculates the mov-
ing average for a daily stock closing price. Window for the moving averaging
can be specified as well as the type of averaging (i.e. simple or exponential).
Moving standard deviation as well as moving maximum, minimum and sum
can be calculated.

Install
net install http://researchata.com/stata/210/tftools.pkg, force

net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force


fetchyahooquotes AAPL, freq(d) start(01jan2015)
gen day=_n
tsset day
tftools movingaverage, symbol(adjclose_AAPL) period(50) ma_type(sma) generate(AAPL)
tftools movingaverage, symbol(adjclose_AAPL) period(200) ma_type(sma) generate(AAPL)
twoway (line adjclose_AAPL date) (line AAPL_sma_50 date) (line AAPL_sma_200 date), scale(0.5)

47

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 32: Technical analysis: Moving averages chart

48

Electronic copy available at: https://ssrn.com/abstract=2318687


4.2. Bollinger bands
The user written command tftools bollingerbands calculates the Bollinger
bands for a daiy stock closing price. Window for the standard deviation and
simple moving averaging can be specified. tftools bollingerbands creates
three new variables: middle band, upper band and lower band.

Install
net install http://researchata.com/stata/210/tftools.pkg, force

net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force


fetchyahooquotes AAPL, freq(d) start(01jan2015)
gen day=_n
tsset day
tftools bollingerbands, symbol(adjclose_AAPL) generate(AAPL)
twoway (line adjclose_AAPL date) (line AAPL_upper_band date) (line AAPL_lower_band date), scale(0.5)

Figure 33: Technical analysis: Bollinger bands chart

49

Electronic copy available at: https://ssrn.com/abstract=2318687


4.3. RSI
The user written command tftools rsi calculates the relative strength in-
dex (RSI) for a single time-series variable. tftools rsi creates a new variable:
RSI14.

Install
net install http://researchata.com/stata/210/tftools.pkg, force

net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force


fetchyahooquotes AAPL, freq(d) start(01jan2015)
gen day=_n
tsset day
tftools rsi, symbol(adjclose_AAPL) generate(AAPL)
twoway (line AAPL_RSI date), scale(0.5)

Figure 34: Technical analysis: RSI chart

50

Electronic copy available at: https://ssrn.com/abstract=2318687


4.4. MACD
The user written command tftools macd calculates the moving average
convergence and divergence (MACD) for a single time-series variable. tftools
macd creates three new variables: MACD line, signal line and MACD histogram.

Install
net install http://researchata.com/stata/210/tftools.pkg, force

net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force


fetchyahooquotes AAPL, freq(d) start(01jan2015)
gen day=_n
tsset day
tftools macd, symbol(adjclose_AAPL) generate(AAPL)
twoway (line AAPL_MACD_line date) (line AAPL_signal_line date) (bar AAPL_MACD_histogram date), scale(0.5)

Figure 35: Technical analysis: MACD chart

51

Electronic copy available at: https://ssrn.com/abstract=2318687


5. Projects
5.1. Risk & Return
The following example is intended to demonstrate the risk and return
relationship for a spectrum of financial securities. Risk is defined as realized
(standard deviation of daily returns) and implied (implied volatility). Return
is defined as daily and earnings yield (earnings per share / price).
Download the code in text format.
Install necessary packages:
net install http://researchata.com/stata/010/fetchcomponents.pkg, force
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
net install http://researchata.com/stata/203/fetchyahookeystats.pkg, force
* fetchyahookeystats requires sxpose package by Nicholas J. Cox, Durham University
net install http://fmwww.bc.edu/RePEc/bocode/s/sxpose.pkg, force
net install http://researchata.com/stata/010/fetchyahoooptions.pkg, force

List of Dow Jones Composite Index stocks.


clear all
fetchcomponents, symbol(^DJA)
sort Symbol
levelsof Symbol, local(tickers) clean
save stocks.dta, replace

Download the daily prices and calculate the year-to-date standard deviations
as well as year-to-date total returns.
foreach stock in `tickers' {
di "`stock'"
fetchyahooquotes `stock', freq(d) chg(ln) start(01jan2017)
collapse (sum) sum_return = ln_`stock' (sd) sd_return = ln_`stock'
gen Symbol = "`stock'"
sort Symbol
merge Symbol using stocks.dta
drop _merge
sort Symbol
save stocks.dta, replace
}
order Symbol
browse

52

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 36: Risk & return: Year-to-date standard deviations and total returns

53

Electronic copy available at: https://ssrn.com/abstract=2318687


Download the options data for each stock and calculate the implied volatili-
ties.
foreach stock in `tickers' {
di "`stock'"
capture: fetchyahoooptions `stock', m(2017-09-15)
if (_N>2) {
drop if IV_Yahoo==.
drop if IV_Yahoo==0
drop if Open_Interest<5
collapse (mean) IV = IV_Yahoo
gen Symbol = "`stock'"
sort Symbol
merge Symbol using stocks.dta
drop _merge
sort Symbol
save stocks.dta, replace
}
}

Figure 37: Risk & return: Implied volatilities

54

Electronic copy available at: https://ssrn.com/abstract=2318687


Download the price to earnings ratios for each stock and calculate the earn-
ings to price ratio (earnings yield).
fetchyahookeystats `tickers', field(n s r)
gen EP_ratio = 1 / Price_to_Earnings
drop Price_to_Earnings
sort Symbol
merge Symbol using stocks.dta
drop _merge
sort Symbol
save stocks.dta, replace

Figure 38: Risk & return: EP ratios

55

Electronic copy available at: https://ssrn.com/abstract=2318687


Earnings yield vs. realized risk:
use stocks.dta, clear
gen risk_return_ratio_1 = EP_ratio / sd_return
format %6.4fc risk_return_ratio_1
gsort -risk_return_ratio_1
br Symbol Name risk_return_ratio_1
twoway (scatter EP_ratio sd_return, mlabel(Symbol)), scale(0.5)
ytitle("Return") ylabel(#20, format(%6.3fc) labsize(small))
xtitle("Risk") xlabel(#20, format(%6.3fc) labsize(small))
graph export risk_return_project4.png, replace

Figure 39: Risk & return: Earnings yield vs. realized risk

56

Electronic copy available at: https://ssrn.com/abstract=2318687


Earnings yield vs. implied volatility:
use stocks.dta, clear
gen risk_return_ratio_1 = EP_ratio / IV
format %6.4fc risk_return_ratio_1
gsort -risk_return_ratio_1
br Symbol Name risk_return_ratio_1
twoway (scatter EP_ratio sd_return, mlabel(Symbol)), scale(0.5)
ytitle("Return") ylabel(#20, format(%6.3fc) labsize(small))
xtitle("Risk") xlabel(#20, format(%6.3fc) labsize(small))
graph export risk_return_project5.png, replace

Figure 40: Risk & return: Earnings yield vs. implied volatility

57

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2. Options: Strategies
The following examples use exercise values only. Any premium values are
ignored.
Download the code in text format.

5.2.1. Purchased call option


The following example uses a call option bought on AAPL with a strike
price of $145. The prices as of April 7, 2017 ( $142.75) is simulated to
increase and decrease by slight increments. While only the exercise value is
considered for this example, an initial (never changing) premium of $1.5 is
assumed for illustration purposes.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen strike = 145
gen option_premium = 1.5
gen call_value = max(0,price-strike) - option_premium

twoway (line call_value price), title(Purchased call option value) ytitle("Call option value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "long_call.png", replace

58

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 41: Options: Purchased call option chart

59

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.2. Purchased put option
The following example uses a put option bought on AAPL with a strike
price of $140. The prices as of April 7, 2017 ( $142.75) is simulated to
increase and decrease by slight increments. While only the exercise value is
considered for this example, an initial (never changing) premium of $1.5 is
assumed for illustration purposes.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen strike = 140
gen option_premium = 1.5
gen put_value = max(0,strike-price) - option_premium

twoway (line put_value price), title(Purchased put option value) ytitle("Put option value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "long_put.png", replace

Figure 42: Options: Purchased put option chart

60

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.3. Written call option
The following example uses a call option written on AAPL with a strike
price of $145. The prices as of April 7, 2017 ( $142.75) is simulated to
increase and decrease by slight increments. While only the exercise value is
considered for this example, an initial (never changing) premium of $1.5 is
assumed for illustration purposes.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen strike = 145
gen option_premium = 1.5
gen call_value = -max(0,price-strike) + option_premium

twoway (line call_value price), title(Written call option value) ytitle("Call option value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "short_call.png", replace

Figure 43: Options: Written call option chart

61

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.4. Written put option
The following example uses a put option written on AAPL with a strike
price of $140. The prices as of April 7, 2017 ( $142.75) is simulated to
increase and decrease by slight increments. While only the exercise value is
considered for this example, an initial (never changing) premium of $1.5 is
assumed for illustration purposes.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen strike = 140
gen option_premium = 1.5
gen put_value = -max(0,strike-price) + option_premium

twoway (line put_value price), title(Written put option value) ytitle("Put option value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "short_put.png", replace

Figure 44: Options: Written put option chart

62

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.5. Covered call option
Covered call option is used to generate income when a stock is not ex-
pected to increase above a certain level. The stock may be already included
in a portfolio. It can also be purchased specifically for the covered call pur-
poses. For the following example prices, as of April 7, 2017 ( $142.75), is
simulated to increase and decrease by slight increments. While only the ex-
ercise value is considered for this example, an initial (never changing) option
premium of $1.5 is assumed for illustration purposes. Portfolio consists of
100 shares of AAPL purchased at $142.75 and one contract of call option
written on AAPL with a strike price of $150.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen strike = 150
gen option_premium = 1.5
gen call_value = -max(0,price-strike) + option_premium
gen stock_PL = price - 142.75
gen portfolio_value = stock_PL + call_value

twoway (line portfolio_value price), title(Covered call portfolio value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "covered_call.png", replace

Figure 45: Options: Covered call option chart

63

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.6. Protective put option
Protective put is used to protect against falling prices. It is considered to
be similar to an insurance. For the following example prices, as of April 7,
2017 ( $142.75), is simulated to increase and decrease by slight increments.
While only the exercise value is considered for this example, an initial (never
changing) option premium of $1.5 is assumed for illustration purposes. Port-
folio consists of 100 shares of AAPL purchased at $142.75 and one contract
of put option purchased on AAPL with a strike price of $135.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen strike = 135
gen option_premium = 1.5
gen put_value = max(0,strike-price) - option_premium
gen stock_PL = price - 142.75
gen portfolio_value = stock_PL + put_value

twoway (line portfolio_value price), title(Protective put portfolio value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "protective_put.png", replace

Figure 46: Options: Protective put option chart

64

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.7. Credit call spread
Credit call spread is used to generate income when the underlying stock is
not expected to increase above a certain level. It does not require holding the
underlying asset. It generates a small income (premium difference between
long and short options) against a potentially unlimited loss. For the following
example prices, as of April 7, 2017 ( $142.75), is simulated to increase and
decrease by slight increments. While only the exercise value is considered
for this example, an initial (never changing) option premiums are assumed:
$1.5 for lower strike and $0.75 for the higher strike prices. Strategy consists
of one contract of written call option at $145 strike price and one contract
of purchased call option at $150 strike price.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen short_strike = 145
gen long_strike = 150
gen short_option_premium = 1.5
gen long_option_premium = 0.75
gen strategy_value = -max(0,price-short_strike) + max(0,price-long_strike) + short_option_premium - long_option_premium

twoway (line strategy_value price), title(Credit call spread value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "credit_call_spread.png", replace

Figure 47: Options: Credit call spread chart

65

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.8. Debit call spread
Debit call spread is used to speculate when the price of the underlying
stock is expected to increase. It is different than buying the call option
naked as the short call option included in the debit call spread limits the
upside potential while making the strategy cheaper. It does not require
holding the underlying asset. For the following example prices, as of April 7,
2017 ( $142.75), is simulated to increase and decrease by slight increments.
While only the exercise value is considered for this example, an initial (never
changing) option premiums are assumed: $1.5 for lower strike and $0.75 for
the higher strike prices. Strategy consists of one contract of purchased call
option at $145 strike price and one contract of written call option at $150
strike price.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen short_strike = 150
gen long_strike = 145
gen short_option_premium = 0.75
gen long_option_premium = 1.50
gen strategy_value = -max(0,price-short_strike) + max(0,price-long_strike) + short_option_premium - long_option_premium

twoway (line strategy_value price), title(Debit call spread value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "debit_call_spread.png", replace

Figure 48: Options: Debit call spread chart

66

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.9. Credit put spread
Credit put spread is used to generate income when the underlying stock is
not expected to decrease below a certain level. It does not require holding the
underlying asset. It generates a small income (premium difference between
long and short options) against a potentially unlimited loss. For the following
example prices, as of April 7, 2017 ( $142.75), is simulated to increase and
decrease by slight increments. While only the exercise value is considered
for this example, an initial (never changing) option premiums are assumed:
$0.75 for lower strike and $1.5 for the higher strike prices. Strategy consists
of one contract of written put option at $140 strike price and one contract
of purchased put option at $135 strike price.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen short_strike = 140
gen long_strike = 135
gen short_option_premium = 1.5
gen long_option_premium = 0.75
gen strategy_value = -max(0,short_strike-price) + max(0,long_strike-price) + short_option_premium - long_option_premium

twoway (line strategy_value price), title(Credit put spread value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "credit_put_spread.png", replace

Figure 49: Options: Credit put spread chart

67

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.10. Debit put spread
Debit put spread is used to speculate when the price of the underlying
stock is expected to decrease. It is different than buying the put option
naked as the short put option included in the debit put spread limits the
upside potential while making the strategy cheaper. It does not require
holding the underlying asset. For the following example prices, as of April 7,
2017 ( $142.75), is simulated to increase and decrease by slight increments.
While only the exercise value is considered for this example, an initial (never
changing) option premiums are assumed: $0.75 for lower strike and $1.5 for
the higher strike prices. Strategy consists of one contract of purchased put
option at $140 strike price and one contract of written put option at $135
strike price.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1
gen short_strike = 135
gen long_strike = 140
gen short_option_premium = 0.75
gen long_option_premium = 1.5
gen strategy_value = -max(0,short_strike-price) + max(0,long_strike-price) + short_option_premium - long_option_premium

twoway (line strategy_value price), title(Debit put spread value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "debit_put_spread.png", replace

Figure 50: Options: Debit put spread chart

68

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.11. Credit box spread
Leg 1: Credit call spread
Leg 2: Credit put spread
Same strike price for both of the spreads
Same expiration date for both of the spreads

clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1

* Leg 1: Credit call spread =================


gen _1_short_strike = 140
gen _1_long_strike = 145
gen _1_short_option_premium = 4.50
gen _1_long_option_premium = 1.25
gen _1_strategy_value = -max(0,price-_1_short_strike) + max(0,price-_1_long_strike) + _1_short_option_premium
- _1_long_option_premium

* Leg 2: Credit put spread ==================


gen _2_short_strike = 145
gen _2_long_strike = 140
gen _2_short_option_premium = 4.50
gen _2_long_option_premium = 1.50
gen _2_strategy_value = -max(0,_2_short_strike-price) + max(0,_2_long_strike-price) + _2_short_option_premium
- _2_long_option_premium

gen strategy_value = _1_strategy_value + _2_strategy_value

twoway (line _1_strategy_value price) (line _2_strategy_value price) (line strategy_value price),
title(Credit box spread value) ytitle("Portfolio value") xtitle("Daily price") ylabel(#20, angle(horizontal) axis(1))
xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "credit_box_spread.png", replace

69

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 51: Options: Credit box spread

70

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.12. Debit box spread
Leg 1: Debit call spread
Leg 2: Debit put spread
Same strike price for both of the spreads
Same expiration date for both of the spreads

clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1

* Leg 1: Debit call spread =================


gen _1_short_strike = 145
gen _1_long_strike = 140
gen _1_short_option_premium = 0.75
gen _1_long_option_premium = 1.50
gen _1_strategy_value = -max(0,price-_1_short_strike) + max(0,price-_1_long_strike) + _1_short_option_premium
- _1_long_option_premium

* Leg 2: Debit put spread ==================


gen _2_short_strike = 140
gen _2_long_strike = 145
gen _2_short_option_premium = 1.00
gen _2_long_option_premium = 1.50
gen _2_strategy_value = -max(0,_2_short_strike-price) + max(0,_2_long_strike-price) + _2_short_option_premium
- _2_long_option_premium

gen strategy_value = _1_strategy_value + _2_strategy_value

twoway (line _1_strategy_value price) (line _2_strategy_value price) (line strategy_value price),
title(Debit box spread value) ytitle("Portfolio value") xtitle("Daily price") ylabel(#20, angle(horizontal) axis(1))
xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "debit_box_spread.png", replace

71

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 52: Options: Debit box spread

72

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.13. Butterfly call spread
Butterfly call spread is essentially a debit call spread. However, we will be
using even number of contracts and splitting the long calls into two different
strike prices: Klongcall < (2 × Kshortcall ) < Klongcall .

clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1

gen _1_long_strike = 140


gen _1_long_option_premium = 2.50

gen short_strike = 145


gen short_option_premium = 1.75

gen _2_long_strike = 150


gen _2_long_option_premium = 1.50

gen strategy_value = max(0,price-_1_long_strike) + max(0,price-_2_long_strike)


- (2*max(0,price-short_strike) ) + (2*short_option_premium)
- _1_long_option_premium - _2_long_option_premium

twoway (line strategy_value price), title(Butterfly call spread value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "butterfly_call_spread.png", replace

Figure 53: Options: Butterfly call spread

73

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.14. Butterfly put spread
Butterfly put spread is essentially a debit put spread. However, we will be
using even number of contracts and splitting the long puts into two different
strike prices: Klongput < (2 × Kshortput ) < Klongput .

clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1

gen _1_long_strike = 145


gen _1_long_option_premium = 2.5

gen short_strike = 140


gen short_option_premium = 1.75

gen _2_long_strike = 135


gen _2_long_option_premium = 1.25

gen strategy_value = max(0,_1_long_strike-price) + max(0,_2_long_strike-price)


- (2*max(0,short_strike-price)) + (2*short_option_premium)
- _1_long_option_premium - _2_long_option_premium

twoway (line strategy_value price), title(Butterfly put spread value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "butterfly_put_spread.png", replace

Figure 54: Options: Butterfly put spread

74

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.15. Straddle
Straddle is a simple options strategy which involves one long call and one
log put option at the same strike price.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1

gen call_strike = 145


gen call_option_premium = 1.5
gen call_value = max(0,price-call_strike) - call_option_premium

gen put_strike = 145


gen put_option_premium = 1.5
gen put_value = max(0,put_strike-price) - put_option_premium

gen strategy_value = call_value + put_value

twoway (line strategy_value price), title(Straddle value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "straddle.png", replace

Figure 55: Options: Straddle

75

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.16. Strip
Strip option strategy is essentially a bearish straddle.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1

gen call_strike = 145


gen call_option_premium = 1.5
gen call_value = max(0,price-call_strike) - call_option_premium

gen put_strike = 145


gen put_option_premium = 1.5
gen put_value = max(0,put_strike-price) - put_option_premium

gen strategy_value = call_value + (2*put_value)

twoway (line strategy_value price), title(Strip value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "strip.png", replace

Figure 56: Options: Strip

76

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.17. Strap
Strap option strategy is essentially a bullish straddle.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1

gen call_strike = 145


gen call_option_premium = 1.5
gen call_value = max(0,price-call_strike) - call_option_premium

gen put_strike = 145


gen put_option_premium = 1.5
gen put_value = max(0,put_strike-price) - put_option_premium

gen strategy_value = (2*call_value) + put_value

twoway (line strategy_value price), title(Strap value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "strap.png", replace

Figure 57: Options: Strap

77

Electronic copy available at: https://ssrn.com/abstract=2318687


5.2.18. Strangle
Strangle option strategy is essentially a straddle with out of the money
strike prices.
clear
set obs 100
gen price = 126 if _n==1
replace price = price[_n-1] + (price[_n-1] * 0.0025) if _n>1

gen call_strike = 150


gen call_option_premium = 1.25
gen call_value = max(0,price-call_strike) - call_option_premium

gen put_strike = 140


gen put_option_premium = 1.25
gen put_value = max(0,put_strike-price) - put_option_premium

gen strategy_value = call_value + put_value

twoway (line strategy_value price), title(Strangle value) ytitle("Portfolio value") xtitle("Daily price")
ylabel(#20, angle(horizontal) axis(1)) xlabel(#20, angle(vertical) format(%5.0fc)) scale(.50) legend(off)

graph export "strangle.png", replace

Figure 58: Options: Strangle

78

Electronic copy available at: https://ssrn.com/abstract=2318687


5.3. Options: Premiums
The following example will download the current options prices for AAPL
with maturity 10/20/2017. Please update the maturity date as there are no
historic options prices.
Download the code in text format.
net install http://researchata.com/stata/010/fetchyahoooptions.pkg, force
fetchyahoooptions AAPL, m(2017-10-20)

The following code will calculate the call options’ intrinsic values and
premiums.
keep if Type=="Call"
keep if Last_traded_date == date("25sep2017","DMY")
gen intrinsic = max(Price - Strike,0)
gen premium = Ask - intrinsic
twoway (line premium Strike), scale(0.5)

Figure 59: Call option premiums for AAPL for maturity date 10/20/2017

79

Electronic copy available at: https://ssrn.com/abstract=2318687


5.4. Options: Volatility smiles
The following example will download the current options prices for AAPL
with maturity 10/20/2017. Please update the maturity date as there are no
historic options prices.
Download the code in text format.
net install http://researchata.com/stata/010/fetchyahoooptions.pkg, force
fetchyahoooptions AAPL, m(2017-10-20)

The following code will calculate the average implied volatility .


keep if Type=="Call"
keep if Last_traded_date == date("25sep2017","DMY")
summ IV_Yahoo

Figure 60: Call options’ average implied volatility for AAPL for maturity date 10/20/2017

The following code will draw the volatility smile chart.


twoway (line IV_Yahoo Strike), scale(0.5)

80

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 61: Call options’ volatility smile for AAPL for maturity date 10/20/2017

81

Electronic copy available at: https://ssrn.com/abstract=2318687


5.5. Portfolio comparisons
The following examples are intended to demonstrate some of the basic
portfolio comparison techniques. These are very simplified examples. Com-
parisons are made for daily return differences between two portfolios as well
as market risk differences.

Download the code in text format.


Install necessary packages:
net install http://researchata.com/stata/010/fetchcomponents.pkg, force
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
net install http://researchata.com/stata/203/fetchyahookeystats.pkg, force
* fetchyahookeystats requires sxpose package by Nicholas J. Cox, Durham University
net install http://fmwww.bc.edu/RePEc/bocode/s/sxpose.pkg, force

List of Dow Jones Composite Index stocks.


clear all
fetchcomponents, symbol(^GSPC)
levelsof Symbol, local(tickers) clean
fetchyahookeystats `tickers'
save keystats_data.dta, replace

5.5.1. Based on price to earnings ratio (P/E)


use keystats_data.dta, clear
keep symbol shortName longName forwardPE
destring forwardPE, replace
sort forwardPE
browse

Figure 62: Top of the list (low P/E stocks)

We will be using the following stocks for our example: Low P/E companies:
CHK, NFX, DISCK, GM and GT. High P/E companies: AIV, SBAC, INCY,
AMZN and UDR.

The following code puts together the portfolios to compare.

82

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 63: Bottom of the list (high P/E stocks)

fetchyahooquotes CHK NFX DISCK GM GT AIV SBAC INCY AMZN UDR ^GSPC, freq(d) chg(ln) start(01jan2010)
gen low_PE = (ln_CHK+ ln_NFX+ ln_DISCK+ ln_GM+ ln_GT) / 5
gen hi_PE = (ln_AIV+ ln_SBAC+ ln_INCY+ ln_AMZN+ ln_UDR) / 5

The following code compares the portfolios using a t-test. This is to test
whether the daily portfolio returns are statistically different between the two
portfolios.
ttest low_PE == hi_PE

Figure 64: t-test to compare the daily returns of the two portfolios

The following code estimates the market model for the low P/E portfolio.
reg low_PE ln__GSPC

83

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 65: Market model for the low P/E portfolio

The following code estimates the market model for the high P/E portfolio.
reg hi_PE ln__GSPC

Figure 66: Market model for the high P/E portfolio

5.5.2. Based on market capitalization (mcap)


use keystats_data.dta, clear
keep symbol shortName longName marketCap
destring marketCap, replace
sort marketCap
browse

84

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 67: Top of the list (low mcap stocks)

Figure 68: Bottom of the list (high mcap stocks)

We will be using the following stocks for our example: Low mcap companies:
PDCO, SIG, CHK, NAVI and RRC. High mcap companies: MSFT, JPM,
FB, AMZN and AAPL.

The following code puts together the portfolios to compare.


fetchyahooquotes PDCO SIG CHK NAVI RRC MSFT JPM FB AMZN AAPL ^GSPC, freq(d) chg(ln) start(01jan2010)
gen low_MCap = (ln_PDCO+ ln_SIG+ ln_CHK+ ln_NAVI+ ln_RRC) / 5
gen hi_MCap = (ln_MSFT+ ln_JPM+ ln_FB+ ln_AMZN+ ln_AAPL) / 5

The following code compares the portfolios using a t-test. This is to test
whether the daily portfolio returns are statistically different between the two
portfolios.
ttest low_MCap == hi_MCap

85

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 69: t-test to compare the daily returns of the two portfolios

The following code estimates the market model for the low mcap portfolio.
reg low_MCap ln__GSPC

Figure 70: Market model for the low mcap portfolio

The following code estimates the market model for the high mcap portfolio.
reg hi_MCap ln__GSPC

86

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 71: Market model for the high mcap portfolio

5.5.3. Based on price to book ratio (PtoB)


use keystats_data.dta, clear
keep symbol shortName longName priceToBook
destring priceToBook, replace
sort priceToBook
browse

Figure 72: Top of the list (low PtoB stocks)

We will be using the following stocks for our example: Low PtoB companies:
IDXX, MAS, LMT, ADSK and MCO. High PtoB companies: KMB, SPGI,
UPS, HD and BA.

The following code puts together the portfolios to compare.


fetchyahooquotes IDXX MAS LMT ADSK MCO KMB SPGI UPS HD BA ^GSPC, freq(d) chg(ln) start(01jan2010)
gen low_PtoB = (ln_IDXX+ ln_MAS+ ln_LMT+ ln_ADSK+ ln_MCO) / 5
gen hi_PtoB = (ln_KMB+ ln_SPGI+ ln_UPS+ ln_HD+ ln_BA) / 5

87

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 73: Bottom of the list (high PtoB stocks)

The following code compares the portfolios using a t-test. This is to test
whether the daily portfolio returns are statistically different between the two
portfolios.
ttest low_PtoB == hi_PtoB

Figure 74: t-test to compare the daily returns of the two portfolios

The following code estimates the market model for the low PtoB portfolio.
reg low_PtoB ln__GSPC

The following code estimates the market model for the high PtoB portfolio.
reg hi_PtoB ln__GSPC

88

Electronic copy available at: https://ssrn.com/abstract=2318687


Figure 75: Market model for the low PtoB portfolio

Figure 76: Market model for the high PtoB portfolio

89

Electronic copy available at: https://ssrn.com/abstract=2318687


6. Portfolio Management
The following examples are based on the student managed investment
portfolio at Loyola University New Orleans (LUP) as of April 8, 2017. Each
example within this section is continues over the previous example within
this section.
Download the code in text format.

6.1. Portfolio allocation


The following Stata code provides the security symbols and the number
of share that are included within the LUP as of April 8, 2017.
clear all
local start_date="01jan2017"

local shares_AAPL = "200"


local shares_AMBA = "100"
local shares_AXP = "100"
local shares_BA = "50"
local shares_BABA = "100"
local shares_BAC = "400"
local shares_C = "140"
local shares_CME = "100"
local shares_DIS = "100"
local shares_F = "1500"
local shares_FB = "100"
local shares_GOOGL = "25"
local shares_HSY = "60"
local shares_IBB = "50"
local shares_IJR = "100"
local shares_KO = "300"
local shares_MAR = "80"
local shares_MMM = "50"
local shares_MNST = "400"
local shares_MO = "150"
local shares_MSFT = "200"
local shares_NKE = "100"
local shares_O = "100"
local shares_PFE = "240"
local shares_PG = "75"
local shares_SHY = "2400"
local shares_SPY = "100"
local shares_T = "170"
local shares_TM = "50"
local shares_VNTV = "150"
local shares_WM = "100"

local symbols= "AAPL AMBA AXP BA BABA BAC C CME DIS F FB GOOGL HSY IBB IJR KO MAR MMM MNST MO MSFT NKE O PFE PG SHY SPY
T TM VNTV WM"

6.2. Risk - return


net install http://researchata.com/stata/010/fetchyahoooptions.pkg, force
fetchyahoooptions `symbols', m(2017-04-21)
gen diff = abs(Price-Strike)
bysort Underlying Type: egen diff_min = min(diff)
keep if diff_min == diff
collapse (sum) Volume Open_Interest (mean) IV_Yahoo, by(Underlying)
rename Underlying Symbol
rename IV_Yahoo IV
format %6.2fc IV
gsort +IV

90

Electronic copy available at: https://ssrn.com/abstract=2318687


6.3. Number of shares
gen shares=.
foreach aa in $symbols {
replace shares = ${shares_`aa'} if Symbol=="`aa'"
}
save temp1.dta, replace

6.4. Latest price, total return, standard deviation of daily returns


net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
foreach aa in `symbols' {
fetchyahooquotes `aa', freq(d) start(`start_date') chg(ln)
local price_`aa' = adjclose_`aa'[_N]
summ ln_`aa'
local sum_`aa' = r(sum)
local sd_`aa' = r(sd)
}

use temp1.dta, clear


gen price = .
gen tot_ret = .
gen std_dev =.
foreach aa in `symbols' {
replace price = `price_`aa'' if Symbol=="`aa'"
replace tot_ret = `sum_`aa'' if Symbol=="`aa'"
replace std_dev = `sd_`aa'' if Symbol=="`aa'"
}
save temp1.dta, replace

6.5. Portfolio return, portfolio standard deviation of daily returns and CAPM
Beta
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes `symbols', freq(d) chg(ln) start(`start_date')
gen portfolio = 0
foreach aa in `symbols' {
replace portfolio = portfolio + (adjclose_`aa' * `shares_`aa'') if (adjclose_`aa'!=.)
}
gen obs=_n
tsset obs
gen ln_portfolio = ln(portfolio/L.portfolio)
summ ln_portfolio
local sum_portfolio = r(sum)
local sd_portfolio = r(sd)

foreach aa in `symbols' {
reg ln_`aa' ln_SPY
local B_`aa' = _b[ln_SPY]
}
reg ln_portfolio ln_SPY
local B_portfolio = _b[ln_SPY]

use temp1.dta, clear


local obs = _N + 1
set obs `obs'
replace Symbol = "Portfolio" if Symbol==""
replace tot_ret = `sum_portfolio' if Symbol=="Portfolio"
replace std_dev = `sd_portfolio' if Symbol=="Portfolio"

gen Beta=.
foreach aa in `symbols' {
replace Beta = `B_`aa'' if Symbol=="`aa'"
}
replace Beta = `B_portfolio' if Symbol=="Portfolio"
save temp1.dta, replace

91

Electronic copy available at: https://ssrn.com/abstract=2318687


6.6. Portfolio weights
gen investment = shares * price
summ investment
local total_investment = r(sum)
gen weight = investment / `total_investment'
save temp1.dta, replace

6.7. Portfolio weighted-IV


gen weighted_IV = IV * weight
summ weighted_IV
replace IV = r(sum) if Symbol=="Portfolio"
drop weighted_IV
save temp1.dta, replace

92

Electronic copy available at: https://ssrn.com/abstract=2318687


6.8. Portfolio charts
In this section, Stata code is provided to draw some of the most common
charts for evaluating investment portfolios.

6.8.1. Investment allocation chart


This pie chart shows the investment allocation for each security included
in the portfolio as of April 8, 2017.
use temp1.dta, clear
drop if Symbol=="Portfolio"
graph pie investment, over(Symbol) sort plabel(_all name, size(*.5) gap(14)) legend(off)
graph export "pie_portfolio.png", replace

Figure 77: Portfolio Management: Investment allocation chart

93

Electronic copy available at: https://ssrn.com/abstract=2318687


6.8.2. Risk - return chart
This scatter chart shows each security as well as the overall portfolio on
a risk to return chart. Risk refers to standard deviation of daily returns
since January 1, 2017. Return refers to the total return since January 1,
2017. This chart allows comparison of investments in terms of risk to return
trade-off.
use temp1.dta, clear
rename tot_ret sum
rename std_dev sd
rename Symbol symbol
replace sum = sum * 100

twoway (scatter sum sd, mlabel(symbol) mlabposition(3) mlabangle(90) mcolor(blue)) (scatter sum sd if
(symbol=="SPY") | (symbol=="Portfolio"), mcolor(red)), title(Risk and Return for Loyno Portfolio (since `start_date'))
ytitle("Total percentage return (%)") xtitle("Standard deviation of daily returns") ylabel(#20, angle(horizontal) axis(1))
xlabel(#20, angle(vertical) format(%7.5f)) scale(.50) legend(off)

graph export "risk_return_portfolio.png", replace

Figure 78: Portfolio Management: Risk - return chart

94

Electronic copy available at: https://ssrn.com/abstract=2318687


6.8.3. Implied volatility - return chart
This scatter chart shows each security as well as the overall portfolio on
a Implied Volatility (IV) to return chart. Implied volatility refers to the
average implied volatility of the call and put options for the at-the-money
strike price with maturity of April 21, 2017 as of April 8, 2017. Return refers
to the total return since January 1, 2017. This chart allows comparison of
investments in terms of expected risk to return trade-off.
use temp1.dta, clear
rename tot_ret sum
rename IV sd
rename Symbol symbol
replace sum = sum * 100

twoway (scatter sum sd, mlabel(symbol) mlabposition(3) mlabangle(90) mcolor(blue)) (scatter sum sd
if (symbol=="SPY") | (symbol=="Portfolio"), mcolor(red)), title(IV and Return for Loyno Portfolio (since `start_date'))
ytitle("Total percentage return (%)") xtitle("Implied Volatility") ylabel(#20, angle(horizontal) axis(1))
xlabel(#20, angle(vertical) format(%7.5f)) scale(.50) legend(off)

graph export "IV_return_portfolio.png", replace

Figure 79: Portfolio Management: Implied volatility - return chart

95

Electronic copy available at: https://ssrn.com/abstract=2318687


6.8.4. Beta-return chart
This scatter chart shows each security as well as the overall portfolio on a
CAPM-Beta to return chart. CAPM-Beta refers to the regression coefficient
for the general CAPM market model as previously estimated in this lecture
notes. Return refers to the total return since January 1, 2017. This chart
allows comparison of investments in terms of expected market risk (Beta) to
return trade-off.
use temp1.dta, clear
rename tot_ret sum
rename Beta sd
rename Symbol symbol
replace sum = sum * 100

twoway (scatter sum sd, mlabel(symbol) mlabposition(3) mlabangle(90) mcolor(blue)) (scatter sum sd if
(symbol=="SPY") | (symbol=="Portfolio"), mcolor(red)), title(Risk and Return for Loyno Portfolio (since `start_date'))
ytitle("Total percentage return (%)") xtitle("CAPM-Beta") ylabel(#20, angle(horizontal) axis(1))
xlabel(#20, angle(vertical) format(%7.5f)) scale(.50) legend(off)

graph export "beta_return_portfolio.png", replace

Figure 80: Portfolio Management: Beta - return chart

96

Electronic copy available at: https://ssrn.com/abstract=2318687


6.9. Portfolio measures
6.9.1. Treynor ratio
Treynor ratio refers to the return per CAPM-Beta. CAPM-Beta refers to
the regression coefficient for the general CAPM market model as previously
estimated in this lecture notes. Return refers to the total return since January
1, 2017.
use temp1.dta, clear
gen Treynor = tot_ret / Beta
gsort +Treynor
browse Symbol Treynor

Figure 81: Portfolio Management: Treynor ratios

97

Electronic copy available at: https://ssrn.com/abstract=2318687


6.9.2. Sharpe ratio
Sharpe ratio refers to the return per risk level. Risk level refers to stan-
dard deviation of daily returns since January 1, 2017. Return refers to the
total return since January 1, 2017.
use temp1.dta, clear
gen Sharpe = tot_ret / std_dev
gsort +Sharpe
browse Symbol Sharpe

Figure 82: Portfolio Management: Sharpe ratios

98

Electronic copy available at: https://ssrn.com/abstract=2318687


6.9.3. Correlations matrix
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes `symbols', freq(d) chg(ln) start(`start_date')
corr ln*

Figure 83: Portfolio Management: Correlations matrix

99

Electronic copy available at: https://ssrn.com/abstract=2318687


6.9.4. Covariance matrix
net install http://researchata.com/stata/203/fetchyahooquotes.pkg, force
fetchyahooquotes `symbols', freq(d) chg(ln) start(`start_date')
corr ln*, cov

Figure 84: Portfolio Management: Covariance matrix

100

Electronic copy available at: https://ssrn.com/abstract=2318687


List of Figures
1 Index components: fetchcomponents . . . . . . . . . . . . . . 6
2 Daily prices: fetchyahooquotes data . . . . . . . . . . . . . . . 7
3 Daily prices: fetchyahooquotes chart . . . . . . . . . . . . . . 8
4 Intraday prices: fetchyahooquotes . . . . . . . . . . . . . . . . 9
5 Intraday prices: fetchyahooquotes chart . . . . . . . . . . . . . 10
6 Option prices: fetchyahoooptions data . . . . . . . . . . . . . 12
7 Key statistics: fetchyahookeystats data . . . . . . . . . . . . . 13
8 Financial statements: fetch statements data . . . . . . . . . . 16
9 Financial statements: fetch statements Dow-Jones Industrial
index components’ balance sheets . . . . . . . . . . . . . . . . 18
10 Economic data: freduse data . . . . . . . . . . . . . . . . . . . 20
11 Economic data: freduse chart . . . . . . . . . . . . . . . . . . 21
12 Daily gold fixing: fetchgold data . . . . . . . . . . . . . . . . . 23
13 Daily gold fixing: fetchgold chart . . . . . . . . . . . . . . . . 24
14 IPOs: fetch IPO data . . . . . . . . . . . . . . . . . . . . . . . 25
15 Short interest: short interest data . . . . . . . . . . . . . . . . 27
16 Institutional ownership: institutional ownership data . . . . . 29
17 Earnings per share: fetch EPS data . . . . . . . . . . . . . . . 30
18 Insider activity: insider activity data . . . . . . . . . . . . . . 32
19 Analyst recommendations: fetch analyst data . . . . . . . . . 33
20 Earnings dates: earnings dates data . . . . . . . . . . . . . . . 34
21 Economic dates: economic dates data . . . . . . . . . . . . . . 35
22 Security profiles: profiles data . . . . . . . . . . . . . . . . . . 36
23 Statistical analysis: Descriptive statistics using tabstat . . . . 37
24 Statistical analysis: Descriptive statistics by year using tabstat 38
25 Statistical analysis: Descriptive statistics using summ . . . . . 39
26 Statistical analysis: Risk and return chart . . . . . . . . . . . 40
27 Statistical analysis: Distribution of daily returns chart . . . . 41
28 Econometric analysis: Capital Asset Pricing Model OLS esti-
mation results . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
29 Econometric analysis: Capital Asset Pricing Model GARCH
estimation results . . . . . . . . . . . . . . . . . . . . . . . . . 43
30 Econometric analysis: Day-of-the-week test data . . . . . . . . 45
31 Econometric analysis: Day-of-the-week test estimation results 46
32 Technical analysis: Moving averages chart . . . . . . . . . . . 48
33 Technical analysis: Bollinger bands chart . . . . . . . . . . . . 49

101

Electronic copy available at: https://ssrn.com/abstract=2318687


34 Technical analysis: RSI chart . . . . . . . . . . . . . . . . . . 50
35 Technical analysis: MACD chart . . . . . . . . . . . . . . . . . 51
36 Risk & return: Year-to-date standard deviations and total
returns . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53
37 Risk & return: Implied volatilities . . . . . . . . . . . . . . . . 54
38 Risk & return: EP ratios . . . . . . . . . . . . . . . . . . . . . 55
39 Risk & return: Earnings yield vs. realized risk . . . . . . . . . 56
40 Risk & return: Earnings yield vs. implied volatility . . . . . . 57
41 Options: Purchased call option chart . . . . . . . . . . . . . . 59
42 Options: Purchased put option chart . . . . . . . . . . . . . . 60
43 Options: Written call option chart . . . . . . . . . . . . . . . . 61
44 Options: Written put option chart . . . . . . . . . . . . . . . . 62
45 Options: Covered call option chart . . . . . . . . . . . . . . . 63
46 Options: Protective put option chart . . . . . . . . . . . . . . 64
47 Options: Credit call spread chart . . . . . . . . . . . . . . . . 65
48 Options: Debit call spread chart . . . . . . . . . . . . . . . . . 66
49 Options: Credit put spread chart . . . . . . . . . . . . . . . . 67
50 Options: Debit put spread chart . . . . . . . . . . . . . . . . . 68
51 Options: Credit box spread . . . . . . . . . . . . . . . . . . . 70
52 Options: Debit box spread . . . . . . . . . . . . . . . . . . . . 72
53 Options: Butterfly call spread . . . . . . . . . . . . . . . . . . 73
54 Options: Butterfly put spread . . . . . . . . . . . . . . . . . . 74
55 Options: Straddle . . . . . . . . . . . . . . . . . . . . . . . . . 75
56 Options: Strip . . . . . . . . . . . . . . . . . . . . . . . . . . . 76
57 Options: Strap . . . . . . . . . . . . . . . . . . . . . . . . . . 77
58 Options: Strangle . . . . . . . . . . . . . . . . . . . . . . . . . 78
59 Call option premiums for AAPL for maturity date 10/20/2017 79
60 Call options’ average implied volatility for AAPL for maturity
date 10/20/2017 . . . . . . . . . . . . . . . . . . . . . . . . . . 80
61 Call options’ volatility smile for AAPL for maturity date 10/20/2017 81
62 Top of the list (low P/E stocks) . . . . . . . . . . . . . . . . . 82
63 Bottom of the list (high P/E stocks) . . . . . . . . . . . . . . 83
64 t-test to compare the daily returns of the two portfolios . . . . 83
65 Market model for the low P/E portfolio . . . . . . . . . . . . . 84
66 Market model for the high P/E portfolio . . . . . . . . . . . . 84
67 Top of the list (low mcap stocks) . . . . . . . . . . . . . . . . 85
68 Bottom of the list (high mcap stocks) . . . . . . . . . . . . . . 85
69 t-test to compare the daily returns of the two portfolios . . . . 86

102

Electronic copy available at: https://ssrn.com/abstract=2318687


70 Market model for the low mcap portfolio . . . . . . . . . . . . 86
71 Market model for the high mcap portfolio . . . . . . . . . . . 87
72 Top of the list (low PtoB stocks) . . . . . . . . . . . . . . . . 87
73 Bottom of the list (high PtoB stocks) . . . . . . . . . . . . . . 88
74 t-test to compare the daily returns of the two portfolios . . . . 88
75 Market model for the low PtoB portfolio . . . . . . . . . . . . 89
76 Market model for the high PtoB portfolio . . . . . . . . . . . . 89
77 Portfolio Management: Investment allocation chart . . . . . . 93
78 Portfolio Management: Risk - return chart . . . . . . . . . . . 94
79 Portfolio Management: Implied volatility - return chart . . . . 95
80 Portfolio Management: Beta - return chart . . . . . . . . . . . 96
81 Portfolio Management: Treynor ratios . . . . . . . . . . . . . . 97
82 Portfolio Management: Sharpe ratios . . . . . . . . . . . . . . 98
83 Portfolio Management: Correlations matrix . . . . . . . . . . . 99
84 Portfolio Management: Covariance matrix . . . . . . . . . . . 100

103

Electronic copy available at: https://ssrn.com/abstract=2318687


References
Dicle, M.F., 2013. Financial portfolio selection using the multifactor capital
asset pricing model and imported options data. Stata Journal 13, 603–
617(15).

Dicle, M.F., Levendis, J., 2011. Importing financial data. Stata Journal 11,
620–626(7).

Dicle, M.F., Levendis, J., 2016. Technical financial analysis tools for stata
(May 25, 2017). Available at SSRN .

Dicle, M.F., Levendis, J.D., 2014. The day-of-the-week effect revisited: In-
ternational evidence. Journal of Economics and Finance 38, 407–437.

Drukker, D.M., 2006. Importing federal reserve economic data. Stata Journal
6, 384–386(3).

104

Electronic copy available at: https://ssrn.com/abstract=2318687