[Returnanalytics-commits] r2567 - pkg/PerformanceAnalytics/sandbox/pulkit/week3/code

noreply at r-forge.r-project.org noreply at r-forge.r-project.org
Sat Jul 13 22:35:03 CEST 2013


Author: pulkit
Date: 2013-07-13 22:35:03 +0200 (Sat, 13 Jul 2013)
New Revision: 2567

Added:
   pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/DD2.py
   pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/DD3.py
   pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/data1.csv
   pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/run.py
Log:
Python code for Triple Penance

Added: pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/DD2.py
===================================================================
--- pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/DD2.py	                        (rev 0)
+++ pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/DD2.py	2013-07-13 20:35:03 UTC (rev 2567)
@@ -0,0 +1,70 @@
+#!/usr/bin/env python
+# On 20121230
+# Get maximum drawdown
+# by MLdP <lopezdeprado at lbl.gov>
+from scipy.stats import norm
+#---------------------------------------------------------------
+def main():
+	#1) Parameters
+	phi=.5 # AR(1) coefficient
+	mu=1 # unconditional mean
+	sigma=2 # Standard deviation of the random shock
+	dPi0=1 # Bet at origin (initialization of AR(1))
+	confidence=.95 # Confidence level for quantile
+	#2) Compute MinQ
+	t,minQ=getMinQ(phi,mu,sigma,dPi0,confidence)
+	print 'MinQ = '+str(minQ)
+	print 'Time at MinQ = '+str(t)
+	print 'MaxDD = '+str(max(0,-minQ))
+	return
+#---------------------------------------------------------------
+def getMinQ(phi,mu,sigma,dPi0,confidence):
+	# Compute MinQ
+	q,bets=0,0
+	#1) Determine extremes of search
+	while not q>0:
+		bets+=1
+		q=getQ(bets,phi,mu,sigma,dPi0,confidence)
+	#2) Compute min of q
+	kargs={'args':(phi,mu,sigma,dPi0,confidence)}
+	t,minQ=goldenSection(getQ,0,bets,**kargs)
+	return t,minQ
+#---------------------------------------------------------------
+def getQ(bets,phi,mu,sigma,dPi0,confidence):
+	# Compute analytical solution to quantile
+	#1) Mean
+	mean=(phi**(bets+1)-phi)/(1-phi)*(dPi0-mu)+mu*bets
+	#2) Variance
+	var=sigma**2/(phi-1)**2
+	var*=(phi**(2*(bets+1))-1)/(phi**2-1)-2*(phi**(bets+1)-1)/(phi-1)+bets+1
+	#3) Quantile
+	q=mean+norm.ppf(1-confidence,0,1)*var**.5
+	return q
+#---------------------------------------------------------------
+def goldenSection(obj,a,b,**kargs):
+	# Golden section method. Maximum if kargs['minimum']==False is passed 
+	from math import log,ceil
+	tol,sign,args=1.0e-9,1,None
+	if 'minimum' in kargs and kargs['minimum']==False:sign=-1
+	if 'args' in kargs:args=kargs['args']
+	numIter=int(ceil(-2.078087*log(tol/abs(b-a))))
+	r=0.618033989
+	c=1.0-r
+	# Initialize
+	x1=r*a+c*b;x2=c*a+r*b
+	f1=sign*obj(x1,*args);f2=sign*obj(x2,*args)
+	# Loop
+	for i in range(numIter):
+		if f1>f2:
+			a=x1
+			x1=x2;f1=f2
+			x2=c*a+r*b;f2=sign*obj(x2,*args)
+		else:
+			b=x2
+			x2=x1;f2=f1
+			x1=r*a+c*b;f1=sign*obj(x1,*args)
+	if f1<f2:return x1,sign*f1
+	else:return x2,sign*f2
+#---------------------------------------------------------------
+# Boilerplate
+if __name__=='__main__':main()

Added: pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/DD3.py
===================================================================
--- pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/DD3.py	                        (rev 0)
+++ pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/DD3.py	2013-07-13 20:35:03 UTC (rev 2567)
@@ -0,0 +1,71 @@
+#!/usr/bin/env python
+# On 20121230
+# Get maximum time under the water
+# by MLdP <lopezdeprado at lbl.gov>
+from scipy.stats import norm
+#---------------------------------------------------------------
+def main():
+	#1) Parameters
+	phi=.5 # AR(1) coefficient
+	mu=1 # unconditional mean
+	sigma=2 # Standard deviation of the random shock
+	dPi0=1 # Bet at origin (initialization of AR(1))
+	confidence=.95 # Confidence level for quantile
+	#2) Compute TuW
+	tuw=getTuW(phi,mu,sigma,dPi0,confidence)
+	print 'MaxTuW = '+str(tuw)
+	return
+#---------------------------------------------------------------
+def getTuW(phi,mu,sigma,dPi0,confidence):
+	# Compute TuW
+	q,bets=0,0
+	#1) Determine extremes of search
+	while not q>0:
+		bets+=1
+		q=getQ(bets,phi,mu,sigma,dPi0,confidence)
+	#2) Compute root of q polynomial
+	kargs={'args':(phi,mu,sigma,dPi0,confidence)}
+	tuw,q=goldenSection(diff,bets-1,bets,**kargs)
+	return tuw
+#---------------------------------------------------------------
+def getQ(bets,phi,mu,sigma,dPi0,confidence):
+	# Compute analytical solution to quantile
+	#1) Mean
+	mean=(phi**(bets+1)-phi)/(1-phi)*(dPi0-mu)+mu*bets
+	#2) Variance
+	var=sigma**2/(phi-1)**2
+	var*=(phi**(2*(bets+1))-1)/(phi**2-1)-2*(phi**(bets+1)-1)/(phi-1)+bets+1
+	#3) Quantile
+	q=mean+norm.ppf(1-confidence,0,1)*var**.5
+	return q
+#---------------------------------------------------------------
+def diff(bets,phi,mu,sigma,dPi0,confidence):
+	return abs(getQ(bets,phi,mu,sigma,dPi0,confidence))
+#---------------------------------------------------------------
+def goldenSection(obj,a,b,**kargs):
+	# Golden section method. Maximum if kargs['minimum']==False is passed 
+	from math import log,ceil
+	tol,sign,args=1.0e-9,1,None
+	if 'minimum' in kargs and kargs['minimum']==False:sign=-1
+	if 'args' in kargs:args=kargs['args']
+	numIter=int(ceil(-2.078087*log(tol/abs(b-a))))
+	r=0.618033989
+	c=1.0-r
+	# Initialize
+	x1=r*a+c*b;x2=c*a+r*b
+	f1=sign*obj(x1,*args);f2=sign*obj(x2,*args)
+	# Loop
+	for i in range(numIter):
+		if f1>f2:
+			a=x1
+			x1=x2;f1=f2
+			x2=c*a+r*b;f2=sign*obj(x2,*args)
+		else:
+			b=x2
+			x2=x1;f2=f1
+			x1=r*a+c*b;f1=sign*obj(x1,*args)
+	if f1<f2:return x1,sign*f1
+	else:return x2,sign*f2
+#---------------------------------------------------------------
+# Boilerplate
+if __name__=='__main__':main()

Added: pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/data1.csv
===================================================================
--- pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/data1.csv	                        (rev 0)
+++ pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/data1.csv	2013-07-13 20:35:03 UTC (rev 2567)
@@ -0,0 +1,27 @@
+Code,Mean,StDev,Phi,Sigma,t-Stat(Phi)
+HFRIFOF Index,0.005516691,0.016969081,0.35942732,0.015835089,6.246140275
+HFRIFWI Index,0.008881851,0.020176781,0.304802238,0.019216682,5.190679363
+HFRIEHI Index,0.009858566,0.026444472,0.26510117,0.025498305,4.460055655
+HFRIMI Index,0.009527016,0.021496073,0.184350274,0.021127643,3.041856755
+HFRIFOFD Index,0.005179518,0.017416384,0.353548291,0.016291569,6.129496094
+HFRIDSI Index,0.009621101,0.018800339,0.545792492,0.015753187,10.56122157
+HFRIEMNI Index,0.005182009,0.009427888,0.164396537,0.009299616,2.703456292
+HFRIFOFC Index,0.004809119,0.011620459,0.455662847,0.01034398,8.302257893
+HFRIEDI Index,0.009536151,0.019247216,0.391629021,0.01770981,6.902140563
+HFRIMTI Index,0.008528045,0.021556689,-0.0188129,0.021552874,-0.305148009
+HFRIFIHY Index,0.007177975,0.017707746,0.483806908,0.015497372,8.972011994
+HFRIFI Index,0.006855376,0.012881753,0.505908165,0.011111637,9.587381222
+HFRIRVA Index,0.008020951,0.012975483,0.452790992,0.011569158,8.242977673
+HFRIMAI Index,0.007142082,0.010437017,0.298219544,0.009962104,5.067023312
+HFRICAI Index,0.007122016,0.019973858,0.578004656,0.016299336,11.48654001
+HFRIEM Index,0.010352034,0.041000178,0.359277175,0.038262633,6.243082394
+HFRIEMA Index,0.007989882,0.038243416,0.311226738,0.036344083,5.310865179
+HFRISHSE Index,-0.001675503,0.053512968,0.090737496,0.053292219,1.477615589
+HFRIEMLA Index,0.011074013,0.05084986,0.196931418,0.04985408,3.257468873
+HFRIFOFS Index,0.006834983,0.024799788,0.323053217,0.023470043,5.536016371
+HFRIENHI Index,0.010092318,0.036682513,0.201118844,0.035932974,3.329910279
+HFRIFWIG Index,0.009382896,0.035972197,0.231372973,0.034996096,3.857301725
+HFRIFOFM Index,0.005607926,0.015907089,0.042154535,0.015892949,0.684239764
+HFRIFWIC Index,0.008947104,0.039009601,0.050499002,0.038959829,0.820004462
+HFRIFWIJ Index,0.008423965,0.03629762,0.0953987,0.036132072,1.554206093
+HFRISTI Index,0.011075118,0.046441033,0.160831261,0.04583646,2.642789417

Added: pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/run.py
===================================================================
--- pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/run.py	                        (rev 0)
+++ pkg/PerformanceAnalytics/sandbox/pulkit/week3/code/run.py	2013-07-13 20:35:03 UTC (rev 2567)
@@ -0,0 +1,51 @@
+#!/usr/bin/env python
+# On 20121230
+# MaxDD, t* and MaxTuW for HFR series
+# by MLdP <lopezdeprado at lbl.gov>
+import DD2,DD3 # These are the two modules in Appendices 9 and 10
+#---------------------------------------------------------------
+def isNumber(input):
+    # Determines whether input is a number
+    try:
+        float(input)
+        return True
+    except:
+        return False
+#---------------------------------------------------------------
+def main():
+    #1) Parameters
+    path=''
+    inFileName='data1.csv'
+    outFileName='Results1.csv'
+    fields=['Code','Mean','Phi','Sigma']
+    confidence=.95
+    dPi0=0
+    #2) Read file
+    inFile=open(path+inFileName,'r')
+    outFile=open(path+outFileName,'w')
+    headers=inFile.readline().split(',')
+    indices=[headers.index(i) for i in fields]
+    for line in inFile:
+        #3) Get Input
+        params={}
+        line=line[:-1].split(',')
+        for i in indices:
+            if isNumber(line[i])==True:
+                params[headers[i]]=float(line[i])
+            else:
+                params[headers[i]]=line[i]
+        #4) Compute MaxDD,MaxTuW
+        if params['Mean']>0 and params['Phi']>=0:
+            t,minQ=DD2.getMinQ(params['Phi'],params['Mean'],params['Sigma'],dPi0,confidence)
+            maxDD=max(0,-minQ)
+            maxTuW=DD3.getTuW(params['Phi'],params['Mean'],params['Sigma'],dPi0,confidence)
+        else:
+            maxDD,t,maxTuW='--','--','--'
+        #5) Store result
+        msg=params['Code']+','+str(maxDD)+','+str(t)+','+str(maxTuW)
+        outFile.writelines(msg+'\n')
+        print msg
+    return
+#---------------------------------------------------------------
+# Boilerplate
+if __name__=='__main__':main()



More information about the Returnanalytics-commits mailing list