Posts tagged: code

10 August 2017, Index Futures on HOSE

By , August 10, 2017 3:24 am

Trước giờ Hợp Đồng Giao Sau Chỉ Số chính thức đi vào hoạt động.

1. VN30 đầu ngày 741.36, cuối ngày 743.42.

Trần – Sàn – Tham Chiếu – Cuối Ngày

VN30F1708 – 811 – 705 – 758 – 745.9
VN30F1709 – 809.3 – 703.5 – 756.4 – 749.1
VN30F1712 – 804.7 – 699.5 – 752.1 – 755
VN30F1803 – 800.4 – 695.8 – 748.1 – 758

Open Interest dịch là Khối Lượng Tích Luỹ dễ hiểu.

2. Ngoài áp lực chốt lãi T+ equity thường có thì giờ còn có áp lực đến ngày đáo hạn (maturity / expiry) của Futures.

3. Value at Risk VN30 Futures theo yêu cầu Basel III = VND 3,696,661

Rất thấp do implied volatility.

Có 4 phương pháp cổ điển tính VaR: (1) Linear Probabilistic (2) Complementary Error Function erfc (3) Normality (4) Monte Carlo Simulation. Pseudo-code cuối bài.

4. 3 yếu tố ảnh hưởng chính đến VN30 Futures: lãi suất, dividend yield, thời gian đến đáo hạn (time to maturity).

Mối liên quan đơn giản nhất là: F = Se^[(r-q)t]

VN30 = SIGMA(PiSifi) / Cap(i) * Zi

Tử số là tổng giá trị vốn hoá của các cổ phiếu tham gia sau khi điều chỉnh free float.
Z: điều chỉnh trường hợp vượt quá tỉ trọng cho phép.

5. Dividend yield hiện tại đang là 2.81%.

6. PE 12.88

7. Vốn hoá VND 1,147,725,989,265,190
Index Point đang được thị trường định giá VND 1,548,135,843,942

8. Dữ liệu lịch sử VN30:

Mean = 0.00048807
Standard Error = 0.000283514
Median = 0.0007096
Mode = 0
Standard Deviation = 0.013124581
Sample Variance = 0.000172255
Kurtosis = 1.920261699
Skewness = -0.060551087
Range = 0.103634608
Minimum = -0.056110646
Maximum = 0.047523962
Count = 2143
Confidence Level (99.0%) = 0.000730935
Mean dương là do horizon bias.

9. Sau 17 năm, lần đầu tiên chúng ta có sản phẩm đánh xuống (Bearish) hợp pháp và công khai và chính thức.

Dùng dữ liệu lịch sử chắc chắn bị chúng khinh là chưa chắc dự đoán được tương lai. Mà lỡ không biết làm thế nào cho hay mà đang bị dí báo cáo thì có nhiêu sống bấy nhiêu thôi.

/** Linear Probabilistic */
for (i = 0 ; i < n-1 ; i++)
{
	r[i] = p[i+1] / p[i] - 1;
	sumr += r[i];
}

muyr = sumr / n;

for (i = 0 ; i < n-1 ; i++)
{
	varianceNum += (r[i] - muyr) ^ 2;
}

vol = sqrt(varianceNum / (n-2));

VaR = getCriticalValue(confidence) * sqrt(multiplyMatrix(multiplyMatrix(w[n]*vol[n], varCov[n][n]),transposeMatrix(w[n]*vol[n]))) * sqrt(BaselForecast / tradingDays);

/** Complementary Error Function */

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

/** Normality */
for (i = 0 ; i < numberOfAssets1 ; i++)
{
	weight[i][0] = securityValue1 / (pdt[startPeriod1][i]);
}

for (i = 0 ; i < a ; i++)
{
	pdtdfu = pdtdf[(startBack1+i):(startPeriod1+i)][];
	pdtdfuv = variance(pdtdfu);
	pdtdfuvf = weight' * pdtdfuv * weight;
	meanp = meanc(pdtdfu);
	var = (-1 * horizon) * weight' * (meanp') - (zValueOnePercent * sqrt(horizon*pdtdfuvf));
	realv = ( (pdt[startPeriod1+i][]) * weight) - ( (pdt[startPeriod1+i+horizon][]) * weight );
	efficiency = -realv / var;
	fprint(file, var,"\t",realv,"\t",efficiency,"\n");
}

/** Monte Carlo Simulation */
for (i = 0 ; i < numberOfAssets1 ; i++)
{
	weight[i][0] = securityValue1 / (pdt[startPeriod1][i]);
}

for (i = 0 ; i < numberOfTradingDays ; i++)
{
	for (b = 0 ; b < repeatB ; b++)
	{
		portrl = pdt[startPeriod1+i][] + pdtdf[startBack1+i+(ranu(1,1)*scaleMultiplier)][];
		for (j = 0 ; j < repeatDeltaP ; j++)
		{
			portrl += pdtdf[startBack1+i+(ranu(1,1)*scaleMultiplier)][];
		}
		portrlv[b][0] = weight' * (portrl)';
	}
	portq = quantilec(portrlv, mq);
	var = ((pdt[startPeriod1+i][]) * weight) - portq[0][0];
	realv = ((pdt[startPeriod1+i][]) * weight) - ((pdt[startPeriod1+i+horizon][]) * weight);
	efficiency = -realv / var;
	fprint(file, var,"\t",realv,"\t",efficiency,"\n");
}

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

Support Tim O'Reilly with a Blogger's Code of Conduct

By , September 4, 2007 4:52 am

Problems of the blogosphere

Anonymity

Anonymity on the web

Anonymity on the web makes people believe that they don’t have to be responsible for what they write. Therefore, many behave on the web in ways that they would not otherwise. Some sp.am, some attack other people, some abuse technology for their own goods while degrading other’s efforts.

sp.am

Comment sp.am

sp.ams in comments is another method of sending irrelevant, unwanted commercial messages to blogs.

Some sp.amme.rs use comment sp.am as a way to increase their websites’ PageRank by including URL to their website.

sp.am is often done by automated software.

SplogSpot

Splog

sp.am blogs, sometimes referred to by the neologism splogs, are artificially created weblog sites which the author uses to promote affiliated websites or to increase the search engine rankings of associated sites. The purpose of a splog can be to increase the PageRank or backlink portfolio of affiliate websites, to artificially inflate paid ad impressions from visitors, and/or use the blog as a link outlet to get new sites indexed. sp.am blogs are usually a type of scraper site, where content is often either Inauthentic Text or merely stolen (see blog scraping) from other websites. These blogs usually contain a high number of links to sites associated with the splog creator which are often disreputable or otherwise useless websites.

Stop Cyberbully

Cyber bullying

Cyber bullying is a type of harassment via electronic messages. Cyber bullying may also include threats, sexual remarks, pejorative labels (i.e., hate speech). Cyber bullies may publish personal contact information for their victims at websites. They may attempt to assume the identity of a victim for the purpose of publishing material in their name that defames or ridicules them.

Cyber bullying via blogs

Recently, Kathy Sierra, a web designer, was threatened by a commenter at her blog Headrush.

Other forms that blog cyber-bullying can take are the creation of fake blogs in the name of a victim which purport to be by the victim but which ridicule him or her. Such sites may use vulgarity, por.nogr.aphy and other forms of inflammatory discourse in an attempt to shame the victim.

Troll

Troll

Trolls can be existing members of a community that often contribute no useful information to the thread, but instead make argumentative posts in an attempt to discredit another person, concentrating almost exclusively on facts irrelevant to the point of the conversation, with the intent of provoking a reaction from others. The key element under attack by a troll is known only to the troll.

A troll’s main goal is usually to arouse anger and frustration among the message board’s other participants, and will write whatever it takes to achieve this end. One popular trolling strategy is the practice of Winning by Losing. While the victim is trying to put forward solid and convincing facts to prove his position, the troll’s only goal is to infuriate its prey. The troll takes (what it knows to be) a badly flawed, wholly illogical argument, and then vigorously defends it while mocking and insulting its prey. The troll looks like a complete fool, but this is all part of the plan. The victim becomes noticeably angry by trying to repeatedly explain the flaws of the troll’s argument. Provoking this anger was the troll’s one and only goal from the very beginning.

A concern troll is a pseudonym created by a user whose point of view is opposed to the one his/her sockpuppet claims to hold. The concern troll posts in web forums devoted to its declared point of view (for example, Democrats or fans of the Prius), and attempts to sway the group’s actions or opinions while claiming to share their goals but with some “concerns”. The goal is to sow fear, uncertainty and doubt within the group.

Do not feed the troll Experienced participants in online forums know that the most effective way to discourage a troll is usually to ignore him or her, because responding encourages a true troll to continue disruptive posts — hence the often-seen warning “Please do not feed the troll”.

Illustration: Troll’s Brain and Memory

Dooce Logo

Dooce

To be “dooced” is to lose one’s job as a result of something one wrote on the internet.

This neologism is formed from the true story of Heather B. Armstrong’s website dooce.com in 2002.

Legal issues

Apart from being a web user, a member of communities, an author, you are also a citizen, and are bound to the law of your region and the Terms of Service of the blogging service you are using.

A behavior deemed acceptable in a community may violate the legal code of the place you’re residing. Be careful.

Tim O’Reilly calls for a Blogger’s Code of Conduct

Tim O’Reilly is calling for a Blogger’s Code of Conduct. Civility Enforced

Tim O’Reilly Draft Blogger’s Code of Conduct

Tim hopes that it would come through self-regulation.

It is still under development. The latest version of his draft contains 6 points.

I believe that his attempt, while will not solve all problems of the blogosphere, will address the issues and raise the awareness of bloggers worldwide so that we can eradicate the bad seeds together.

Panorama Theme by Themocracy