Posts tagged: programming

Code for Efficient Frontier, Global Minimum Variance Portfolio, Tangeng Portfolio

By , August 7, 2012 8:57 pm
/*
 * This pseudo-code class entails the risk and expected return values for efficient frontier
 * In real code, accessors and mutators should be provided
 */
class EfficientFrontier()
{
	float[] return;	// series of expected returns on efficient portfolios
	float[] risk;	// series of standard deviation of returns of efficient portfolios
	float gmvpReturn;	// expected return of Global Minimum Variance Portfolio
	float gmvpRisk;	// standard deviation of returns of Global Minimum Variance Portfolio
	float tangentReturn;		// expected return of the efficient portfolio tangent to Capital Market Line
	float tangentRisk;	// standard deviation of returns of the efficient portfolio tangent to Capital Market Line
	float shortConstraintMaxReturn;	// maximum expected return that an efficient portfolio can reach
	float shortConstraintMaxRisk;	// standard deviation of returns of the efficient portfolio with maxmimum return
}

/*
 * This pseudo-code function produces position of Markowitz Efficient Frontier
 */
EfficientFrontier getEfficientFrontier(float[][] price)
{
	const float c1 = 0.1;	// first substitute of risk-free rate for Black's shortcut
	const float c2 = 0.2;	// second substitute of risk-free rate for Black's shortcut
	float[] annualReturn = annualReturn(price);
	float[][] annualVarcovar = annualVarcovarMatrix(price);
	annualVarcovar = InverseMatrix(annualVarcovar);

	for (i = 0 ; i < NUMBER_OF_VARIABLES ; i++)
	{
		for (j = 0 ; j < NUMBER_OF_VARIABLES ; j++)
		{
			z1[i] += annualVarcovar[i][j] * (annualReturn[j] - c1);
		}
		sumz1 += z1[i];
		x1[i] = z1[i] / sumz1;
	}

	// repeat for z2 & x2;

	float expectedReturn1, expectedReturn2;

	for (i = 0 ; i < NUMBER_OF_VARIABLES ; i++)	// calculate expected return
	{
		expectedReturn1 += annualReturn[i] * x[i];
	}

	// repeat for expectedReturn2;

	variance1 = z1[] * annualVarcovar * z1[];	// this is a shorthand for tri-matrices multiplication. Actual code should extend the calculation of matrix multiplication

	// repeat for variance2;

	covariance = z1[] * annualVarcovar * z2[];

	return = discreteReturn(price);
	risk = stdDev(price);

	for (i = 0 ; i < NUMBER_OF_OBSERVATIONS ; i++)
	{
		if (maxReturn < return[i])	maxReturn = return[i];
		if (maxRisk < risk[i])	maxRisk = risk[i];
		// the maximum return and standard deviation here are not exactly value due to limitation of the method
	}

	do
	{
		w2 = 1 - w1;	// rebalance the two asset portfolio
		EfficientFrontier.return[i] = w1 * expectedReturn1;	// for demonstration only, a mutator should be used
		EfficientFrontier.risk[i] = (w1^2 * variance1 + w2^2 * variance2 + 2 * w1 * w2 * covariance)^(1/2);	// for demonstration only, a mutator should be used
		w1 += INCREMENT;
		i++;
	}
	while(EfficientFrontier.return[i] <= maxReturn);	// for demonstration only, an accessor should be used
}

/*
 * Global Minimum Variance Portfolio
 */

	gmvpWeight1 = (variance2 - covariance) / (variance1 + variance2 + 2 * 

covariance);	// Bodie Kane Marcus Investments 8e page 204
	gmvpWeight2 = 1 - gmvpWeight1;
	EfficientFrontier.gmvpReturn = gmvpWeight1 * expectedReturn1 + 

gmvpWeight2 * expectedReturn2;
	EfficientFrontier.gmvpRisk = (gmvpWeight1^2 * variance1 + gmvpWeight2^2 * 

variance2 + 2 * gmvpWeight1 * gmvpWeight2 * covariance)^(1/2);

	tangentWeight1=(expectedExcessReturn1*variance2-

expectedExcessReturn1*covariance)/

(expectedExcessReturn1*variance2+expectedExcessReturn2*variance1-

(expectedExcessReturn1+expectedExcessReturn2)*covariance);
	// Bodie Kane Marcus Investments 8e page 207
	tangentWeight2 = 1 - tangentWeight1;
	EfficientFrontier.gmvpReturn = tangentWeight1 * expectedReturn1 + 

tangentWeight2 * expectedReturn2;
	EfficientFrontier.gmvpRisk = (tangentWeight1^2 * variance1 + 

tangentWeight2^2 * variance2 + 2 * tangentWeight1 * tangentWeight2 * covariance)^

(1/2);

	return EfficientFrontier;

Monte Carlo method for Option Pricing: Pseudo-Code

By , June 25, 2012 1:44 pm
/*
 * Pseudo-code
 * Monte Carlo method for option pricing
 */

double S;	// price of underlying asset
double r;	// interest rate
double sigma;	// volatility
double t;	// time to maturity
double X;	// exercise price
double n;	// number of simulations
double i;	// loop parameter

/*
 * Code to get the variables from user input
 */

/*
 * Function to retrieve lognormal random variable
 */
double getLognormalRandomVariable(S, r, sigma, t)
{
	return S * exp( (r - 0.5 * sigma ^2) * t + sigma * sqrt(t) );
}

/*
 * Pricing European Call option
 */
double R;
double sd;
double St;
double sumPayoff = 0;

double  getEuropeanCallPrice(S, X, r, sigma, t, n)
{
	R = (r - 0.5 * sigma ^ 2) * t;
	sd = sigma * sqrt(t);

	for (i = 0 ; i < n ; i++)
	{
		St = S * exp (R + sd * randomNormal() );
		sumPayoff += max (0, St - X);
	}
	return exp (-r * t) * (sumPayoff / n);
}

/*
 * Calculate Delta
 */
double q;
double c;
double cq;
double sumPayOffQ = 0;

double getEuropeanCallDelta(S, X, r, sigma, t, n)
{
	q = S * 0.01;

	for (i = 0 ; i < n ; i++)
	{
		St = S * exp (R + sd * randomNormal() );
		sumPayoff += max (0, St - X);
		Stq = (S + q) * exp (R + sd * randomNormal() );
		sumPayoffQ += max (0, Stq - X);
	}
	c = exp (-r * t) * (sumPayoff / n);
	cq = exp (-r * t) * (sumPayoffQ / n);
	return (cq - c) / q;
}

double[] motions;

double[] getBrownianMotion (S, r, sigma, t)
{
	motions = new double[n];

	for (i = 0 ; i

Value-at-Risk using Wolfram historical volatility

By , August 9, 2011 6:58 pm

WolframAlpha offers a Value-at-Risk calculation method basing on past volatility.

This entry attempts to replicate this method.

My attempt adheres to Basel II requirements: daily VaR on 10-day horizon with 99% confidence

I construct a hypothetical portfolio including the following stocks: Cisco (CSCO), Microsoft (MSFT), IBM (IBM), American Express (AXP). The portfolio is equally weighted. Data are downloaded from Wharton Research Data Services.

This graph projects daily VaR for 2006 (before the turbulence caused by the GFC) and the ex post portfolio daily profit/loss. While passing backtesting, this method produces very high VaR estimates, leading to large reserve locked in.

I use Doornik Ox programming language for solving this problem. Volatility is from Hull method.

/* * Wolfram.ox * generate VaR, portfolio loss and efficiency using Wolfram volatility approach */

#include var.h

const decl fileName = "Wolfram.out";const decl portfolioFile = "realv.csv";

main(){	ranseed(967537412);

	decl price;	decl r;	decl rmean,rsum;	decl value=portfolioValue2;	decl var=0;	decl volatility;	decl probability;	decl portfolio;	decl exceptions=0;	decl i,j;

	price = new matrix[observations2][numberOfAssets2];	price = loadmat(sourceFileAll);	portfolio = new matrix[tradingDaysIn2006][1];	portfolio = loadmat(portfolioFile);	r = new matrix[observations2][numberOfAssets2];	rmean = new matrix[tradingDaysIn2006][1];	rsum = new matrix[tradingDaysIn2006][1];	volatility = new matrix[tradingDaysIn2006][1];	var = new matrix[tradingDaysIn2006][1];	probability = new matrix[tradingDaysIn2006][1];

	// Calculate mean return of observed period	for (i = 1 ; i < observations2 ; i++)	{		for (j = 0 ; j < numberOfAssets2 ; j++)		{			r[i][j] = log(price[i][j]/price[i-1][j]);		}		r[i][0] /= numberOfAssets2;	// calculate portfolio return to the column	}

	// Calculate volatility of observed period	for (i = 0 ; i < tradingDaysIn2006 ; i++)	{		for (j = 0 ; j < goBackDays ; j++)		{			rmean[i][0] += r[j+i][0];		}		rmean[i][0] /= goBackDays;	}

	for (i = 0 ; i < tradingDaysIn2006 ; i++)	{		for (j = 0 ; j < goBackDays ; j++)		{			rsum[i][0] += (r[j+i][0] - rmean[i][0])^2;		}	}

	for (i = 0 ; i < tradingDaysIn2006 ; i++)	{		volatility[i][0] = sqrt(1/(goBackDays-1) * rsum[i][0]);	}

	// Estimate VaR	for (i = 0 ; i < tradingDaysIn2006 ; i++)	{		while(probability[i][0] < p)		{			probability[i][0] = 1/2 * erf((rmean[i][0] + log(value) - log(value - var[i][0])) / (volatility[i][0] * sqrt(2 * 1)));			var[i][0] += 1;		}		var[i][0] = var[i][0] * (goBackDays - 1);	}

	// Backtest VaR	for (i = 0 ; i < tradingDaysIn2006 - 1 ; i++)	{		if (portfolio[i][0] > var[i][0])		{			exceptions++;		}	}

	while (exceptions > tradingDaysIn2006 * p)	{		exceptions = 0;		for (i = 0 ; i < tradingDaysIn2006 - 1 ; i++)		{			var[i][0]++;			if (portfolio[i][0] > var[i][0])			{				exceptions++;			}		}	}

	file = fopen(fileName,"w");	for (i = 0 ; i < tradingDaysIn2006 ; i++)	{		fprint(file, var[i][0],"\n");	}	fclose(file);}

The Excel equivalent method is by using ERFC() function combined with Solver.

Further research may be extended to:

  • Different portfolio construction
  • Efficient portfolio construction
  • Historical observation optimization
  • Different volatility estimates
  • Compare with other methods e.g. Variance-Covariance, Historical Simulation, Monte-Carlo

Reference

Philippe Jorion, Value at Risk, 3rd Ed.: The New Benchmark for Managing Financial Risk

Jonathan Reeves, FINS5542 Course Notes, School of Banking and Finance, Australian School of Business, University of New South Wales

John Hull, Options, Futures, and other Derivatives, 7th Ed

Spreading the word for BarCamp Hanoi 2009

By , April 10, 2009 12:59 pm

BarCamp Hanoi

Barcamp Hanoi 2009 will be held on April 19, from 8.30 AM to 5.00 PM at RMIT International University, Hanoi campus – 2/2C Van Phuc Compound, Kim Ma street, Hanoi.

Topics may include, but are not limited to: online services, social media, startups, UI design, entrepreneurship, VC, Web 2.0 technologies, online marketing, online advertising, online payment, e-commerce, open source software, hardware hacking, robotics, mobile computing, bioinformatics, programming languages, even the future of technology or global issues.

REGISTER FREE HERE: http://www.barcamphanoi.org/?page_id=10&lang=en
WANT TO SPONSOR US: http://www.barcamphanoi.org/?page_id=12&lang=en

As a part of the community building process, we’re looking for people to help spread the word about the event.

SO WHAT CAN YOU DO?

* Add a badge to your websites or blogs (http://www.barcamphanoi.org/?page_id=130&lang=en)
* Write blog entries about Barcamp and Barcamp Hanoi 2009 (What is Barcamp?, Information about Barcamp Hanoi 2009, Sponsor for Barcamp Hanoi,…)
* Spread information about Barcamp Hanoi 2009 to people who may concern, maybe via IM, Discussion groups, Email, Twitter, Facebook,…

That would help us alot and make Barcamp Hanoi even more successful.

Thank you so much, we greatly appreciate what you do for Barcamp Hanoi.

***

Hội thảo công nghệ mở Barcamp Hanoi 2009 sẽ được tổ chức vào ngày 19/4, từ 8.30 sáng đến 5.00 chiều tại trường Đại học Quốc tế RMIT, cơ sở Hà Nội – 2/2C khu Ngoại giao đoàn Vạn Phúc, đường Kim Mã, Hà Nội.

Chủ đề không giới hạn, có thể bao gồm: Dịch vụ trực tuyến, social media, startups, thiết kế giao diện người dùng, entrepreneurship, Đầu tư mạo hiểm, Các công nghệ Web 2.0, marketing trực tuyến, quảng cáo trực tuyến, thanh toán trực tuyến, thương mại điện tử, phần mềm mã nguồn mở, hardware hacking, robotics, mobile computing, bioinformatics, các ngôn ngữ lập trình, công nghệ tương lai, các vấn đề toàn cầu…

ĐĂNG KÝ THAM DỰ TỰ DO TẠI ĐÂY: http://www.barcamphanoi.org/?page_id=10
TÀI TRỢ CHO SỰ KIỆN NÀY: http://www.barcamphanoi.org/?page_id=12

Là một phần của quá trình xây dựng cộng đồng, rất mong các bạn giúp đỡ quảng bá sự kiện này đến những người quan tâm.

BẠN CÓ THỂ LÀM GÌ ĐỂ GIÚP ĐỠ BARCAMP HANOI?

* Thêm phù hiệu Barcamp Hanoi vào website hay blog của bạn. (http://www.barcamphanoi.org/?page_id=130)
* Viết blog về Barcamp Hanoi (Barcamp là gì?, Thông tin về Barcamp Hanoi 2009, Tài trợ cho Barcamp Hanoi,…)
* Gửi địa chỉ trang web này và giới thiệu với những người có thể quan tâm, có thể qua Yahoo! Messenger, Email, Forum, Twitter, Facebook,…

Việc này sẽ giúp những người tổ chức rất nhiều và làm cho sự kiện thành công hơn nữa.

Cảm ơn các bạn, chúng tôi thật sự rất cảm kích những gì bạn làm cho Barcamp Hanoi.

Write “Hello User” Facebook Application using PHP

By , October 20, 2007 12:55 am

1. Install Facebook Developer Application

Add The Facebook Developer Application

2. Install PHP Facebook API Client Library

Facebook API

Unzip the library into a web folder that is accessible by your PHP scripts.

3. Creating Your Application Profile And API Key

  1. Go to the developer panel, click “Set Up New Application”.
  2. Input application name
  3. Go to “Optional Fields”, input “Callback Url” with the location of your script. This is the public URL on your webserver where the Facebook application will be.
  4. Input “Canvas Page URL”. This is your application URL within Facebook. The application named “Hello World” would make the full URL http://apps.facebook.com/helloworld
  5. “Can your application be added on Facebook?” => “Yes”
  6. Check “Developer Mode” checkbox until you have completed the application.
  7. Under “Integration Points” fill out “Side Nav URL” with the full “Canvas Page URL” http://apps.facebook.com/helloworld. This allows users to add your application to their Facebook left side bar navigation.
  8. Obtain the API Key and Secrete

4. Hello Facebook!

<?php
require_once('facebook/client/facebook.php');/* initialize the facebook API with your application API Key and Secrete */
$facebook = new Facebook(YOUR_API_KEY,YOUR_SECRETE_CODE);?>
Hello <fb:name uid='<?php echo $fb_user; ?>' useyou='false' possessive='true' />! Welcome to Facebook application!

And there, we’re done!

Panorama Theme by Themocracy