File: risk_statistics.py

package info (click to toggle)
quantlib-python 0.2.1.cvs20020322-1
  • links: PTS
  • area: main
  • in suites: woody
  • size: 2,040 kB
  • ctags: 3,245
  • sloc: cpp: 32,997; python: 7,156; makefile: 70
file content (214 lines) | stat: -rwxr-xr-x 7,542 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
#!/usr/bin/python

"""
 Copyright (C) 2000, 2001, 2002 RiskMap srl

 This file is part of QuantLib, a free-software/open-source library
 for financial quantitative analysts and developers - http://quantlib.org/

 QuantLib is free software: you can redistribute it and/or modify it under the
 terms of the QuantLib license.  You should have received a copy of the
 license along with this program; if not, please email ferdinando@ametrano.net
 The license is also available online at http://quantlib.org/html/license.html

 This program is distributed in the hope that it will be useful, but WITHOUT
 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 FOR A PARTICULAR PURPOSE.  See the license for more details.
"""

__version__ = "$Revision: 1.15 $"
# $Source: /cvsroot/quantlib/QuantLib-Python/QuantLib/test/risk_statistics.py,v $

import QuantLib
import unittest
from math import exp, sqrt, pi

# define a Gaussian
def gaussian(x, average, sigma):
    normFact = sigma * sqrt( 2 * pi )
    dx = x-average
    return exp( -dx*dx/(2.0*sigma*sigma) ) / normFact

class RiskStatisticsTest(unittest.TestCase):
    def runTest(self):
        "Testing risk statistics"
        s = QuantLib.RiskStatistics()
        averageRange = [-100.0, 0.0, 100.0]
        sigmaRange = [0.1, 1.0, 10]
        N = 25000
        numberOfSigma = 15

        for average in averageRange:
            for sigma in sigmaRange:
                #target cannot be changed:
                #it is a strong assumption to compute values to be checked
                target = average
                normal = QuantLib.NormalDistribution(average, sigma)

                dataMin = average - numberOfSigma*sigma
                dataMax = average + numberOfSigma*sigma
                # even NOT to include average
                h = (dataMax-dataMin)/(N-1)

                data = [0]*N        # creates a list of N elements
                for i in range(N):
                    data[i] = dataMin+h*i

                weights = map(lambda x,average=average,sigma=sigma:
                    gaussian(x,average,sigma), data)
                s.addWeightedSequence(data, weights)

                samples = s.samples()
                if not (samples == N):
                    self.fail("""
wrong number of samples
    calculated: %(samples)d
    expected  : %(N)d
                              """ % locals())

                rightWeightSum = reduce(lambda x,y: x+y, weights)
                weightSum = s.weightSum()
                if not (weightSum == rightWeightSum):
                    self.fail("""
wrong sum of weights
    calculated: %(weightSum)f
    expected  : %(rightWeightSum)f
                              """ % locals())

                minDatum = s.min()
                maxDatum = s.max()
                if not (minDatum == dataMin):
                    self.fail("""
wrong minimum value
    calculated: %(minDatum)f
    expected  : %(dataMin)f
                              """ % locals())

                if not (abs(s.max()-dataMax) <= 1e-13):
                    self.fail("""
wrong maximum value
    calculated: %(maxDatum)f
    expected  : %(dataMax)f
                              """ % locals())

                mean = s.mean()
                if average == 0.0:
                    check = abs(mean-average)
                else:
                    check = abs(mean-average)/average
                if not (check <= 1e-13):
                    self.fail("""
wrong mean value
    calculated: %(mean)f
    expected  : %(average)f
                              """ % locals())

                variance = s.variance()
                sigma2 = sigma*sigma
                if not (abs(variance-sigma2)/sigma2 <= 1e-4):
                    self.fail("""
wrong variance
    calculated: %(variance)f
    expected  : %(sigma2)f
                              """ % locals())

                stdDev = s.standardDeviation()
                if not (abs(stdDev-sigma)/sigma <= 1e-4):
                    self.fail("""
wrong standard deviation
    calculated: %(stdDev)f
    expected  : %(sigma)f
                              """ % locals())

                skewness = s.skewness()
                if not (abs(skewness) <= 1e-4):
                    self.fail("""
wrong skewness
    calculated: %(skewness)f
    expected  : 0.0
                              """ % locals())

                kurtosis = s.kurtosis()
                if not (abs(kurtosis) <= 1e-1):
                    self.fail("""
wrong kurtosis
    calculated: %(kurtosis)f
    expected  : 0.0
                              """ % locals())


                rightPotentialUpside = max(average+2.0*sigma, 0.0)
                potentialUpside = s.potentialUpside(0.9772)
                if rightPotentialUpside == 0.0:
                    check = abs(potentialUpside-rightPotentialUpside)
                else:
                    check = abs(potentialUpside-rightPotentialUpside)/\
                    rightPotentialUpside
                if not (check <= 1e-3):
                    self.fail("""
wrong potential upside
    calculated: %(potentialUpside)f
    expected:   %(rightPotentialUpside)f
                              """ % locals())

                rightVAR = -min(average-2.0*sigma, 0.0)
                VAR = s.valueAtRisk(0.9772)
                if rightVAR == 0.0:
                    check = abs(VAR-rightVAR)
                else:
                    check = abs(VAR-rightVAR)/rightVAR
                if not (check <= 1e-3):
                    self.fail("""
wrong value at risk
    calculated: %(VAR)f
    expected:   %(rightVAR)f
                              """ % locals())

                tempVAR = average-2.0*sigma
                rightExShortfall = average - sigma*sigma*gaussian(tempVAR,
                    average, sigma)/(1.0-0.9772)
                rightExShortfall = -min(rightExShortfall, 0.0)
                exShortfall = s.expectedShortfall(0.9772)
                if rightExShortfall == 0.0:
                    check = abs(exShortfall)
                else:
                    check = abs(exShortfall-rightExShortfall)/rightExShortfall
                if not (check <= 1e-3):
                    self.fail("""
wrong expected shortfall
    calculated: %(exShortFall)f
    expected:   %(rightExShortfall)f
                              """ % locals())

                rightShortfall = 0.5
                shortfall = s.shortfall(target)
                if not (abs(shortfall-rightShortfall)/rightShortfall <= 1e-8):
                    self.fail("""
wrong shortfall
    calculated: %(shortFall)
    expected:   %(rightShortfall)f
                              """ % locals())

                rightAvgShortfall = sigma/sqrt( 2 * pi )
                avgShortfall = s.averageShortfall(target)
                check = abs(avgShortfall-rightAvgShortfall)/rightAvgShortfall
                if not (check <= 1e-4):
                    self.fail("""
wrong average shortfall
    calculated: %(avgShortFall)f
    expected:   %(rightAvgShortfall)f
                              """ % locals())

                s.reset()


if __name__ == '__main__':
    print 'testing QuantLib', QuantLib.__version__, QuantLib.QuantLibc.__file__, QuantLib.__file__
    import sys
    suite = unittest.TestSuite()
    suite.addTest(RiskStatisticsTest())
    if sys.hexversion >= 0x020100f0:
        unittest.TextTestRunner(verbosity=2).run(suite)
    else:
        unittest.TextTestRunner().run(suite)
    raw_input('press any key to continue')