Monthly Archives: February 2016

Research for Profit

Category : iOS Apps

Research for Profit

Download at iTunes

This app is for educational purposes only.

What?

Research for Profit app provides educational content that relates to finance, statistics and econometrics.

Content includes:

1) Teaching notes and lecture material,
2) Financial research utilities and programming code (Stata, PHP and iOS),
3) Data mining utilities and programming code (Stata, PHP and iOS),
4) Technical analysis utilities and programming code (Stata, PHP and iOS),
5) Empirical tests (Stata).

Purpose:

To provide educational content for finance, statistics and econometrics.

Audience:

Graduate and undergraduate students of finance, accounting and economics.

Cost:

Free (No ads, no in-app purchases etc.)
You can also access the content via: researchforprofit.com

Feedback:

info@researchforprofit.com

DISCLAIMER

THIS SOFTWARE AND ITS CONTENTS ARE FOR EDUCATIONAL PURPOSES ONLY.

THIS SOFTWARE AND ITS CONTENTS ARE PROVIDED “AS IS” AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.

IN NO EVENT SHALL MEHMET F. DICLE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, USE OF ITS CONTENTS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Without limiting the foregoing, Mehmet F. Dicle makes NO WARRANTY that:
– the software or its contents will meet your requirements.
– the software or its contents will be uninterrupted, timely, secure or error-free.
– the results that may be obtained from the use of the software or its contents will be effective, accurate or reliable.
– the quality of the software or its contents will meet your expectations.
– any errors in the software or its contents will be corrected.
– the software or its contents will be accurate, reliable or even usable.

Software, its contents and its documentation:
– could include technical or other mistakes, inaccuracies or typographical errors.
– Mehmet F. Dicle may make changes to the software, its contents or documentation.
– may be out of date and Mehmet F. Dicle makes no commitment to update such materials.
– Mehmet F. Dicle assumes no responsibility for errors or omissions in the software, its contents or documentation.

In no event shall Mehmet F. Dicle be liable to you or any third parties for any special, punitive, incidental, indirect or consequential damages of any kind, or any damages whatsoever, including, without limitation, those resulting from loss of use, data or profits, whether or not Mehmet F. Dicle has been advised of the possibility of such damages, and on any theory of liability, arising out of or in connection with the use of this software or its contents.

The use of the software is done at your own discretion and risk and with agreement that you will be solely responsible for any damage to your computer system or loss of data that results from such activities.

FURTHERMORE: LICENSED APPLICATION END USER LICENSE AGREEMENT available at http://www.apple.com/legal/internet-services/itunes/appstore/dev/stdeula/ APPLIES TO THIS SOFTWARE.

No advice or information, whether oral or written, obtained by you from Mehmet F. Dicle shall create any warranty for the software and its contents.

Information on this software and its contents is not an offer to buy or sell, or a solicitation of any offer to buy or sell any securities.

Mehmet F. Dicle disclaims any responsibility for information, services, or products found on the software and its contents.

Additionally, Mehmet F. Dicle is not liable for any direct or indirect technical or system issues or any consequences arising out of use of the software or its contents.

Mehmet F. Dicle is NOT a financial advisor and does NOT provide financial advice in any form or shape. Any examples used within the software and within its contents are purely for educational purposes. There are NO direct or implied financial advice WHAT-SO-EVER.

Methods, procedures, programming code and material provided within the software and its contents may be COMPLETELY WRONG.

Anything and everything about (and within) this software and its contents may be COMPLETELY WRONG.

The Information on this software and its contents is provided for educational purposes only, without any express or implied warranty of any kind, including warranties of accuracy, completeness, or fitness for any particular purpose.

The Information contained in or provided from or through this software and its contents is not intended to be and does not constitute financial advice, investment advice, trading advice or any other advice.

YOU SHOULD NOT MAKE ANY DECISION, FINANCIAL, INVESTMENTS, TRADING OR OTHERWISE, BASED ON ANY OF THE INFORMATION PRESENTED ON THIS SOFTWARE AND ITS CONTENTS.

YOU SHOULD NOT USE THIS SOFTWARE AND ITS CONTENTS WITHIN YOUR DECISION CRITERIA FOR ANY DECISION, FINANCIAL, INVESTMENTS, TRADING OR OTHERWISE.

You understand that you are using any and all Information available on or through this software and its contents AT YOUR OWN RISK.

Trading of stocks, options, futures, commodities, index futures or any other securities has SERIOUS RISKS involved. YOU CAN LOSE ALL YOUR MONEY AND ASSETS. YOU CAN EVEN LOSE MORE MONEY AND ASSETS THAN YOU HAVE.

   

PRIVACY


This privacy policy governs your use of the software application “RESEARCH FOR PROFIT” (“Application”) for mobile devices that was created by MEHMET F. DICLE.

The Application is intended to be provide educational content for finance, statistics and econometrics.

Content includes, but not limited to:
1) Teaching notes and lecture material,
2) Financial research utilities and programming code (Stata, PHP and iOS),
3) Data mining utilities and programming code (Stata, PHP and iOS),
4) Technical analysis utilities and programming code (Stata, PHP and iOS),
5) Empirical tests (Stata).

User Provided Information

The Application stores unique device ID (UDID) and usage counter. Usage counter is incremented (by one) each time the Application is started by the user.
This information (UDID and usage counter) is sent to our servers every time the Application is started by the user (as long as there is internet connection).

The Application does not send any other data to our servers.

Automatically Collected Information

In addition, the Application may collect certain information automatically, including, but not limited to, the type of mobile device you use, your mobile devices unique device ID, the IP address of your mobile device, your mobile operating system, the type of mobile Internet browsers you use, and information about the way you use the Application.
This Application does NOT collect precise information about the location of your mobile device.

Do third parties see and/or have access to information obtained by the Application?

We will share your information with third parties only in the ways that are described in this privacy statement.

We may disclose User Provided and Automatically Collected Information:
– as required by law, such as to comply with a subpoena, or similar legal process;
– when we believe in good faith that disclosure is necessary to protect our rights, protect your safety or the safety of others, investigate fraud, or respond to a government request;
– with our trusted services providers who work on our behalf, do not have an independent use of the information we disclose to them, and have agreed to adhere to the rules set forth in this privacy statement.
– if MEHMET F. DICLE is involved in a merger, acquisition, or sale of all or a portion of its software assets, you will be notified via email and/or a prominent notice on our Web site of any change in ownership or uses of this information, as well as any choices you may have regarding this information.
The Application uses GoDaddy.com, LLC for data, domain and SQL hosting services:
– GoDaddy.com, LLC legal agreements and policies can be accessed at: https://www.godaddy.com/legal-agreements.aspx
– GoDaddy.com, LLC privacy policy can be accessed at: https://www.godaddy.com/Agreements/Privacy.aspx

What are my opt-out rights?

You can stop all collection of information by the Application easily by uninstalling the Application.

You may use the standard uninstall processes as may be available as part of your mobile device or via the mobile application marketplace or network.

Data Retention Policy, Managing Your Information

We will retain User Provided data for as long as you use the Application and for a reasonable time thereafter.

If you’d like us to delete User Provided Data that you have provided via the Application, please contact us at info@researchforprofit.com and we will respond in a reasonable time.

Children

We do not use the Application to knowingly solicit data from or market to children under the age of 13.

If a parent or guardian becomes aware that his or her child has provided us with information without their consent, he or she should contact us at info@researchforprofit.com

We will delete such information from our files within a reasonable time.

Security

We are concerned about safeguarding the confidentiality of your information.

We provide physical, electronic, and procedural safeguards to protect information we process and maintain.

For example, we limit access to this information to authorized employees and contractors who need to know that information in order to operate, develop or improve our Application.

Please be aware that, although we endeavor provide reasonable security for information we process and maintain, no security system can prevent all potential security breaches.

The Application uses GoDaddy.com, LLC for data, domain and SQL hosting services:
– GoDaddy.com, LLC legal agreements and policies can be accessed at: https://www.godaddy.com/legal-agreements.aspx
– GoDaddy.com, LLC privacy policy can be accessed at: https://www.godaddy.com/Agreements/Privacy.aspx

Changes

This Privacy Policy may be updated from time to time for any reason.

We will notify you of any changes to our Privacy Policy by posting the new Privacy Policy here.

You are advised to consult this Privacy Policy regularly for any changes, as continued use is deemed approval of all changes.

Your Consent

By using the Application, you are consenting to our processing of your information as set forth in this Privacy Policy now and as amended by us.

“Processing,” means using cookies on a computer/hand held device or using or touching information in any way, including, but not limited to, collecting, storing, deleting, using, combining and disclosing information, all of which activities will take place in the United States.

If you reside outside the United States your information will be transferred, processed and stored there under United States privacy standards.

Contact us

If you have any questions regarding privacy while using the Application, or have questions about our practices, please contact us via email at info@researchforprofit.com


Link Depot

Category : iOS Apps

Link Depot

Download at iTunes

This app is for educational purposes only.

What?

1) Save your internet links under categories
2) Hide private links under your fingerprint authentication
3) Email the list of links to yourself or to others (i.e. create an HTML list of your links).
4) Backup and restore (even to other devices).

Purpose:

This app came out of my own need.

1) I save links as I come across them, like everybody else. Links that are related to my job, my hobbies etc. But, when it is time to find them, I can’t find a specific link that I am looking for. I end up searching again and again. Putting them under categories makes it easier for me to find my links.

2) There are a few favorite links that are private to me. No such thing as private favorites with any browsers that I know of. So, with “Link Depot”, links can be saved as private. Private links are hidden until you click on the “fleur de lis” button and pass finger print authentication.

3) Frequently, I need to prepare lists of links and email them to others. For instance: I prepare “suggested reading” for students in my classes. Providing a list of links for the reading material makes life easier for everyone. With a button click, you can email your entire link library (except private links) or group of links to anybody. Using the list in the email, you can also create HTML pages with links.

4) Like most people, I use browser links and share them through popular means. However, to this day, I am not happy with the way links are shared. So, “Link Depot” makes the process “manual”. I create list of links using my iPad and restore it to my iPhone (or vice-a-versa). The process is not sync. It is a manual backup and restore.

Audience:

Anybody who needs to save links under different categories.

Cost:

Completely Free.
No ads.
No in-app purchases.

Feedback:

info@researchforprofit.com

DISCLAIMER

THIS SOFTWARE AND ITS CONTENTS ARE FOR EDUCATIONAL PURPOSES ONLY.

THIS SOFTWARE AND ITS CONTENTS ARE PROVIDED “AS IS” AND ANY EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.

IN NO EVENT SHALL MEHMET F. DICLE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, USE OF ITS CONTENTS, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

Without limiting the foregoing, Mehmet F. Dicle makes NO WARRANTY that:
– the software or its contents will meet your requirements.
– the software or its contents will be uninterrupted, timely, secure or error-free.
– the results that may be obtained from the use of the software or its contents will be effective, accurate or reliable.
– the quality of the software or its contents will meet your expectations.
– any errors in the software or its contents will be corrected.
– the software or its contents will be accurate, reliable or even usable.

Software, its contents and its documentation:
– could include technical or other mistakes, inaccuracies or typographical errors.
– Mehmet F. Dicle may make changes to the software, its contents or documentation.
– may be out of date and Mehmet F. Dicle makes no commitment to update such materials.
– Mehmet F. Dicle assumes no responsibility for errors or omissions in the software, its contents or documentation.

In no event shall Mehmet F. Dicle be liable to you or any third parties for any special, punitive, incidental, indirect or consequential damages of any kind, or any damages whatsoever, including, without limitation, those resulting from loss of use, data or profits, whether or not Mehmet F. Dicle has been advised of the possibility of such damages, and on any theory of liability, arising out of or in connection with the use of this software or its contents.

The use of the software is done at your own discretion and risk and with agreement that you will be solely responsible for any damage to your computer system or loss of data that results from such activities.

FURTHERMORE: LICENSED APPLICATION END USER LICENSE AGREEMENT available at http://www.apple.com/legal/internet-services/itunes/appstore/dev/stdeula/ APPLIES TO THIS SOFTWARE.

No advice or information, whether oral or written, obtained by you from Mehmet F. Dicle shall create any warranty for the software and its contents.

Information on this software and its contents is not an offer to buy or sell, or a solicitation of any offer to buy or sell any securities.

Mehmet F. Dicle disclaims any responsibility for information, services, or products found on the software and its contents.

Additionally, Mehmet F. Dicle is not liable for any direct or indirect technical or system issues or any consequences arising out of use of the software or its contents.

Mehmet F. Dicle is NOT a financial advisor and does NOT provide financial advice in any form or shape. Any examples used within the software and within its contents are purely for educational purposes. There are NO direct or implied financial advice WHAT-SO-EVER.

Methods, procedures, programming code and material provided within the software and its contents may be COMPLETELY WRONG.

Anything and everything about (and within) this software and its contents may be COMPLETELY WRONG.

The Information on this software and its contents is provided for educational purposes only, without any express or implied warranty of any kind, including warranties of accuracy, completeness, or fitness for any particular purpose.

The Information contained in or provided from or through this software and its contents is not intended to be and does not constitute financial advice, investment advice, trading advice or any other advice.

YOU SHOULD NOT MAKE ANY DECISION, FINANCIAL, INVESTMENTS, TRADING OR OTHERWISE, BASED ON ANY OF THE INFORMATION PRESENTED ON THIS SOFTWARE AND ITS CONTENTS.

YOU SHOULD NOT USE THIS SOFTWARE AND ITS CONTENTS WITHIN YOUR DECISION CRITERIA FOR ANY DECISION, FINANCIAL, INVESTMENTS, TRADING OR OTHERWISE.

You understand that you are using any and all information available on or through this software and its contents AT YOUR OWN RISK.

Trading of stocks, options, futures, commodities, index futures or any other securities has SERIOUS RISKS involved. YOU CAN LOSE ALL YOUR MONEY AND ASSETS. YOU CAN EVEN LOSE MORE MONEY AND ASSETS THAN YOU HAVE.

   

PRIVACY


This privacy policy governs your use of the software application “LINK DEPOT” (“Application”) for mobile devices that was created by MEHMET F. DICLE.

The Application is for educational purposes only.

The Application is intended to:
1) Save your internet links under categories
2) Hide private links under your fingerprint authentication
3) Email the list of links to yourself or to others (i.e. create an HTML list of your links).
4) Backup and restore (even to other devices).

User Provided Information

The Application stores unique device ID (UDID) and usage counter. Usage counter is incremented (by one) each time the Application is started by the user.
This information (UDID and usage counter) is sent to our servers every time the Application is started by the user (as long as there is internet connection).

The Application allows the user to register with our servers. During this process, a username (selected and provided by the user), a password (selected and provided by the user) and user’s email address (selected and provided by the user) are sent to our servers. This data is stored at our servers.

The Application allows the user to login with our servers. During this process, a username (selected and provided by the user), a password (selected and provided by the user) and user’s email address (selected and provided by the user) are sent to our servers. This data is stored at our servers.

The Application allows the user to send himself/herself a new randomly generated password (upon user’s request). The email is sent to the email address provided by the user during the registration. The new password is sent to our servers. This data is stored at our servers.

The Application allows the user to backup (save) user’s internet links, their titles and all related data to our servers. This data is stored at our servers. The backup process can only be initiated upon user’s request within the Application.

The Application allows the user to restore (load) user’s internet links, their titles and all related data from our servers. This data is stored at our servers. The restore process can only be initiated upon user’s request within the Application.

The Application does not send any other data to our servers.

Automatically Collected Information

In addition, the Application may collect certain information automatically, including, but not limited to, the type of mobile device you use, your mobile devices unique device ID, the IP address of your mobile device, your mobile operating system, the type of mobile Internet browsers you use, and information about the way you use the Application.
This Application does NOT collect precise information about the location of your mobile device.

Do third parties see and/or have access to information obtained by the Application?

We will share your information with third parties only in the ways that are described in this privacy statement.

We may disclose User Provided and Automatically Collected Information:
– as required by law, such as to comply with a subpoena, or similar legal process;
– when we believe in good faith that disclosure is necessary to protect our rights, protect your safety or the safety of others, investigate fraud, or respond to a government request;
– with our trusted services providers who work on our behalf, do not have an independent use of the information we disclose to them, and have agreed to adhere to the rules set forth in this privacy statement.
– if MEHMET F. DICLE is involved in a merger, acquisition, or sale of all or a portion of its software assets, you will be notified via email and/or a prominent notice on our Web site of any change in ownership or uses of this information, as well as any choices you may have regarding this information.
The Application uses GoDaddy.com, LLC for data, domain and SQL hosting services:
– GoDaddy.com, LLC legal agreements and policies can be accessed at: https://www.godaddy.com/legal-agreements.aspx
– GoDaddy.com, LLC privacy policy can be accessed at: https://www.godaddy.com/Agreements/Privacy.aspx

What are my opt-out rights?

You can stop all collection of information by the Application easily by uninstalling the Application.

You may use the standard uninstall processes as may be available as part of your mobile device or via the mobile application marketplace or network.

Data Retention Policy, Managing Your Information

We will retain User Provided data for as long as you use the Application and for a reasonable time thereafter.

If you’d like us to delete User Provided Data that you have provided via the Application, please contact us at info@researchforprofit.com and we will respond in a reasonable time.

Children

We do not use the Application to knowingly solicit data from or market to children under the age of 13.

If a parent or guardian becomes aware that his or her child has provided us with information without their consent, he or she should contact us at info@researchforprofit.com

We will delete such information from our files within a reasonable time.

Security

We are concerned about safeguarding the confidentiality of your information.

We provide physical, electronic, and procedural safeguards to protect information we process and maintain.

For example, we limit access to this information to authorized employees and contractors who need to know that information in order to operate, develop or improve our Application.

Please be aware that, although we endeavor provide reasonable security for information we process and maintain, no security system can prevent all potential security breaches.

The Application uses GoDaddy.com, LLC for data, domain and SQL hosting services:
– GoDaddy.com, LLC legal agreements and policies can be accessed at: https://www.godaddy.com/legal-agreements.aspx
– GoDaddy.com, LLC privacy policy can be accessed at: https://www.godaddy.com/Agreements/Privacy.aspx

Changes

This Privacy Policy may be updated from time to time for any reason.

We will notify you of any changes to our Privacy Policy by posting the new Privacy Policy here.

You are advised to consult this Privacy Policy regularly for any changes, as continued use is deemed approval of all changes.

Your Consent

By using the Application, you are consenting to our processing of your information as set forth in this Privacy Policy now and as amended by us.

“Processing,” means using cookies on a computer/hand held device or using or touching information in any way, including, but not limited to, collecting, storing, deleting, using, combining and disclosing information, all of which activities will take place in the United States.

If you reside outside the United States your information will be transferred, processed and stored there under United States privacy standards.

Contact us

If you have any questions regarding privacy while using the Application, or have questions about our practices, please contact us via email at info@researchforprofit.com


Pre- and post-dividend returns compared

Category : Uncategorized

Pre- and post-dividend returns compared

*
clear all
cd "/users/mfd/desktop"

capture: erase temp.dta

* Get the list of all DJI component companies (^GSPC)
mfd_dm_components, symbol(^GSPC)
levelsof Symbol, local(tickers)

foreach aa of local tickers {
	mfd_dm_prices `aa', freq(d) chg(ln) start(01jan2000)
	capture: mfd_dm_prices `aa', freq(v) start(01jan2000) merge
	capture: summ dividends_`aa'
	if (_rc==0) {
		gen day=_n
		tsset day

		gen pre_div = (ln_`aa'+L.ln_`aa'+L2.ln_`aa'+L3.ln_`aa'+L4.ln_`aa') if dividends_`aa'!=.
		gen post_div = (F.ln_`aa'+F2.ln_`aa'+F3.ln_`aa'+F4.ln_`aa'+F5.ln_`aa') if dividends_`aa'!=.

		keep if dividends_`aa'!=.
		keep date pre* post* 
		gen symbol="`aa'"
		
		capture: append using temp.dta
		save temp.dta, replace
	}
}
ttest pre_div=post_div
*

Portfolio comparison (price-to-earnings ratio)

Category : Archieve

Compare the daily returns for two portfolios: Based on price-to-earnings ratio

*
clear all
cd "/Users/mfd/Desktop"
* This directory is for me. You need to use your own working directory.


* Get the list of all DJI component companies (^DJI)
mfd_dm_components, symbol(^DJI)
levelsof Symbol, local(tickers)

local counter=1
foreach aa of local tickers {
	di "BS `counter': `aa'"
	clear
	qui: capture: mfd_dm_statements `aa', freq(a) st(BS) type(wider)
	if (_rc==0) { 	
		qui: if (`counter'!=1) append using BS.dta
		qui: save BS.dta, replace
		local counter = `counter'+1	
	}
}

replace price = subinstr(price,",","",1)
destring price, gen(price2)
gen pe=price2/( net_income/ shares)

keep symbol name date pe
keep if (year(date)==2014)
replace pe = abs(pe)
sort pe

* Low portfolio Symbols
* We use 1 to 3 because we want to include first 3 companies into our portfolio
forval aa=1/3 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}


* High portfolio Symbols
* We use 23 to 25 because we want to include the last 3 companies into our portfolio
forval aa=23/25 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return /3
* we divide by 3 because we included 3 companies into our portfolio


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return /3
* we divide by 3 because we included 3 companies into our portfolio


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return
*

It may be the case that you may have slow internet connection. In this case your download of S&P-500 companies’ financial statements will either take forever or will not complete.
The following part of the above code is to download the data:

*
* Get the list of all DJI component companies (^DJI)
mfd_dm_components, symbol(^DJI)
levelsof Symbol, local(tickers)

local counter=1
foreach aa of local tickers {
	di "BS `counter': `aa'"
	clear
	qui: capture: mfd_dm_statements `aa', freq(a) st(BS) type(wider)
	if (_rc==0) { 	
		qui: if (`counter'!=1) append using BS.dta
		qui: save BS.dta, replace
		local counter = `counter'+1	
	}
}
*

So, instead of downloading this data one-by-one, you can actually download the data as a whole (i.e. I downloaded the data for you and made it available for download in one file).
The original code then would become as follows:

*
clear all
cd "/Users/mfd/Desktop"
* This directory is for me. You need to use your own working directory.

use "http://researchforprofit.com/data_public/FIN400_financial_statements.dta", clear

replace price = subinstr(price,",","",1)
destring price, gen(price2)
gen pe=price2/( net_income/ shares)

keep symbol name date pe
keep if (year(date)==2014)
replace pe = abs(pe)
sort pe

* Low portfolio Symbols
* We use 1 to 3 because we want to include first 3 companies into our portfolio
forval aa=1/3 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}


* High portfolio Symbols
* We use 23 to 25 because we want to include the last 3 companies into our portfolio
forval aa=23/25 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return /3
* we divide by 3 because we included 3 companies into our portfolio


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return /3
* we divide by 3 because we included 3 companies into our portfolio


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return

*

Portfolio comparison (debt-to-asset ratio)

Category : Archieve

Compare the daily returns for two portfolios: Based on debt-to-assets ratio

*
clear all
cd "/Users/mfd/Desktop"
* This directory is for me. You need to use your own working directory.


* Get the list of all DJI component companies (^GSPC)
mfd_dm_components, symbol(^GSPC)
levelsof Symbol, local(tickers)

local counter=1
foreach aa of local tickers {
	di "BS `counter': `aa'"
	clear
	qui: capture: mfd_dm_statements `aa', freq(a) st(BS) type(wider)
	if (_rc==0) { 	
		qui: if (`counter'!=1) append using BS.dta
		qui: save BS.dta, replace
		local counter = `counter'+1	
	}
}

gen liabities_to_assets = total_liabilities/total_assets
keep symbol name date liabities_to_assets
keep if (year(date)==2014)
sort liabities_to_assets

* Low portfolio Symbols
* We use 1 to 3 because we want to include first 3 companies into our portfolio
forval aa=1/3 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}


* High portfolio Symbols
* We use 23 to 25 because we want to include the last 3 companies into our portfolio
forval aa=23/25 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return /3
* we divide by 3 because we included 3 companies into our portfolio


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return /3
* we divide by 3 because we included 3 companies into our portfolio


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return
*

It may be the case that you may have slow internet connection. In this case your download of S&P-500 companies’ financial statements will either take forever or will not complete.
The following part of the above code is to download the data:

*
* Get the list of all DJI component companies (^DJI)
mfd_dm_components, symbol(^DJI)
levelsof Symbol, local(tickers)

local counter=1
foreach aa of local tickers {
	di "BS `counter': `aa'"
	clear
	qui: capture: mfd_dm_statements `aa', freq(a) st(BS) type(wider)
	if (_rc==0) { 	
		qui: if (`counter'!=1) append using BS.dta
		qui: save BS.dta, replace
		local counter = `counter'+1	
	}
}
*

So, instead of downloading this data one-by-one, you can actually download the data as a whole (i.e. I downloaded the data for you and made it available for download in one file).
The original code then would become as follows:

*
clear all
cd "/Users/mfd/Desktop"
* This directory is for me. You need to use your own working directory.

use "http://researchforprofit.com/data_public/FIN400_financial_statements.dta", clear

gen liabities_to_assets = total_liabilities/total_assets
keep symbol name date liabities_to_assets
keep if (year(date)==2014)
sort liabities_to_assets

* Low portfolio Symbols
* We use 1 to 46 because we want to include first 46 companies into our portfolio
forval aa=1/46 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}


* High portfolio Symbols
* We use 417 to 463 because we want to include the last 3 companies into our portfolio
forval aa=417/463 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	capture: replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return / 46
* we divide by 46 because we included 46 companies into our portfolio


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	capture: replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return / 46
* we divide by 46 because we included 46 companies into our portfolio


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return

*

How to find a company: PNR

*
clear all
cd "/Users/mfd/Desktop"
* This directory is for me. You need to use your own working directory.
 
use "http://researchforprofit.com/data_public/FIN400_financial_statements.dta", clear
 
gen liabities_to_assets = total_liabilities/total_assets
keep symbol name date liabities_to_assets
keep if (year(date)==2014)
sort liabities_to_assets

br if symbol=="PNR"
*

We are at 4th portfolio. We will now compare the 4th portfolio to the highest portfolio.

*
* Low portfolio Symbols
* We use 141 to 187 because we want to include first 46 companies into our portfolio
forval aa=141/187 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}


* High portfolio Symbols
* We use 417 to 463 because we want to include the last 3 companies into our portfolio
forval aa=417/463 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	capture: replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return / 46
* we divide by 46 because we included 46 companies into our portfolio


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	capture: replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return / 46
* we divide by 46 because we included 46 companies into our portfolio


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return
*

Portfolio comparison (based on total returns)

Category : Archieve

Compare the daily returns for two portfolios: Based on total returns

*
clear all
cd "/Users/mfd/Desktop"
mfd_dm_components_cnn
levelsof Symbol, local(tickers)
mfd_dm_prices `tickers', freq(d) chg(ln) start(01jan2014) end(31dec2014)
save 2014_prices.dta

* Total 2014 return
use 2014_prices.dta, clear
collapse (sum) ln*
xpose, clear varname format
gen symbol = substr(_varname,4,.)
sort v1

* Low portfolio Symbols
forval aa=1/50 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}

* High portfolio Symbols
forval aa=447/497 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return / 50


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return / 50


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return
*

Or, if you are downloading the file I prepared:

*

clear all
cd "/Users/mfd/Desktop"
use "http://researchforprofit.com/data_public/FIN400_2014_prices.dta", clear

collapse (sum) ln*
xpose, clear varname format
gen symbol = substr(_varname,4,.)
sort v1

* Low portfolio Symbols
forval aa=1/50 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}

* High portfolio Symbols
forval aa=447/497 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return / 50


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return / 50


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return
*

Portfolio comparison (based on risk)

Category : Archieve

Compare the daily returns for two portfolios: Based on risk

*
clear all
cd "/Users/mfd/Desktop"
mfd_dm_components_cnn
levelsof Symbol, local(tickers)
mfd_dm_prices `tickers', freq(d) chg(ln) start(01jan2014) end(31dec2014)
save 2014_prices.dta

* Total 2014 risk
use 2014_prices.dta, clear
collapse (sd) ln*
xpose, clear varname format
gen symbol = substr(_varname,4,.)
sort v1

* Low portfolio Symbols
forval aa=1/50 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}

* High portfolio Symbols
forval aa=447/497 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return / 50


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return / 50


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return
*

Or, if you are downloading the file I prepared:

*

clear all
cd "/Users/mfd/Desktop"
use "http://researchforprofit.com/data_public/FIN400_2014_prices.dta", clear

collapse (sd) ln*
xpose, clear varname format
gen symbol = substr(_varname,4,.)
sort v1

* Low portfolio Symbols
forval aa=1/50 {
	local LP_symbols="`LP_symbols' " + symbol[`aa']
}

* High portfolio Symbols
forval aa=447/497 {
	local HP_symbols="`HP_symbols' " + symbol[`aa']
}


* Let's see which companies are in each portfolio
di "`LP_symbols'"
di "`HP_symbols'"


* Let's download the daily prices
mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan2015)


* Let's calculate the equally weighted LOW portfolio returns
gen LP_portfolio_return = 0
foreach company in `LP_symbols' {
	replace LP_portfolio_return = LP_portfolio_return + ln_`company'
}
replace LP_portfolio_return = LP_portfolio_return / 50


* Let's calculate the equally weighted HIGH portfolio returns
gen HP_portfolio_return = 0
foreach company in `HP_symbols' {
	replace HP_portfolio_return = HP_portfolio_return + ln_`company'
}
replace HP_portfolio_return = HP_portfolio_return / 50


* Now, we test
ttest LP_portfolio_return = HP_portfolio_return
*

Portfolio comparison (based on dividend yields)

Category : Archieve

Compare the daily returns for two portfolios: Based on dividend yields

*
clear all
cd "/users/mfd/desktop"

* Get the list of all DJI component companies (^GSPC)
mfd_dm_components, symbol(^GSPC)
levelsof Symbol, local(tickers)

foreach aa of local tickers {
	mfd_dm_prices `aa', freq(v) start(01jan2009)
	capture: summ dividends_`aa'
	if (_rc==0) {
	        capture: mfd_dm_prices `aa', freq(d) chg(ln) start(01jan2009) merge
		replace dividends_`aa' = dividends_`aa' / adjclose_`aa'
		gen year=year(date)
		collapse (sum) dividends_`aa', by (year)
		
		gen symbol="`aa'"
		rename dividends_`aa' dividends		
		
		capture: append using temp.dta
		save temp.dta, replace
	}
}
save dividends.dta, replace
tabstat dividends, by(year) stat(mean count)

quiet: {
    forval year=2009/2014 {
        local next_year = `year' + 1

        use dividends.dta, clear
        keep if year==`year'
        drop if dividends==0 | dividends==.
        sort dividends
 
        local obs = _N
        local low_number = round(_N/10)
        local high_number = _N - `low_number'

        * Low portfolio Symbols
        forval aa=1/`low_number' {
        	local LP_symbols="`LP_symbols' " + symbol[`aa']
        }
 
        * High portfolio Symbols
        forval aa= `high_number' / `obs' {
        	local HP_symbols=" `HP_symbols' " + symbol[`aa']
        }

        * Let's see which companies are in each portfolio
        di "`LP_symbols'"
        di "`HP_symbols'"
 
        * Let's download the daily prices
        mfd_dm_prices `LP_symbols' `HP_symbols', freq(d) chg(ln) start(01jan`next_year')
 
        * Let's calculate the equally weighted LOW portfolio returns
        gen LP_portfolio_return = 0
        foreach company in `LP_symbols' {
        	replace LP_portfolio_return = LP_portfolio_return + ln_`company'
        }
        replace LP_portfolio_return = LP_portfolio_return / `low_number'
 
        * Let's calculate the equally weighted HIGH portfolio returns
        gen HP_portfolio_return = 0
        foreach company in `HP_symbols' {
        	replace HP_portfolio_return = HP_portfolio_return + ln_`company'
        }
        replace HP_portfolio_return = HP_portfolio_return / `low_number'
 
        * Now, we test
        noi: di "`next_year'"
        noi: ttest LP_portfolio_return = HP_portfolio_return
    }
}


*

IPO performance reasons

Category : Uncategorized

IPO performance

Educational purposes only…

Please make sure you have the most updated mfd_dm package for Stata installed for this post.

*
net from "http://www.researchforprofit.com/stata/mfd_dm"
* click on the blue mfd_dm package and then "click here to install" 
*
*
* Download the IPO dataset
clear all
cd "/users/mfd/desktop"
mfd_dm_ipo
gen year = substr(IPO_date_yahoo, 1, 4)
replace year = IPO_year_nasdaq if year==""
drop if year==""
keep Symbol year
destring year, replace
save ipo.dta, replace


* Testing IPO performance for 2014
clear all
cd "/users/mfd/desktop"
use ipo.dta, clear
keep if year==2014

* we dont need foreign stocks
drop if strpos(Symbol, ".")>0

levelsof Symbol, local(tickers)

foreach aa in `tickers' {
	qui {
		mfd_dm_prices `aa' ^GSPC, freq(d) chg(ln) start(01jan2014) end(31dec2015)
		capture: drop if adjclose_`aa'==.
		if (_rc==0) {
			gen first_price = adjclose_`aa' if _n==1
			gen period_1 = ln_`aa' if _n<=20
			gen period_3 = ln_`aa' if _n<=60
			gen period_6 = ln_`aa' if _n<=130
			gen period_12 = ln_`aa' if _n<=260

			gen period_1_sp500 = ln__GSPC if _n<=20
			gen period_3_sp500 = ln__GSPC if _n<=60
			gen period_6_sp500 = ln__GSPC if _n<=130
			gen period_12_sp500 = ln__GSPC if _n<=260

			collapse (sum) period* (mean) *_price
			gen Symbol="`aa'"
			sort Symbol			
			save temp0000001.dta, replace

			* number of shares
			mfd_dm_keystats `aa', field(s l1 j1)
			if (trim(Market_Capitalization)!="N/A") {
				gen temp=substr(Market_Capitalization,-1,1)
				replace Market_Capitalization=substr(Market_Capitalization,1,strlen(Market_Capitalization)-1)
				destring Market_Capitalization, replace
				replace Market_Capitalization=Market_Capitalization * 1000 if temp=="T" 
				replace Market_Capitalization=Market_Capitalization * 1000000 if temp=="M" 
				replace Market_Capitalization=Market_Capitalization * 1000000000 if temp=="B" 
				gen shares=Market_Capitalization/Last_Trade_Price
			}
			else {
				clear
				set obs 1
				gen Symbol="`aa'"
				gen shares=.
			}
			keep Symbol shares
			sort Symbol
			merge Symbol using temp0000001.dta
			drop _merge			
			order Symbol period_1 period_3 period_6 period_12 first_price shares			
			* number of shares
			erase temp0000001.dta
			 
			capture: append using ipo_performance_2014.dta
			save ipo_performance_2014.dta, replace
			noi: di "`aa' done."
		}
	}
}
use ipo_performance_2014.dta, clear
* RESULTING STATA FILE IS AVAILABLE VIA THE FOLLOWING LINK
use "http://researchforprofit.com/data_public/ipo_performance_2014.dta", clear
*

Empirical Test

*
clear all
cd "/users/mfd/desktop"
use "http://researchforprofit.com/data_public/ipo_performance_2014.dta", clear

gen excess_return_1 = period_1 - period_1_sp500
gen excess_return_3 = period_3 - period_3_sp500
gen excess_return_6 = period_6 - period_6_sp500
gen excess_return_12 = period_12 - period_12_sp500

gen mcap = ln(first_price * shares)
*

Does Market Capitalization matter in post-IPO 1-month return performance?

*
reg excess_return_1 mcap
*

Regression table

*
      Source |       SS       df       MS              Number of obs =     350
-------------+------------------------------           F(  1,   348) =    0.34
       Model |   .01037455     1   .01037455           Prob > F      =  0.5622
    Residual |  10.7298254   348  .030832831           R-squared     =  0.0010
-------------+------------------------------           Adj R-squared = -0.0019
       Total |  10.7401999   349  .030774212           Root MSE      =  .17559

------------------------------------------------------------------------------
excess_ret~1 |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
        mcap |   .0036938   .0063679     0.58   0.562    -.0088307    .0162183
       _cons |  -.0766529   .1289658    -0.59   0.553    -.3303033    .1769976
------------------------------------------------------------------------------
*

Does Market Capitalization matter in post-IPO 3-months return performance?

*
reg excess_return_3 mcap
*

Regression table

*
      Source |       SS       df       MS              Number of obs =     350
-------------+------------------------------           F(  1,   348) =    3.55
       Model |  .345886161     1  .345886161           Prob > F      =  0.0605
    Residual |  33.9263482   348  .097489506           R-squared     =  0.0101
-------------+------------------------------           Adj R-squared =  0.0072
       Total |  34.2722343   349  .098201244           Root MSE      =  .31223

------------------------------------------------------------------------------
excess_ret~3 |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
        mcap |   .0213285   .0113233     1.88   0.060    -.0009422    .0435991
       _cons |  -.4648056   .2293225    -2.03   0.043    -.9158381    -.013773
------------------------------------------------------------------------------
*

Does Market Capitalization matter in post-IPO 6-months return performance?

*
reg excess_return_6 mcap
*

Regression table

*
      Source |       SS       df       MS              Number of obs =     350
-------------+------------------------------           F(  1,   348) =    0.98
       Model |  .175696319     1  .175696319           Prob > F      =  0.3227
    Residual |  62.3432636   348  .179147309           R-squared     =  0.0028
-------------+------------------------------           Adj R-squared = -0.0001
       Total |  62.5189599   349  .179137421           Root MSE      =  .42326

------------------------------------------------------------------------------
excess_ret~6 |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
        mcap |   .0152011   .0153496     0.99   0.323    -.0149887    .0453908
       _cons |  -.3999731   .3108658    -1.29   0.199    -1.011385    .2114391
------------------------------------------------------------------------------
*

Does Market Capitalization matter in post-IPO 12-months return performance?

*
reg excess_return_12 mcap
*

Regression table

*
      Source |       SS       df       MS              Number of obs =     350
-------------+------------------------------           F(  1,   348) =    0.04
       Model |  .017882995     1  .017882995           Prob > F      =  0.8452
    Residual |  162.932779   348  .468197639           R-squared     =  0.0001
-------------+------------------------------           Adj R-squared = -0.0028
       Total |  162.950662   349   .46690734           Root MSE      =  .68425

------------------------------------------------------------------------------
excess_re~12 |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
        mcap |   .0048497   .0248146     0.20   0.845    -.0439558    .0536552
       _cons |  -.2872212   .5025536    -0.57   0.568    -1.275646    .7012034
------------------------------------------------------------------------------
*

Does first month's return matter in post-IPO 3-months return performance

*
reg excess_return_3 excess_return_1
*

Regression table

*
      Source |       SS       df       MS              Number of obs =     385
-------------+------------------------------           F(  1,   383) =  274.04
       Model |  15.3044018     1  15.3044018           Prob > F      =  0.0000
    Residual |  21.3893512   383   .05584687           R-squared     =  0.4171
-------------+------------------------------           Adj R-squared =  0.4156
       Total |   36.693753   384  .095556649           Root MSE      =  .23632

---------------------------------------------------------------------------------
excess_return_3 |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
----------------+----------------------------------------------------------------
excess_return_1 |    1.15937   .0700347    16.55   0.000     1.021669     1.29707
          _cons |  -.0315621   .0120481    -2.62   0.009    -.0552508   -.0078734
---------------------------------------------------------------------------------
*

Does first month's return matter in post-IPO 6-months return performance

*
reg excess_return_6 excess_return_1
*

Regression table

*
      Source |       SS       df       MS              Number of obs =     385
-------------+------------------------------           F(  1,   383) =  104.97
       Model |  14.0212267     1  14.0212267           Prob > F      =  0.0000
    Residual |  51.1597902   383  .133576476           R-squared     =  0.2151
-------------+------------------------------           Adj R-squared =  0.2131
       Total |   65.181017   384  .169742232           Root MSE      =  .36548

---------------------------------------------------------------------------------
excess_return_6 |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
----------------+----------------------------------------------------------------
excess_return_1 |   1.109703   .1083125    10.25   0.000     .8967413    1.322665
          _cons |  -.0874616    .018633    -4.69   0.000    -.1240974   -.0508258
---------------------------------------------------------------------------------
*

Does first month's return matter in post-IPO 12-months return performance

*
reg excess_return_12 excess_return_1
*

Regression table

*
      Source |       SS       df       MS              Number of obs =     385
-------------+------------------------------           F(  1,   383) =   77.45
       Model |  28.8596603     1  28.8596603           Prob > F      =  0.0000
    Residual |   142.71552   383  .372625379           R-squared     =  0.1682
-------------+------------------------------           Adj R-squared =  0.1660
       Total |   171.57518   384  .446810366           Root MSE      =  .61043

---------------------------------------------------------------------------------
excess_retur~12 |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
----------------+----------------------------------------------------------------
excess_return_1 |    1.59206   .1809047     8.80   0.000     1.236369    1.947751
          _cons |   -.182039   .0311211    -5.85   0.000    -.2432286   -.1208495
---------------------------------------------------------------------------------
*

State index calculation

Category : Uncategorized

Company profiles

Educational purposes only…

Please make sure you have the most updated mfd_dm package for Stata installed for this post.

*
net from "http://www.researchforprofit.com/stata/mfd_dm"
* click on the blue mfd_dm package and then "click here to install" 
*

Companies are grouped by state and a daily return index is created for each state. The index is value weighted and calculated at the end of each day.

*
clear all
cd "/users/mfd/desktop"
* mfd_dm_components_cnn
mfd_dm_components, symbol(^DJI)
levelsof Symbol, local(tickers)
mfd_dm_profile `tickers'
save profiles.dta, replace
* prices and market capitalizations
foreach aa in `tickers' {
	mfd_dm_keystats `aa', field(s l1 p j1) merge
	di "`aa' downloaded"
}
gen size = substr(Market_Capitalization,-1,1)
gen MCap = substr(Market_Capitalization,1,strlen(Market_Capitalization)-1)
drop Market_Capitalization
destring MCap, gen(Market_Capitalization)
replace Market_Capitalization = Market_Capitalization * 1000000000 if size=="B"
replace Market_Capitalization = Market_Capitalization * 1000000 if size=="M"
replace Market_Capitalization = Market_Capitalization * 1000 if size=="T"
drop MCap size

qui: summ Market_Capitalization
local total_mcap=r(sum)

gen return = (Last_Trade_Price - Previous_Close) / Previous_Close

* Total index calculation
gen weight = .
gen weighted_return = .
foreach aa in `tickers' {
	replace weight = Market_Capitalization / `total_mcap' if Symbol=="`aa'"
	replace weighted_return = return * weight
}
save profiles.dta, replace

qui: summ weighted_return
di "Down Jones index is: `r(sum)'"

* State by state index calculation
levelsof State, local(states)
gen weight_state=.
gen weighted_return_state=.
foreach aa in `states' {
	qui: summ Market_Capitalization if State=="`aa'"
	replace weight_state = r(sum)
	replace weighted_return_state = (Market_Capitalization / weight_state) * return
}
collapse (sum) state_index = weighted_return_state, by(State)
sort state_index
*

Options’ open interests

Category : Uncategorized

Options’ open interest

Open interests for options are important part of predictive analysis for stocks.
In this post, Stata code is provided for downloading the open interests for AAPL for multiple maturities.
Charts are intended for a simple visual comparison.

*
clear all
cd "/Users/mfd/Desktop"
fetchyahoooptions AAPL, m(2015-11-20 2015-11-27 2015-12-19 2015-12-31 2016-01-15 2016-02-19)

gen mini=1 if (strlen(Symbol) > strlen(Underlying) + 15 )
replace mini=0 if mini==.

gen contracts = Open_Interest * 100 if mini==0
replace contracts = Open_Interest * 10 if mini==1
replace contracts = contracts / 100

drop if Strike>Price*1.2
drop if Strike

When comparing charts: Please note that the scales are different.
One of the charts has 72000 contracts whereas another one has less than 5000.
So, monthly and weekly options may lead to incorrect implications.


Implied volatility (Stata, call/put option, multiple stocks, multiple maturities)

Category : Uncategorized

Implied volatility (Stata, call/put options, multiple stocks, multiple maturities)

Implied volatility of AAPL is downloaded and calculated as follows.

*
clear all
cd "/users/mfd/desktop"
fetchyahoooptions AAPL, m(2015-11-20 2015-11-27 2015-12-19 2015-12-31 2016-01-15 2016-02-19)

* Keep options within 50% of the current spot price

drop if Strike>Price*1.5
drop if Strike
                

Correlation, regression and causation (across country indices)

Category : Uncategorized

Correlation, regression and causation (across country indices)

The following Stata code calculates the correlation matrix for the market returns.

*
cd "/users/mfd/desktop"
mfd_dm_prices SPY ^FTSE ^GDAXI ^FCHI ^ATX ^AEX ^SSMI ^N225 000001.SS ^AORD ^BSESN, freq(d) chg(ln) start(01jan2014) end(31dec2014) 
correl ln*
*

The resulting correlation matrix is as follows.

*
(obs=203)

             |   ln_SPY ln__FTSE ln__GD~I ln__FCHI  ln__ATX  ln__AEX ln__SSMI ln__N225 ln_000~S ln__AORD ln__BS~N
-------------+---------------------------------------------------------------------------------------------------
      ln_SPY |   1.0000
    ln__FTSE |   0.5041   1.0000
   ln__GDAXI |   0.4976   0.8283   1.0000
    ln__FCHI |   0.5578   0.8482   0.9163   1.0000
     ln__ATX |   0.4505   0.6916   0.7452   0.7392   1.0000
     ln__AEX |   0.5389   0.8657   0.8966   0.9053   0.7409   1.0000
    ln__SSMI |   0.5039   0.7587   0.8166   0.8063   0.6847   0.8433   1.0000
    ln__N225 |   0.0729   0.1927   0.1275   0.1393   0.2372   0.2087   0.2612   1.0000
ln_000001_SS |  -0.0173   0.2158   0.1077   0.0937   0.1143   0.1361   0.0113   0.1100   1.0000
    ln__AORD |   0.0897   0.2761   0.1297   0.1363   0.2589   0.2042   0.2183   0.4174   0.2017   1.0000
   ln__BSESN |   0.1704   0.2747   0.2518   0.2537   0.2767   0.2955   0.2932   0.2938   0.1096   0.2772   1.0000
*

There seems to be high correlation between FCHI and AEX indices. Thus, we will review this relationship further, as we did in class.

*
reg ln__AEX ln__FCHI
*

The regression estimation results are as follows.

*
      Source |       SS       df       MS              Number of obs =     254
-------------+------------------------------           F(  1,   252) = 1262.52
       Model |  .016346197     1  .016346197           Prob > F      =  0.0000
    Residual |  .003262704   252  .000012947           R-squared     =  0.8336
-------------+------------------------------           Adj R-squared =  0.8330
       Total |  .019608902   253  .000077506           Root MSE      =   .0036

------------------------------------------------------------------------------
     ln__AEX |      Coef.   Std. Err.      t    P>|t|     [95% Conf. Interval]
-------------+----------------------------------------------------------------
    ln__FCHI |   .7911365   .0222655    35.53   0.000     .7472864    .8349866
       _cons |   .0002022   .0002258     0.90   0.371    -.0002424    .0006469
------------------------------------------------------------------------------
*

The results mean that the relationship between FCHI and AEX is statistically significant (P>|t|=0.000). They also mean that as FCHI move by 1%, AEX moves about 0.79% in the same direction. Furthermore, the variation in AEX index is explained 83.36% by the variations in FCHI.

How about causation?

Causation requires lagged effect. With the regression analysis, we have evaluated the contemporaneous relationship. With the causation analysis the evaluation has to be sequential: What happens in one market one day should be the cause for what happens in the other market the next day.

*
gwke82 ln__FCHI ln__AEX
*

The causality test results are as follows.

*
  +------------------------------------------------------------+
  |Granger Causation       |          Chi2|   df|       P-value|
  |------------------------+--------------+-----+--------------|
  |ln__FCHI -> ln__AEX     |        1.2634|    2|        0.5317|
  |------------------------+--------------+-----+--------------|
  |ln__AEX -> ln__FCHI     |        0.4808|    2|        0.7863|
  +------------------------------------------------------------+

  +------------------------------------------------------------+
  |Instantaneous feedback  |          Chi2|   df|       P-value|
  |------------------------+--------------+-----+--------------|
  |ln__FCHI <-> ln__AEX    |      287.6228|    1|        0.0000|
  +------------------------------------------------------------+

  +------------------------------------------------------------+
  |Total correlation       |          Chi2|   df|       P-value|
  |------------------------+--------------+-----+--------------|
  |ln__FCHI , ln__AEX      |      289.3669|    5|        0.0000|
  +------------------------------------------------------------+
*


PHP code snippets

Category : Uncategorized

PHP code snippets

String manipulation

Statistical

Yahoo! Finance related

Derivatives


RSI (Relative strength index)

Category : Uncategorized

RSI (Relative strength index)

Please make sure you have the most updated mfd_dm, mfd_ta and mfd_tex packages for Stata installed for this post.

*
net from "http://www.researchforprofit.com/stata/mfd_dm"
net from "http://www.researchforprofit.com/stata/mfd_ta"
net from "http://www.researchforprofit.com/stata/mfd_tex"
* click on the blue mfd_dm package and then "click here to install" 
*

One of many technical analysis tools is the relative strength index (RSI). Based on momentum trading arguments, RSI shows whether the stock is overbought or oversold.

*
clear all
cd "/users/mfd/desktop"
mfd_dm_prices FXE, freq(d) start(01jan2000) end(11nov2015) field(o c h l)

gen day=_n
tsset day

mfd_ta_RSI adjclose_FXE

tsline RSI14 if year(date)>2014
*

The resulting chart looks like the following.

RSI

Stata code for backtesting RSI for DJA components: 

*
clear all
cd "/Users/mfd/Desktop"

mfd_dm_components, symbol(^DJA) page(2)
drop if Symbol==""
levelsof Symbol, local(tickers)

local counter=1
foreach aa of local tickers {
	di "`counter': `aa'"
	clear
	capture: mfd_dm_prices `aa', freq(d) field(o c h l)
	gen day=_n
	tsset day
	mfd_ta_RSI adjclose_`aa'
	mfd_ta_RSI adjclose_`aa', backtest("20-80")
	capture: summ date
	if (_rc==0) { 
		if (`counter'!=1) append using RSI_backtest.dta
		save RSI_backtest.dta, replace
		local counter = `counter'+1	
	}
}

sort symbol date

save RSI_backtest.dta, replace

* all companies by year
clear all
cd "/Users/mfd/Desktop"
local counter=1
foreach aa in "L_profit" "L_profit_1p" "H_profit" "H_profit_1p" {
	di "`counter': `aa'"
	qui: {
		use RSI_backtest.dta, clear
		gen year=year(date)
		collapse (mean) `aa'_mean=`aa' (semean) `aa'_semean=`aa' (count) `aa'_N=`aa', by(year)
		gen `aa'_t=`aa'_mean/`aa'_semean
		gen `aa'_pval=2*ttail(`aa'_N,abs(`aa'_t)) 
		gen `aa'_star=""
		replace `aa'_star="*" if `aa'_pval<=0.10
		replace `aa'_star="**" if `aa'_pval<=0.05
		replace `aa'_star="***" if `aa'_pval<=0.01		
		keep year `aa'_mean `aa'_star `aa'_semean
		order year `aa'_mean `aa'_star `aa'_semean
		sort year
		if (`counter'!=1) {
			merge year using stats.dta
			drop _merge
			sort year
		}
		save stats.dta, replace
		local counter = `counter'+1		
	}
}

* by symbol year
clear all
cd "/Users/mfd/Desktop"
local counter=1
foreach aa in "L_profit" "L_profit_1p" "H_profit" "H_profit_1p" {
	di "`counter': `aa'"
	qui: {
		use RSI_backtest.dta, clear
		gen year=year(date)
		collapse (mean) `aa'_mean=`aa' (semean) `aa'_semean=`aa' (count) `aa'_N=`aa', by(symbol year)
		gen `aa'_t=`aa'_mean/`aa'_semean
		gen `aa'_pval=2*ttail(`aa'_N,abs(`aa'_t)) 
		gen `aa'_star=""
		replace `aa'_star="*" if `aa'_pval<=0.10
		replace `aa'_star="**" if `aa'_pval<=0.05
		replace `aa'_star="***" if `aa'_pval<=0.01		
		keep symbol year `aa'_mean `aa'_star `aa'_semean
		order symbol year `aa'_mean `aa'_star `aa'_semean
		sort symbol year
		if (`counter'!=1) {
			merge symbol year using stats.dta
			drop _merge
			sort symbol year
		}
		save stats.dta, replace
		local counter = `counter'+1		
	}
}
*

 


Moving average (MA)

Category : Uncategorized

Moving average (MA)

Please make sure you have the most updated mfd_dm and mfd_ta packages for Stata installed for this post.

*
net from "http://www.researchforprofit.com/stata/mfd_dm"
net from "http://www.researchforprofit.com/stata/mfd_ta"
* click on the blue mfd_dm package and then "click here to install" 
*

Moving averages are the foundations of technical analysis and they are used extensively.
They are actually simple but needed to provide a reference for future technical analysis posts.

*
clear all
cd "/users/mfd/desktop"
mfd_dm_prices AAPL, freq(d) start(01jan2013) end(31dec2013) field(c)
label variable close_AAPL "AAPL daily close"

gen day=_n
tsset day

* simple moving average
mfd_ta_MA adjclose_AAPL, period(10) ma_type(sma)

* exponential moving average
mfd_ta_MA adjclose_AAPL, period(10) ma_type(ema)

tsline close_AAPL sma10_AAPL ema10_AAPL
*

Different durations: 

*
clear all
cd "/users/mfd/desktop"
mfd_dm_prices AAPL, freq(d) start(01jan2011)end(31dec2013) field(c)
label variable close_AAPL "AAPL daily close"

gen day=_n
tsset day

forval aa=10(10)200 {
	* simple moving average
	mfd_ta_MA adjclose_AAPL, period(`aa') ma_type(sma)

	* exponential moving average
	mfd_ta_MA adjclose_AAPL, period(`aa') ma_type(ema)
}

* tsline close_AAPL sma50_AAPL sma100_AAPL sma150_AAPL sma200_AAPL ema50_AAPL ema100_AAPL ema150_AAPL ema200_AAPL if year(date)==2013 & month(date)>3

keep if _n==_N
xpose, clear varname
drop if _n<5
rename v1 price
rename _varname MA
order MA

browse if substr(MA,1,1)=="s"
*

Here is how 10 days Simple Moving Average (SMA) and 10 days Exponential Moving Average (EMA) look on a chart.
sma10ema10

Crossovers

When short-term moving average goes above the longer term moving average, it is considered to be a bullish signal. 
When short-term moving average goes below the longer term moving average, it is considered to be a bearish signal.

*
* Short term cross-over
* Bullish: S/T goes above L/T
* Bearish: S/T goes below L/T
* S/T: 5  vs. L/T: 35 days
* S/T: 50 vs. L/T: 200 days
clear all
cd "/users/mfd/desktop"
mfd_dm_prices AAPL, freq(d) start(01jan2011)end(31dec2013) field(c)
label variable close_AAPL "AAPL daily close"

gen day=_n
tsset day

* simple moving average
local aa=5
local bb=`aa'-1
tssmooth ma sma`aa'_AAPL=close_AAPL, window(`bb' 1 0)
replace sma`aa'_AAPL=. if _n<`aa'
label variable sma`aa'_AAPL "SMA (`aa' days)"
* exponential moving average
gen multiplier= 2 / (`aa'+1)
gen ema`aa'_AAPL=sma`aa'_AAPL if _n==`aa'
replace ema`aa'_AAPL=(multiplier * (close_AAPL - L.ema`aa'_AAPL)) + L.ema`aa'_AAPL if _n>`aa'
label variable ema`aa'_AAPL "EMA (`aa' days)"
drop mul*

* simple moving average
local aa=35
local bb=`aa'-1
tssmooth ma sma`aa'_AAPL=close_AAPL, window(`bb' 1 0)
replace sma`aa'_AAPL=. if _n<`aa'
label variable sma`aa'_AAPL "SMA (`aa' days)"
* exponential moving average
gen multiplier= 2 / (`aa'+1)
gen ema`aa'_AAPL=sma`aa'_AAPL if _n==`aa'
replace ema`aa'_AAPL=(multiplier * (close_AAPL - L.ema`aa'_AAPL)) + L.ema`aa'_AAPL if _n>`aa'
label variable ema`aa'_AAPL "EMA (`aa' days)"
drop mul*

* simple moving average
local aa=50
local bb=`aa'-1
tssmooth ma sma`aa'_AAPL=close_AAPL, window(`bb' 1 0)
replace sma`aa'_AAPL=. if _n<`aa'
label variable sma`aa'_AAPL "SMA (`aa' days)"
* exponential moving average
gen multiplier= 2 / (`aa'+1)
gen ema`aa'_AAPL=sma`aa'_AAPL if _n==`aa'
replace ema`aa'_AAPL=(multiplier * (close_AAPL - L.ema`aa'_AAPL)) + L.ema`aa'_AAPL if _n>`aa'
label variable ema`aa'_AAPL "EMA (`aa' days)"
drop mul*

* simple moving average
local aa=200
local bb=`aa'-1
tssmooth ma sma`aa'_AAPL=close_AAPL, window(`bb' 1 0)
replace sma`aa'_AAPL=. if _n<`aa'
label variable sma`aa'_AAPL "SMA (`aa' days)"
* exponential moving average
gen multiplier= 2 / (`aa'+1)
gen ema`aa'_AAPL=sma`aa'_AAPL if _n==`aa'
replace ema`aa'_AAPL=(multiplier * (close_AAPL - L.ema`aa'_AAPL)) + L.ema`aa'_AAPL if _n>`aa'
label variable ema`aa'_AAPL "EMA (`aa' days)"
drop mul*

twoway (line ema5_AAPL date) (line ema35_AAPL date) if year(date)==2013
twoway (line sma5_AAPL date) (line sma35_AAPL date) if year(date)==2013

twoway (line ema50_AAPL date) (line ema200_AAPL date) if year(date)==2013
twoway (line sma50_AAPL date) (line sma200_AAPL date) if year(date)==2013
*

Short-term (5-35 days) looks like this:
ema5ema35

Long-term (50-200 days) looks like this:
ema50ema200

Golden cross: 10-50 SMA vs. 150-200SMA:

*
clear all
cd "/users/mfd/desktop"
mfd_dm_prices AAPL, freq(d) start(01jan2011)end(31dec2013) field(c)
label variable close_AAPL "AAPL daily close"
gen day=_n
tsset day

forval aa=10(10)200 {
	mfd_ta_MA close_AAPL, period(`aa') ma_type(sma)
}

twoway (line close_AAPL date) (line sma20_AAPL date) (line sma200_AAPL date), ylabel(#30, angle(horizontal) axis(1)) xlabel(#50, angle(vertical)) scale(.35) legend(on cols(5)) 
twoway (line sma20_AAPL date) (line sma200_AAPL date), ylabel(#30, angle(horizontal) axis(1)) xlabel(#50, angle(vertical)) scale(.35) legend(on cols(5)) 
twoway (line sma20_AAPL date) (line sma30_AAPL date) (line sma40_AAPL date) (line sma50_AAPL date) (line sma60_AAPL date) (line sma70_AAPL date) (line sma80_AAPL date) (line sma90_AAPL date) (line sma100_AAPL date) (line sma110_AAPL date) (line sma120_AAPL date) (line sma130_AAPL date) (line sma140_AAPL date) (line sma150_AAPL date) (line sma160_AAPL date) (line sma170_AAPL date) (line sma180_AAPL date) (line sma190_AAPL date) (line sma200_AAPL date), ylabel(#30, angle(horizontal) axis(1)) xlabel(#50, angle(vertical)) scale(.35) legend(on cols(5)) 
twoway (line sma20_AAPL date) (line sma30_AAPL date) (line sma40_AAPL date) (line sma50_AAPL date) (line sma150_AAPL date) (line sma160_AAPL date) (line sma170_AAPL date) (line sma180_AAPL date) (line sma190_AAPL date) (line sma200_AAPL date), ylabel(#30, angle(horizontal) axis(1)) xlabel(#50, angle(vertical)) scale(.35) legend(on cols(5)) 
graph export "chart_aapl_ma.png", replace
*

The resulting chart looks like the following.
golden_cross

We can also look at moving beta and R-squared and their moving averages: 

*
clear all
cd "/Users/mfd/Desktop"
mfd_dm_prices AAPL SPY QQQ, freq(d) chg(ln per) start(01jan2008) field(o c h l v)
gen day=_n
tsset day

local obs=_N

gen beta=.
gen r2=.
forval aa=41/`obs' {
	qui: reg ln_AAPL ln_SPY if _n>=(`aa'-40) & _n<=`aa'
	replace beta=_b[ln_SPY] if _n==`aa'
	replace r2=e(r2) if _n==`aa'	
}
drop if beta==.
twoway (line adjclose_AAPL date if year(date)==2013, yaxis(2)) (line beta date if year(date)==2013, xlabel(#30, angle(vertical)) scale(.70))
twoway (line adjclose_AAPL date if year(date)==2013, yaxis(2)) (line r2 date if year(date)==2013, xlabel(#30, angle(vertical)) scale(.70))
*

The resulting chart for the Beta looks like the following.
moving_beta

The resulting chart for the R-squared looks like the following.
ma_r2

Testing golden cross for all NYSE stocks: 

*
clear all
cd "/Users/mfd/Desktop"

mfd_tex, saving("NYSE_GC") custom("symbol,start,end,mean,sum,obs")

use "NYA.dta", clear
ds close*
foreach aa in `r(varlist)' {
	local symbol=substr(subinstr("`aa'","__","_",.),strpos(subinstr("`aa'","__","_",.),"_")+1,.)
	di "`symbol'"
	qui {
		mfd_ta_MA close_`symbol', period(20) ma_type(sma)
		mfd_ta_MA close_`symbol', period(200) ma_type(sma)
		gen GC_`symbol'=1 if (sma20_`symbol'>sma200_`symbol') & (L.sma20_`symbol'<=L.sma200_`symbol')
		gen return_`symbol'=ln_`symbol' if L.GC_`symbol'==1
		replace return_`symbol'=ln_`symbol' if L2.GC_`symbol'==1
		replace return_`symbol'=ln_`symbol' if L3.GC_`symbol'==1
		summ return_`symbol'
		local mean=r(mean)
		local sum=r(sum)
		local obs=r(N)
		summ date if ln_`symbol'!=.
		local first: di %td r(min)
		local last: di %td r(max)
		mfd_tex, saving("NYSE_GC") custom("`symbol',`first',`last',`mean',`sum',`obs'")
		drop sma* GC* return*
	}
}
insheet using NYSE_GC.tex, comma clear
gen outcome=1 if sum>0
replace outcome=0 if sum<0
tabstat mean sum outcome, stat(mean)
*

Screen Shot 2013-09-09 at 1.51.16 AM

 

Results:

Screen Shot 2013-09-09 at 1.52.21 AM

 


MACD (Moving average convergence divergence)

Category : Uncategorized

MACD (Moving average convergence divergence)

Please make sure you have the most updated mfd_dm and mfd_ta packages for Stata installed for this post.

*
net from "http://www.researchforprofit.com/stata/mfd_dm"
net from "http://www.researchforprofit.com/stata/mfd_ta"
* click on the blue mfd_dm package and then "click here to install" 
*

Moving Average Convergence and Divergence (MACD) is one of the common technical analysis tools that is based on momentum of the stock. It simply shows the trend by evaluating short term exponential moving average versus slightly longer term exponential moving average.

*
clear all
cd "/users/mfd/desktop"
mfd_dm_prices FXE, freq(d) start(01sep2013) end(11nov2015) field(c)
label variable close_FXE "FXE daily close"

gen day=_n
tsset day

mfd_ta_MACD adjclose_FXE

twoway (bar MACD_histogram date) (line MACD_line date) (line signal_line date)
*

The resulting chart looks like the following.
MACD

Important points

  1. Positive MACD means positive momentum.
  2. Negative MACD means negative momentum
  3. Bullish crossover: MACD goes above signal line
  4. Bearish crossover: MACD goes below signal line

Fibonacci retracement

Category : Uncategorized

Fibonacci retracement

Please make sure you have the most updated mfd_dm and mfd_ta packages for Stata installed for this post.

*
net from "http://www.researchforprofit.com/stata/mfd_dm"
net from "http://www.researchforprofit.com/stata/mfd_ta"
* click on the blue mfd_dm package and then "click here to install" 
*

Fibonacci sequence is famous. One of many uses of Fibonacci sequence is in financial technical analysis. After each increasing or decreasing trend, technical analysts expect a correction. This correction can be a new trend setter or simply mark resistance/support levels. Here, Stata code is provided for commonly used Fibonacci retracement levels: 23.6%, 38.2% and 61.8%. Along with these lines, 50% and 100% are also included.

Fibonacci retracement from a drop

*
clear all
cd "/users/mfd/desktop"
mfd_dm_prices AAPL, freq(d) start(01jan2013) end(31dec2013)

mfd_ta_fibonacci adjclose_AAPL, ret_from(low) high(103) low(123)
*

The resulting chart looks like the following.
fibonacci_from_drop

Fibonacci retracement from an increase

*
clear all
cd "/users/mfd/desktop"
mfd_dm_prices AAPL, freq(d) start(01jan2013) end(31dec2013)

mfd_ta_fibonacci adjclose_AAPL, ret_from(high) high(88) low(75)
*

The resulting chart looks like the following.
fibonacci_from_increase

Alternative method

*
clear all
cd "/Users/mfd/Desktop"
mfd_dm_prices AAPL, freq(d) chg(ln) start(01aug2012) field(o c h l v)
gen day=_n
tsset day
summ close_AAPL
local obs=_N
forval aa=1/`obs' {
    if close_AAPL[`aa']==r(min) local low=`aa' 
	if close_AAPL[`aa']==r(max) local high=`aa' 
}
di "low=`low' and high=`high'"
mfd_ta_fibonacci close_AAPL, ret_from(low) high(`high') low(`low')
*

SEC Edgar: Symbol => CIK (mfd_dm_SEC_CIK)

Category : Uncategorized

SEC Edgar: Symbol => CIK (mfd_dm_SEC_CIK)

Please make sure you have the most updated mfd_dm, mfd_ta and mfd_tex packages for Stata installed for this post.

*
net from "http://www.researchforprofit.com/stata/mfd_dm"
net from "http://www.researchforprofit.com/stata/mfd_ta"
net from "http://www.researchforprofit.com/stata/mfd_tex"
* click on the blue mfd_dm package and then "click here to install" 
*
*
clear all
cd "/users/mfd/desktop"
use "http://researchforprofit.com/data_public/profiles.dta", clear
levelsof Symbol, local(tickers)
mfd_dm_SEC_CIK `tickers'
* THE RESULTING DATASET IS AVAILABLE AT THE FOLLOWING LINK
use "http://researchforprofit.com/data_public/symbol_to_cik.dta", clear
*

ADO

*
program define mfd_dm_SEC_CIK, rclass
	
	version 10.0
	
	syntax anything(name=tickers)

	qui: {	
		foreach ticker in `tickers' {
			clear
			mata: get_CIK ("`ticker'")
			gen Symbol="`ticker'"
			compress
			capture: append using temp0000000000001.dta
			save temp0000000000001.dta, replace
			noi: di "CIK for `ticker' is: " cik[1]
		}
		erase temp0000000000001.dta
		sort Symbol
		order Symbol cik
	}
	
end



mata:
	void get_CIK (string scalar symbol)
	{
		icerik = file_get_contents("http://researchforprofit.com/posts/stata_edgar_cik.php?symbol=" + symbol)

		st_addvar("str244", "cik")
		st_addobs(1)
		st_sstore(.,"cik",icerik)
	}

	string file_get_contents (string scalar raw)
	{
		fh = fopen(raw, "r")
		raw=""
		while ((line=fget(fh))!=J(0,0,"")) {
			raw=raw+line
		}
		fclose(fh)
		return (raw)
	}
		
end
*