How to use test_call method in Testify

Best Python code snippet using Testify_python

test_options.py

Source:test_options.py Github

copy

Full Screen

1import unittest2import copy3import numpy as np4import numpy.testing as np_test5import pandas as pd6import pandas.testing as pd_test7import warnings8from pyblackscholesanalytics.market.market import MarketEnvironment9from pyblackscholesanalytics.options.options import PlainVanillaOption, DigitalOption10from pyblackscholesanalytics.utils.utils import scalarize11class TestPlainVanillaOption(unittest.TestCase):12 """Class to test public methods of PlainVanillaOption class"""13 def setUp(self) -> None:14 warnings.filterwarnings("ignore")15 # common market environment16 mkt_env = MarketEnvironment()17 # option objects18 self.call_opt = PlainVanillaOption(mkt_env)19 self.put_opt = PlainVanillaOption(mkt_env, option_type="put")20 # pricing parameters21 S_scalar = 10022 S_vector = [90, 100, 110]23 t_scalar_string = "01-06-2020"24 t_date_range = pd.date_range(start="2020-04-19", end="2020-12-21", periods=5)25 # common pricing parameter setup26 common_params = {"np_output": True, "minimization_method": "Least-Squares"}27 # scalar parameters setup28 self.scalar_params = copy.deepcopy(common_params)29 self.scalar_params["S"] = S_scalar30 self.scalar_params["t"] = t_scalar_string31 # vector parameters setup32 self.vector_params = copy.deepcopy(common_params)33 self.vector_params["S"] = S_vector34 self.vector_params["t"] = t_date_range35 # complex pricing parameter setup36 # (S scalar, K and t vector, sigma distributed as Kxt grid, r distributed as Kxt grid)37 K_vector = [75, 85, 90, 95]38 mK = len(K_vector)39 n = 340 sigma_grid_K = np.array([0.1 * (1 + i) for i in range(mK * n)]).reshape(n, mK)41 r_grid_K = np.array([0.01 * (1 + i) for i in range(mK * n)]).reshape(n, mK)42 self.complex_params = {"S": S_vector[0],43 "K": K_vector,44 "t": pd.date_range(start="2020-04-19", end="2020-12-21", periods=n),45 "sigma": sigma_grid_K,46 "r": r_grid_K,47 "np_output": False,48 "minimization_method": "Least-Squares"}49 def test_price_scalar(self):50 """Test price - scalar case"""51 # call52 test_call = scalarize(self.call_opt.price(**self.scalar_params))53 expected_call = 7.54838171681183954 self.assertEqual(test_call, expected_call)55 # put56 test_put = scalarize(self.put_opt.price(**self.scalar_params))57 expected_put = 4.67273050640795958 self.assertEqual(test_put, expected_put)59 def test_price_vector_np(self):60 """Test price - np.ndarray output case"""61 # call62 test_call = self.call_opt.price(**self.vector_params)63 expected_call = np.array([[3.48740247e+00, 8.42523213e+00, 1.55968082e+01],64 [2.53045128e+00, 7.14167587e+00, 1.43217796e+01],65 [1.56095778e+00, 5.72684668e+00, 1.29736886e+01],66 [5.89165298e-01, 4.00605304e+00, 1.14939139e+01],67 [7.21585753e-04, 1.38927959e+00, 1.01386434e+01]])68 np_test.assert_allclose(test_call, expected_call)69 # put70 test_put = self.put_opt.price(**self.vector_params)71 expected_put = np.array([[1.00413306e+01, 4.97916024e+00, 2.15073633e+00],72 [9.90791873e+00, 4.51914332e+00, 1.69924708e+00],73 [9.75553655e+00, 3.92142545e+00, 1.16826738e+00],74 [9.62127704e+00, 3.03816479e+00, 5.26025639e-01],75 [9.86382907e+00, 1.25238707e+00, 1.75090342e-03]])76 np_test.assert_allclose(test_put, expected_put)77 def test_price_vector_df(self):78 """Test price - pd.DataFrame output case"""79 # request Pandas DataFrame as output format80 self.vector_params["np_output"] = False81 # call82 test_call = self.call_opt.price(**self.vector_params)83 expected_call = pd.DataFrame(data=[[3.48740247e+00, 8.42523213e+00, 1.55968082e+01],84 [2.53045128e+00, 7.14167587e+00, 1.43217796e+01],85 [1.56095778e+00, 5.72684668e+00, 1.29736886e+01],86 [5.89165298e-01, 4.00605304e+00, 1.14939139e+01],87 [7.21585753e-04, 1.38927959e+00, 1.01386434e+01]],88 index=self.vector_params["t"],89 columns=self.vector_params["S"])90 expected_call.rename_axis("S", axis='columns', inplace=True)91 expected_call.rename_axis("t", axis='rows', inplace=True)92 pd_test.assert_frame_equal(test_call, expected_call)93 # put94 test_put = self.put_opt.price(**self.vector_params)95 expected_put = pd.DataFrame(data=[[1.00413306e+01, 4.97916024e+00, 2.15073633e+00],96 [9.90791873e+00, 4.51914332e+00, 1.69924708e+00],97 [9.75553655e+00, 3.92142545e+00, 1.16826738e+00],98 [9.62127704e+00, 3.03816479e+00, 5.26025639e-01],99 [9.86382907e+00, 1.25238707e+00, 1.75090342e-03]],100 index=self.vector_params["t"],101 columns=self.vector_params["S"])102 expected_put.rename_axis("S", axis='columns', inplace=True)103 expected_put.rename_axis("t", axis='rows', inplace=True)104 pd_test.assert_frame_equal(test_put, expected_put)105 def test_PnL_scalar(self):106 """Test P&L - scalar case"""107 # call108 test_call = scalarize(self.call_opt.PnL(**self.scalar_params))109 expected_call = 4.060979245868182110 self.assertEqual(test_call, expected_call)111 # put112 test_put = scalarize(self.put_opt.PnL(**self.scalar_params))113 expected_put = -5.368600081057167114 self.assertEqual(test_put, expected_put)115 def test_PnL_vector_np(self):116 """Test P&L - np.ndarray output case"""117 # call118 test_call = self.call_opt.PnL(**self.vector_params)119 expected_call = np.array([[0., 4.93782966, 12.10940574],120 [-0.95695119, 3.6542734, 10.83437716],121 [-1.92644469, 2.2394442, 9.48628613],122 [-2.89823717, 0.51865057, 8.00651142],123 [-3.48668089, -2.09812288, 6.65124095]])124 np_test.assert_allclose(test_call, expected_call)125 # put126 test_put = self.put_opt.PnL(**self.vector_params)127 expected_put = np.array([[0., -5.06217034, -7.89059426],128 [-0.13341186, -5.52218727, -8.3420835],129 [-0.28579403, -6.11990513, -8.87306321],130 [-0.42005355, -7.0031658, -9.51530495],131 [-0.17750152, -8.78894351, -10.03957968]])132 np_test.assert_allclose(test_put, expected_put)133 def test_PnL_vector_df(self):134 """Test P&L - pd.DataFrame output case"""135 # request Pandas DataFrame as output format136 self.vector_params["np_output"] = False137 # call138 test_call = self.call_opt.PnL(**self.vector_params)139 expected_call = pd.DataFrame(data=[[0., 4.93782966, 12.10940574],140 [-0.95695119, 3.6542734, 10.83437716],141 [-1.92644469, 2.2394442, 9.48628613],142 [-2.89823717, 0.51865057, 8.00651142],143 [-3.48668089, -2.09812288, 6.65124095]],144 index=self.vector_params["t"],145 columns=self.vector_params["S"])146 expected_call.rename_axis("S", axis='columns', inplace=True)147 expected_call.rename_axis("t", axis='rows', inplace=True)148 pd_test.assert_frame_equal(test_call, expected_call)149 # put150 test_put = self.put_opt.PnL(**self.vector_params)151 expected_put = pd.DataFrame(data=[[0., -5.06217034, -7.89059426],152 [-0.13341186, -5.52218727, -8.3420835],153 [-0.28579403, -6.11990513, -8.87306321],154 [-0.42005355, -7.0031658, -9.51530495],155 [-0.17750152, -8.78894351, -10.03957968]],156 index=self.vector_params["t"],157 columns=self.vector_params["S"])158 expected_put.rename_axis("S", axis='columns', inplace=True)159 expected_put.rename_axis("t", axis='rows', inplace=True)160 pd_test.assert_frame_equal(test_put, expected_put)161 def test_delta_scalar(self):162 """Test Delta - scalar case"""163 # call164 test_call = scalarize(self.call_opt.delta(**self.scalar_params))165 expected_call = 0.6054075531684143166 self.assertEqual(test_call, expected_call)167 # put168 test_put = scalarize(self.put_opt.delta(**self.scalar_params))169 expected_put = -0.3945924468315857170 self.assertEqual(test_put, expected_put)171 def test_delta_vector_np(self):172 """Test Delta - np.ndarray output case"""173 # call174 test_call = self.call_opt.delta(**self.vector_params)175 expected_call = np.array([[3.68466757e-01, 6.15283790e-01, 8.05697003e-01],176 [3.20097309e-01, 6.00702480e-01, 8.18280131e-01],177 [2.54167521e-01, 5.83663527e-01, 8.41522350e-01],178 [1.49152172e-01, 5.61339299e-01, 8.91560577e-01],179 [8.89758553e-04, 5.23098767e-01, 9.98343116e-01]])180 np_test.assert_allclose(test_call, expected_call)181 # put182 test_put = self.put_opt.delta(**self.vector_params)183 expected_put = np.array([[-0.63153324, -0.38471621, -0.194303],184 [-0.67990269, -0.39929752, -0.18171987],185 [-0.74583248, -0.41633647, -0.15847765],186 [-0.85084783, -0.4386607, -0.10843942],187 [-0.99911024, -0.47690123, -0.00165688]])188 np_test.assert_allclose(test_put, expected_put, rtol=5e-6)189 def test_delta_vector_df(self):190 """Test Delta - pd.DataFrame output case"""191 # request Pandas DataFrame as output format192 self.vector_params["np_output"] = False193 # call194 test_call = self.call_opt.delta(**self.vector_params)195 expected_call = pd.DataFrame(data=[[3.68466757e-01, 6.15283790e-01, 8.05697003e-01],196 [3.20097309e-01, 6.00702480e-01, 8.18280131e-01],197 [2.54167521e-01, 5.83663527e-01, 8.41522350e-01],198 [1.49152172e-01, 5.61339299e-01, 8.91560577e-01],199 [8.89758553e-04, 5.23098767e-01, 9.98343116e-01]],200 index=self.vector_params["t"],201 columns=self.vector_params["S"])202 expected_call.rename_axis("S", axis='columns', inplace=True)203 expected_call.rename_axis("t", axis='rows', inplace=True)204 pd_test.assert_frame_equal(test_call, expected_call)205 # put206 test_put = self.put_opt.delta(**self.vector_params)207 expected_put = pd.DataFrame(data=[[-0.63153324, -0.38471621, -0.194303],208 [-0.67990269, -0.39929752, -0.18171987],209 [-0.74583248, -0.41633647, -0.15847765],210 [-0.85084783, -0.4386607, -0.10843942],211 [-0.99911024, -0.47690123, -0.00165688]],212 index=self.vector_params["t"],213 columns=self.vector_params["S"])214 expected_put.rename_axis("S", axis='columns', inplace=True)215 expected_put.rename_axis("t", axis='rows', inplace=True)216 pd_test.assert_frame_equal(test_put, expected_put)217 def test_gamma_scalar(self):218 """Test Gamma - scalar case"""219 # call220 test_call = scalarize(self.call_opt.gamma(**self.scalar_params))221 expected_call = 0.025194958512498786222 self.assertEqual(test_call, expected_call)223 # put224 test_put = scalarize(self.put_opt.gamma(**self.scalar_params))225 expected_put = copy.deepcopy(expected_call)226 self.assertEqual(test_put, expected_put)227 # assert call and put gamma coincide228 self.assertEqual(test_call, test_put)229 def test_gamma_vector_np(self):230 """Test Gamma - np.ndarray output case"""231 # call232 test_call = self.call_opt.gamma(**self.vector_params)233 expected_call = np.array([[0.02501273, 0.02281654, 0.01493167],234 [0.02725456, 0.02648423, 0.01645793],235 [0.02950243, 0.03231528, 0.01820714],236 [0.02925862, 0.0446913, 0.01918121],237 [0.00101516, 0.12030889, 0.00146722]])238 np_test.assert_allclose(test_call, expected_call, rtol=5e-6)239 # put240 test_put = self.put_opt.gamma(**self.vector_params)241 expected_put = copy.deepcopy(expected_call)242 np_test.assert_allclose(test_put, expected_put, rtol=5e-6)243 # assert call and put gamma coincide244 np_test.assert_allclose(test_call, test_put)245 def test_gamma_vector_df(self):246 """Test Gamma - pd.DataFrame output case"""247 # request Pandas DataFrame as output format248 self.vector_params["np_output"] = False249 # call250 test_call = self.call_opt.gamma(**self.vector_params)251 expected_call = pd.DataFrame(data=[[0.02501273, 0.02281654, 0.01493167],252 [0.02725456, 0.02648423, 0.01645793],253 [0.02950243, 0.03231528, 0.01820714],254 [0.02925862, 0.0446913, 0.01918121],255 [0.00101516, 0.12030889, 0.00146722]],256 index=self.vector_params["t"],257 columns=self.vector_params["S"])258 expected_call.rename_axis("S", axis='columns', inplace=True)259 expected_call.rename_axis("t", axis='rows', inplace=True)260 pd_test.assert_frame_equal(test_call, expected_call)261 # put262 test_put = self.put_opt.gamma(**self.vector_params)263 expected_put = copy.deepcopy(expected_call)264 pd_test.assert_frame_equal(test_put, expected_put)265 # assert call and put gamma coincide266 pd_test.assert_frame_equal(test_call, test_put)267 def test_vega_scalar(self):268 """Test Vega - scalar case"""269 # call270 test_call = scalarize(self.call_opt.vega(**self.scalar_params))271 expected_call = 0.29405622811847903272 self.assertEqual(test_call, expected_call)273 # put274 test_put = scalarize(self.put_opt.vega(**self.scalar_params))275 expected_put = copy.deepcopy(expected_call)276 self.assertEqual(test_put, expected_put)277 # assert call and put vega coincide278 self.assertEqual(test_call, test_put)279 def test_vega_vector_np(self):280 """Test Vega - np.ndarray output case"""281 # call282 test_call = self.call_opt.vega(**self.vector_params)283 expected_call = np.array([[0.28419942, 0.32005661, 0.2534375],284 [0.23467293, 0.28153094, 0.21168961],285 [0.17415326, 0.23550311, 0.16055207],286 [0.09220072, 0.17386752, 0.09029355],287 [0.00045056, 0.06592268, 0.00097279]])288 np_test.assert_allclose(test_call, expected_call, rtol=1e-5)289 # put290 test_put = self.put_opt.vega(**self.vector_params)291 expected_put = copy.deepcopy(expected_call)292 np_test.assert_allclose(test_put, expected_put, rtol=1e-5)293 # assert call and put vega coincide294 np_test.assert_allclose(test_call, test_put)295 def test_vega_vector_df(self):296 """Test Vega - pd.DataFrame output case"""297 # request Pandas DataFrame as output format298 self.vector_params["np_output"] = False299 # call300 test_call = self.call_opt.vega(**self.vector_params)301 expected_call = pd.DataFrame(data=[[0.28419942, 0.32005661, 0.2534375],302 [0.23467293, 0.28153094, 0.21168961],303 [0.17415326, 0.23550311, 0.16055207],304 [0.09220072, 0.17386752, 0.09029355],305 [0.00045056, 0.06592268, 0.00097279]],306 index=self.vector_params["t"],307 columns=self.vector_params["S"])308 expected_call.rename_axis("S", axis='columns', inplace=True)309 expected_call.rename_axis("t", axis='rows', inplace=True)310 pd_test.assert_frame_equal(test_call, expected_call, check_less_precise=True)311 # put312 test_put = self.put_opt.vega(**self.vector_params)313 expected_put = copy.deepcopy(expected_call)314 pd_test.assert_frame_equal(test_put, expected_put, check_less_precise=True)315 # assert call and put vega coincide316 pd_test.assert_frame_equal(test_call, test_put)317 def test_theta_scalar(self):318 """Test Theta - scalar case"""319 # call320 test_call = scalarize(self.call_opt.theta(**self.scalar_params))321 expected_call = -0.021064685979455443322 self.assertEqual(test_call, expected_call)323 # put324 test_put = scalarize(self.put_opt.theta(**self.scalar_params))325 expected_put = -0.007759980665812141326 self.assertEqual(test_put, expected_put)327 def test_theta_vector_np(self):328 """Test Theta - np.ndarray output case"""329 # call330 test_call = self.call_opt.theta(**self.vector_params)331 expected_call = np.array([[-0.01516655, -0.01977662, -0.01990399],332 [-0.01569631, -0.02176239, -0.0212802],333 [-0.01601397, -0.02491789, -0.02297484],334 [-0.01474417, -0.03162919, -0.02457737],335 [-0.00046144, -0.0728981, -0.01462746]])336 np_test.assert_allclose(test_call, expected_call, rtol=5e-4)337 # put338 test_put = self.put_opt.theta(**self.vector_params)339 expected_put = np.array([[-0.00193999, -0.00655005, -0.00667743],340 [-0.00235693, -0.00842301, -0.00794082],341 [-0.00256266, -0.01146658, -0.00952353],342 [-0.00117813, -0.01806315, -0.01101133],343 [0.01321844, -0.05921823, -0.00094758]])344 np_test.assert_allclose(test_put, expected_put, rtol=1e-5)345 def test_theta_vector_df(self):346 """Test Theta - pd.DataFrame output case"""347 # request Pandas DataFrame as output format348 self.vector_params["np_output"] = False349 # call350 test_call = self.call_opt.theta(**self.vector_params)351 expected_call = pd.DataFrame(data=[[-0.01516655, -0.01977662, -0.01990399],352 [-0.01569631, -0.02176239, -0.0212802],353 [-0.01601397, -0.02491789, -0.02297484],354 [-0.01474417, -0.03162919, -0.02457737],355 [-0.00046144, -0.0728981, -0.01462746]],356 index=self.vector_params["t"],357 columns=self.vector_params["S"])358 expected_call.rename_axis("S", axis='columns', inplace=True)359 expected_call.rename_axis("t", axis='rows', inplace=True)360 pd_test.assert_frame_equal(test_call, expected_call, check_less_precise=True)361 # put362 test_put = self.put_opt.theta(**self.vector_params)363 expected_put = pd.DataFrame(data=[[-0.00193999, -0.00655005, -0.00667743],364 [-0.00235693, -0.00842301, -0.00794082],365 [-0.00256266, -0.01146658, -0.00952353],366 [-0.00117813, -0.01806315, -0.01101133],367 [0.01321844, -0.05921823, -0.00094758]],368 index=self.vector_params["t"],369 columns=self.vector_params["S"])370 expected_put.rename_axis("S", axis='columns', inplace=True)371 expected_put.rename_axis("t", axis='rows', inplace=True)372 pd_test.assert_frame_equal(test_put, expected_put, check_less_precise=True)373 def test_rho_scalar(self):374 """Test Rho - scalar case"""375 # call376 test_call = scalarize(self.call_opt.rho(**self.scalar_params))377 expected_call = 0.309243166487844378 self.assertEqual(test_call, expected_call)379 # put380 test_put = scalarize(self.put_opt.rho(**self.scalar_params))381 expected_put = -0.2575372798733608382 self.assertEqual(test_put, expected_put)383 def test_rho_vector_np(self):384 """Test Rho - np.ndarray output case"""385 # call386 test_call = self.call_opt.rho(**self.vector_params)387 expected_call = np.array([[2.08128741e-01, 3.72449469e-01, 5.12209444e-01],388 [1.39670999e-01, 2.81318986e-01, 4.02292404e-01],389 [7.76651463e-02, 1.91809707e-01, 2.90026614e-01],390 [2.49657984e-02, 1.01399432e-01, 1.68411513e-01],391 [2.17415573e-05, 1.39508485e-02, 2.73093423e-02]])392 np_test.assert_allclose(test_call, expected_call, rtol=1e-5)393 # put394 test_put = self.put_opt.rho(**self.vector_params)395 expected_put = np.array([[-4.69071412e-01, -3.04750685e-01, -1.64990710e-01],396 [-3.77896910e-01, -2.36248923e-01, -1.15275505e-01],397 [-2.80139757e-01, -1.65995197e-01, -6.77782897e-02],398 [-1.67672008e-01, -9.12383748e-02, -2.42262934e-02],399 [-2.73380139e-02, -1.34089069e-02, -5.04131783e-05]])400 np_test.assert_allclose(test_put, expected_put, rtol=1e-5)401 def test_rho_vector_df(self):402 """Test Theta - pd.DataFrame output case"""403 # request Pandas DataFrame as output format404 self.vector_params["np_output"] = False405 # call406 test_call = self.call_opt.rho(**self.vector_params)407 expected_call = pd.DataFrame(data=[[2.08128741e-01, 3.72449469e-01, 5.12209444e-01],408 [1.39670999e-01, 2.81318986e-01, 4.02292404e-01],409 [7.76651463e-02, 1.91809707e-01, 2.90026614e-01],410 [2.49657984e-02, 1.01399432e-01, 1.68411513e-01],411 [2.17415573e-05, 1.39508485e-02, 2.73093423e-02]],412 index=self.vector_params["t"],413 columns=self.vector_params["S"])414 expected_call.rename_axis("S", axis='columns', inplace=True)415 expected_call.rename_axis("t", axis='rows', inplace=True)416 pd_test.assert_frame_equal(test_call, expected_call, check_less_precise=True)417 # put418 test_put = self.put_opt.rho(**self.vector_params)419 expected_put = pd.DataFrame(data=[[-4.69071412e-01, -3.04750685e-01, -1.64990710e-01],420 [-3.77896910e-01, -2.36248923e-01, -1.15275505e-01],421 [-2.80139757e-01, -1.65995197e-01, -6.77782897e-02],422 [-1.67672008e-01, -9.12383748e-02, -2.42262934e-02],423 [-2.73380139e-02, -1.34089069e-02, -5.04131783e-05]],424 index=self.vector_params["t"],425 columns=self.vector_params["S"])426 expected_put.rename_axis("S", axis='columns', inplace=True)427 expected_put.rename_axis("t", axis='rows', inplace=True)428 pd_test.assert_frame_equal(test_put, expected_put, check_less_precise=True)429 def test_Implied_Vol_scalar(self):430 """Test Implied Volatility - scalar case"""431 # call432 test_call = scalarize(self.call_opt.implied_volatility(**self.scalar_params))433 expected_call = 0.2434 self.assertAlmostEqual(test_call, expected_call)435 # put436 test_put = scalarize(self.put_opt.implied_volatility(**self.scalar_params))437 expected_put = 0.2438 self.assertAlmostEqual(test_put, expected_put)439 def test_Implied_Vol_vector_np(self):440 """Test Implied Volatility - np.ndarray output case"""441 # call442 test_call = self.call_opt.implied_volatility(**self.vector_params)443 expected_call = 0.2 + np.zeros_like(test_call)444 np_test.assert_allclose(test_call, expected_call, rtol=1e-5)445 # put446 test_put = self.put_opt.implied_volatility(**self.vector_params)447 expected_put = 0.2 + np.zeros_like(test_put)448 np_test.assert_allclose(test_put, expected_put, rtol=1e-5)449 def test_Implied_Vol_vector_df(self):450 """Test Implied Volatility - pd.DataFrame output case"""451 # request Pandas DataFrame as output format452 self.vector_params["np_output"] = False453 # call454 test_call = self.call_opt.implied_volatility(**self.vector_params)455 expected_call = pd.DataFrame(data=0.2 + np.zeros_like(test_call),456 index=self.vector_params["t"],457 columns=self.vector_params["S"])458 expected_call.rename_axis("S", axis='columns', inplace=True)459 expected_call.rename_axis("t", axis='rows', inplace=True)460 pd_test.assert_frame_equal(test_call, expected_call, check_less_precise=True)461 # put462 test_put = self.put_opt.implied_volatility(**self.vector_params)463 expected_put = pd.DataFrame(data=0.2 + np.zeros_like(test_put),464 index=self.vector_params["t"],465 columns=self.vector_params["S"])466 expected_put.rename_axis("S", axis='columns', inplace=True)467 expected_put.rename_axis("t", axis='rows', inplace=True)468 pd_test.assert_frame_equal(test_put, expected_put, check_less_precise=True)469 def test_complex_parameters_setup(self):470 """471 Test complex parameter setup:472 (S scalar, K and t vector, sigma distributed as Kxt grid, r distributed as Kxt grid)473 """474 # call475 test_call_price = self.call_opt.price(**self.complex_params)476 test_call_PnL = self.call_opt.PnL(**self.complex_params)477 test_call_delta = self.call_opt.delta(**self.complex_params)478 test_call_gamma = self.call_opt.gamma(**self.complex_params)479 test_call_vega = self.call_opt.vega(**self.complex_params)480 test_call_theta = self.call_opt.theta(**self.complex_params)481 test_call_rho = self.call_opt.rho(**self.complex_params)482 test_call_iv = self.call_opt.implied_volatility(**self.complex_params)483 expected_call_price = pd.DataFrame(data=[[15.55231058, 9.40714796, 9.87150919, 10.97983523],484 [20.05777231, 16.15277891, 16.02977848, 16.27588191],485 [15.81433361, 8.75227505, 6.65476799, 5.19785143]],486 index=self.complex_params["t"],487 columns=self.complex_params["K"])488 expected_call_price.rename_axis("K", axis='columns', inplace=True)489 expected_call_price.rename_axis("t", axis='rows', inplace=True)490 expected_call_PnL = pd.DataFrame(data=[[12.06490811, 5.91974549, 6.38410672, 7.49243276],491 [16.57036984, 12.66537644, 12.54237601, 12.78847944],492 [12.32693114, 5.26487258, 3.16736552, 1.71044896]],493 index=self.complex_params["t"],494 columns=self.complex_params["K"])495 expected_call_PnL.rename_axis("K", axis='columns', inplace=True)496 expected_call_PnL.rename_axis("t", axis='rows', inplace=True)497 expected_call_delta = pd.DataFrame(data=[[0.98935079, 0.69453583, 0.58292013, 0.53579465],498 [0.79256302, 0.65515368, 0.60705014, 0.57529078],499 [0.90573251, 0.6717088, 0.54283905, 0.43788167]],500 index=self.complex_params["t"],501 columns=self.complex_params["K"])502 expected_call_delta.rename_axis("K", axis='columns', inplace=True)503 expected_call_delta.rename_axis("t", axis='rows', inplace=True)504 expected_call_gamma = pd.DataFrame(data=[[0.00373538, 0.02325203, 0.01726052, 0.01317896],505 [0.01053321, 0.01130107, 0.01011038, 0.0090151],506 [0.01253481, 0.0242596, 0.02420515, 0.02204576]],507 index=self.complex_params["t"],508 columns=self.complex_params["K"])509 expected_call_gamma.rename_axis("K", axis='columns', inplace=True)510 expected_call_gamma.rename_axis("t", axis='rows', inplace=True)511 expected_call_vega = pd.DataFrame(data=[[0.02122104, 0.26419398, 0.29417607, 0.29948378],512 [0.15544424, 0.20013116, 0.20888592, 0.2128651],513 [0.02503527, 0.05383637, 0.05908709, 0.05870816]],514 index=self.complex_params["t"],515 columns=self.complex_params["K"])516 expected_call_vega.rename_axis("K", axis='columns', inplace=True)517 expected_call_vega.rename_axis("t", axis='rows', inplace=True)518 expected_call_theta = pd.DataFrame(data=[[-0.00242788, -0.01322973, -0.02073753, -0.02747845],519 [-0.03624253, -0.0521798, -0.06237363, -0.07180046],520 [-0.12885912, -0.28334665, -0.33769702, -0.36349655]],521 index=self.complex_params["t"],522 columns=self.complex_params["K"])523 expected_call_theta.rename_axis("K", axis='columns', inplace=True)524 expected_call_theta.rename_axis("t", axis='rows', inplace=True)525 expected_call_rho = pd.DataFrame(data=[[0.51543152, 0.37243495, 0.29872256, 0.26120194],526 [0.18683002, 0.15599644, 0.14066931, 0.12935721],527 [0.01800044, 0.0141648, 0.01156185, 0.00937301]],528 index=self.complex_params["t"],529 columns=self.complex_params["K"])530 expected_call_rho.rename_axis("K", axis='columns', inplace=True)531 expected_call_rho.rename_axis("t", axis='rows', inplace=True)532 expected_call_iv = pd.DataFrame(data=self.complex_params["sigma"],533 index=self.complex_params["t"],534 columns=self.complex_params["K"])535 expected_call_iv.rename_axis("K", axis='columns', inplace=True)536 expected_call_iv.rename_axis("t", axis='rows', inplace=True)537 pd_test.assert_frame_equal(test_call_price, expected_call_price)538 pd_test.assert_frame_equal(test_call_PnL, expected_call_PnL)539 pd_test.assert_frame_equal(test_call_delta, expected_call_delta)540 pd_test.assert_frame_equal(test_call_gamma, expected_call_gamma)541 pd_test.assert_frame_equal(test_call_vega, expected_call_vega)542 pd_test.assert_frame_equal(test_call_theta, expected_call_theta)543 pd_test.assert_frame_equal(test_call_rho, expected_call_rho)544 pd_test.assert_frame_equal(test_call_iv, expected_call_iv)545 # put546 test_put_price = self.put_opt.price(**self.complex_params)547 test_put_PnL = self.put_opt.PnL(**self.complex_params)548 test_put_delta = self.put_opt.delta(**self.complex_params)549 test_put_gamma = self.put_opt.gamma(**self.complex_params)550 test_put_vega = self.put_opt.vega(**self.complex_params)551 test_put_theta = self.put_opt.theta(**self.complex_params)552 test_put_rho = self.put_opt.rho(**self.complex_params)553 test_put_iv = self.put_opt.implied_volatility(**self.complex_params)554 expected_put_price = pd.DataFrame(data=[[0.02812357, 3.22314287, 7.9975943, 13.35166847],555 [3.70370639, 9.31459014, 13.76319167, 18.54654119],556 [0.62962992, 3.51971706, 6.38394341, 9.88603552]],557 index=self.complex_params["t"],558 columns=self.complex_params["K"])559 expected_put_price.rename_axis("K", axis='columns', inplace=True)560 expected_put_price.rename_axis("t", axis='rows', inplace=True)561 expected_put_PnL = pd.DataFrame(data=[[-10.01320701, -6.81818772, -2.04373628, 3.31033788],562 [-6.3376242, -0.72674045, 3.72186108, 8.5052106],563 [-9.41170067, -6.52161353, -3.65738717, -0.15529507]],564 index=self.complex_params["t"],565 columns=self.complex_params["K"])566 expected_put_PnL.rename_axis("K", axis='columns', inplace=True)567 expected_put_PnL.rename_axis("t", axis='rows', inplace=True)568 expected_put_delta = pd.DataFrame(data=[[-0.01064921, -0.30546417, -0.41707987, -0.46420535],569 [-0.20743698, -0.34484632, -0.39294986, -0.42470922],570 [-0.09426749, -0.3282912, -0.45716095, -0.56211833]],571 index=self.complex_params["t"],572 columns=self.complex_params["K"])573 expected_put_delta.rename_axis("K", axis='columns', inplace=True)574 expected_put_delta.rename_axis("t", axis='rows', inplace=True)575 expected_put_gamma = copy.deepcopy(expected_call_gamma)576 expected_put_vega = copy.deepcopy(expected_call_vega)577 expected_put_theta = pd.DataFrame(data=[[-0.00038744, -0.00863707, -0.01349429, -0.01735551],578 [-0.02615404, -0.03850937, -0.04554804, -0.05157676],579 [-0.11041151, -0.26012269, -0.31065535, -0.33236619]],580 index=self.complex_params["t"],581 columns=self.complex_params["K"])582 expected_put_theta.rename_axis("K", axis='columns', inplace=True)583 expected_put_theta.rename_axis("t", axis='rows', inplace=True)584 expected_put_rho = pd.DataFrame(data=[[-0.00691938, -0.21542518, -0.31936724, -0.38666626],585 [-0.08152366, -0.14703153, -0.17901683, -0.2068619],586 [-0.00249691, -0.00905916, -0.01302149, -0.01656895]],587 index=self.complex_params["t"],588 columns=self.complex_params["K"])589 expected_put_rho.rename_axis("K", axis='columns', inplace=True)590 expected_put_rho.rename_axis("t", axis='rows', inplace=True)591 expected_put_iv = pd.DataFrame(data=self.complex_params["sigma"],592 index=self.complex_params["t"],593 columns=self.complex_params["K"])594 expected_put_iv.rename_axis("K", axis='columns', inplace=True)595 expected_put_iv.rename_axis("t", axis='rows', inplace=True)596 pd_test.assert_frame_equal(test_put_price, expected_put_price)597 pd_test.assert_frame_equal(test_put_PnL, expected_put_PnL)598 pd_test.assert_frame_equal(test_put_delta, expected_put_delta)599 pd_test.assert_frame_equal(test_put_gamma, expected_put_gamma)600 pd_test.assert_frame_equal(test_put_vega, expected_put_vega)601 pd_test.assert_frame_equal(test_put_theta, expected_put_theta, check_less_precise=True)602 pd_test.assert_frame_equal(test_put_rho, expected_put_rho)603 pd_test.assert_frame_equal(test_put_iv, expected_put_iv)604 # test gamma and vega consistency605 pd_test.assert_frame_equal(test_call_gamma, test_put_gamma)606 pd_test.assert_frame_equal(test_call_vega, test_put_vega)607class TestDigitalOption(unittest.TestCase):608 """Class to test public methods of DigitalOption class"""609 def setUp(self) -> None:610 warnings.filterwarnings("ignore")611 # common market environment612 mkt_env = MarketEnvironment()613 # option objects614 self.call_opt = DigitalOption(mkt_env)615 self.put_opt = DigitalOption(mkt_env, option_type="put")616 # pricing parameters617 S_scalar = 100618 S_vector = [90, 100, 110]619 t_scalar_string = "01-06-2020"620 t_date_range = pd.date_range(start="2020-04-19", end="2020-12-21", periods=5)621 # common pricing parameter setup622 common_params = {"np_output": True, "minimization_method": "Least-Squares"}623 # scalar parameters setup624 self.scalar_params = copy.deepcopy(common_params)625 self.scalar_params["S"] = S_scalar626 self.scalar_params["t"] = t_scalar_string627 # vector parameters setup628 self.vector_params = copy.deepcopy(common_params)629 self.vector_params["S"] = S_vector630 self.vector_params["t"] = t_date_range631 # complex pricing parameter setup632 # (S scalar, K and t vector, sigma distributed as Kxt grid, r distributed as Kxt grid)633 K_vector = [75, 85, 90, 95]634 mK = len(K_vector)635 n = 3636 sigma_grid_K = np.array([0.1 * (1 + i) for i in range(mK * n)]).reshape(n, mK)637 r_grid_K = np.array([0.01 * (1 + i) for i in range(mK * n)]).reshape(n, mK)638 self.complex_params = {"S": S_vector[0],639 "K": K_vector,640 "t": pd.date_range(start="2020-04-19", end="2020-12-21", periods=n),641 "sigma": sigma_grid_K,642 "r": r_grid_K,643 "np_output": False,644 "minimization_method": "Least-Squares"}645 def test_price_scalar(self):646 """Test price - scalar case"""647 # call648 test_call = scalarize(self.call_opt.price(**self.scalar_params))649 expected_call = 0.529923736000296650 self.assertEqual(test_call, expected_call)651 # put652 test_put = scalarize(self.put_opt.price(**self.scalar_params))653 expected_put = 0.4413197518956652654 self.assertEqual(test_put, expected_put)655 def test_price_vector_np(self):656 """Test price - np.ndarray output case"""657 # call658 test_call = self.call_opt.price(**self.vector_params)659 expected_call = np.array([[2.96746057e-01, 5.31031469e-01, 7.30298621e-01],660 [2.62783065e-01, 5.29285722e-01, 7.56890348e-01],661 [2.13141191e-01, 5.26395060e-01, 7.95937699e-01],662 [1.28345302e-01, 5.21278768e-01, 8.65777496e-01],663 [7.93566840e-04, 5.09205971e-01, 9.96790994e-01]])664 np_test.assert_allclose(test_call, expected_call)665 # put666 test_put = self.put_opt.price(**self.vector_params)667 expected_put = np.array([[0.66879322, 0.43450781, 0.23524066],668 [0.71099161, 0.44448895, 0.21688433],669 [0.7688046, 0.45555073, 0.18600809],670 [0.86197582, 0.46904235, 0.12454362],671 [0.99783751, 0.4894251, 0.00184008]])672 np_test.assert_allclose(test_put, expected_put, rtol=1e-6)673 def test_price_vector_df(self):674 """Test price - pd.DataFrame output case"""675 # request Pandas DataFrame as output format676 self.vector_params["np_output"] = False677 # call678 test_call = self.call_opt.price(**self.vector_params)679 expected_call = pd.DataFrame(data=[[2.96746057e-01, 5.31031469e-01, 7.30298621e-01],680 [2.62783065e-01, 5.29285722e-01, 7.56890348e-01],681 [2.13141191e-01, 5.26395060e-01, 7.95937699e-01],682 [1.28345302e-01, 5.21278768e-01, 8.65777496e-01],683 [7.93566840e-04, 5.09205971e-01, 9.96790994e-01]],684 index=self.vector_params["t"],685 columns=self.vector_params["S"])686 expected_call.rename_axis("S", axis='columns', inplace=True)687 expected_call.rename_axis("t", axis='rows', inplace=True)688 pd_test.assert_frame_equal(test_call, expected_call)689 # put690 test_put = self.put_opt.price(**self.vector_params)691 expected_put = pd.DataFrame(data=[[0.66879322, 0.43450781, 0.23524066],692 [0.71099161, 0.44448895, 0.21688433],693 [0.7688046, 0.45555073, 0.18600809],694 [0.86197582, 0.46904235, 0.12454362],695 [0.99783751, 0.4894251, 0.00184008]],696 index=self.vector_params["t"],697 columns=self.vector_params["S"])698 expected_put.rename_axis("S", axis='columns', inplace=True)699 expected_put.rename_axis("t", axis='rows', inplace=True)700 pd_test.assert_frame_equal(test_put, expected_put)701 def test_PnL_scalar(self):702 """Test P&L - scalar case"""703 # call704 test_call = scalarize(self.call_opt.PnL(**self.scalar_params))705 expected_call = 0.23317767915072352706 self.assertEqual(test_call, expected_call)707 # put708 test_put = scalarize(self.put_opt.PnL(**self.scalar_params))709 expected_put = -0.22747347241997717710 self.assertEqual(test_put, expected_put)711 def test_PnL_vector_np(self):712 """Test P&L - np.ndarray output case"""713 # call714 test_call = self.call_opt.PnL(**self.vector_params)715 expected_call = np.array([[0., 0.23428541, 0.43355256],716 [-0.03396299, 0.23253966, 0.46014429],717 [-0.08360487, 0.229649, 0.49919164],718 [-0.16840076, 0.22453271, 0.56903144],719 [-0.29595249, 0.21245991, 0.70004494]])720 np_test.assert_allclose(test_call, expected_call)721 # put722 test_put = self.put_opt.PnL(**self.vector_params)723 expected_put = np.array([[0., -0.23428541, -0.43355256],724 [0.04219839, -0.22430427, -0.4519089],725 [0.10001137, -0.2132425, -0.48278514],726 [0.19318259, -0.19975088, -0.5442496],727 [0.32904428, -0.17936812, -0.66695314]])728 np_test.assert_allclose(test_put, expected_put, rtol=1e-6)729 def test_PnL_vector_df(self):730 """Test P&L - pd.DataFrame output case"""731 # request Pandas DataFrame as output format732 self.vector_params["np_output"] = False733 # call734 test_call = self.call_opt.PnL(**self.vector_params)735 expected_call = pd.DataFrame(data=[[0., 0.23428541, 0.43355256],736 [-0.03396299, 0.23253966, 0.46014429],737 [-0.08360487, 0.229649, 0.49919164],738 [-0.16840076, 0.22453271, 0.56903144],739 [-0.29595249, 0.21245991, 0.70004494]],740 index=self.vector_params["t"],741 columns=self.vector_params["S"])742 expected_call.rename_axis("S", axis='columns', inplace=True)743 expected_call.rename_axis("t", axis='rows', inplace=True)744 pd_test.assert_frame_equal(test_call, expected_call)745 # put746 test_put = self.put_opt.PnL(**self.vector_params)747 expected_put = pd.DataFrame(data=[[0., -0.23428541, -0.43355256],748 [0.04219839, -0.22430427, -0.4519089],749 [0.10001137, -0.2132425, -0.48278514],750 [0.19318259, -0.19975088, -0.5442496],751 [0.32904428, -0.17936812, -0.66695314]],752 index=self.vector_params["t"],753 columns=self.vector_params["S"])754 expected_put.rename_axis("S", axis='columns', inplace=True)755 expected_put.rename_axis("t", axis='rows', inplace=True)756 pd_test.assert_frame_equal(test_put, expected_put)757 def test_delta_scalar(self):758 """Test Delta - scalar case"""759 # call760 test_call = scalarize(self.call_opt.delta(**self.scalar_params))761 expected_call = 0.025194958512498786762 self.assertEqual(test_call, expected_call)763 # put764 test_put = scalarize(self.put_opt.delta(**self.scalar_params))765 expected_put = copy.deepcopy(-expected_call)766 self.assertEqual(test_put, expected_put)767 # assert call and put delta consistency768 self.assertEqual(test_call, -test_put)769 def test_delta_vector_np(self):770 """Test Delta - np.ndarray output case"""771 # call772 test_call = self.call_opt.delta(**self.vector_params)773 expected_call = np.array([[0.02251146, 0.02281654, 0.01642484],774 [0.0245291, 0.02648423, 0.01810373],775 [0.02655219, 0.03231528, 0.02002786],776 [0.02633276, 0.0446913, 0.02109933],777 [0.00091364, 0.12030889, 0.00161394]])778 np_test.assert_allclose(test_call, expected_call, rtol=5e-6)779 # put780 test_put = self.put_opt.delta(**self.vector_params)781 expected_put = copy.deepcopy(-expected_call)782 np_test.assert_allclose(test_put, expected_put, rtol=5e-6)783 # assert call and put delta consistency784 np_test.assert_allclose(test_call, -test_put)785 def test_delta_vector_df(self):786 """Test Delta - pd.DataFrame output case"""787 # request Pandas DataFrame as output format788 self.vector_params["np_output"] = False789 # call790 test_call = self.call_opt.delta(**self.vector_params)791 expected_call = pd.DataFrame(data=[[0.02251146, 0.02281654, 0.01642484],792 [0.0245291, 0.02648423, 0.01810373],793 [0.02655219, 0.03231528, 0.02002786],794 [0.02633276, 0.0446913, 0.02109933],795 [0.00091364, 0.12030889, 0.00161394]],796 index=self.vector_params["t"],797 columns=self.vector_params["S"])798 expected_call.rename_axis("S", axis='columns', inplace=True)799 expected_call.rename_axis("t", axis='rows', inplace=True)800 pd_test.assert_frame_equal(test_call, expected_call)801 # put802 test_put = self.put_opt.delta(**self.vector_params)803 expected_put = copy.deepcopy(-expected_call)804 pd_test.assert_frame_equal(test_put, expected_put)805 # assert call and put delta consistency806 pd_test.assert_frame_equal(test_call, -test_put)807 def test_gamma_scalar(self):808 """Test Gamma - scalar case"""809 # call810 test_call = scalarize(self.call_opt.gamma(**self.scalar_params))811 expected_call = -0.0004409117739687288812 self.assertEqual(test_call, expected_call)813 # put814 test_put = scalarize(self.put_opt.gamma(**self.scalar_params))815 expected_put = copy.deepcopy(-expected_call)816 self.assertEqual(test_put, expected_put)817 # assert call and put gamma coincide818 self.assertEqual(test_call, -test_put)819 def test_gamma_vector_np(self):820 """Test Gamma - np.ndarray output case"""821 # call822 test_call = self.call_opt.gamma(**self.vector_params)823 expected_call = np.array([[0.00050164, -0.00039929, -0.00076858],824 [0.00087371, -0.00046347, -0.00102583],825 [0.00161634, -0.00056552, -0.00150922],826 [0.0034499, -0.0007821, -0.00268525],827 [0.00095822, -0.00210541, -0.00130173]])828 np_test.assert_allclose(test_call, expected_call, rtol=1e-5)829 # put830 test_put = self.put_opt.gamma(**self.vector_params)831 expected_put = copy.deepcopy(-expected_call)832 np_test.assert_allclose(test_put, expected_put, rtol=1e-5)833 # assert call and put gamma coincide834 np_test.assert_allclose(test_call, -test_put)835 def test_gamma_vector_df(self):836 """Test Gamma - pd.DataFrame output case"""837 # request Pandas DataFrame as output format838 self.vector_params["np_output"] = False839 # call840 test_call = self.call_opt.gamma(**self.vector_params)841 expected_call = pd.DataFrame(data=[[0.00050164, -0.00039929, -0.00076858],842 [0.00087371, -0.00046347, -0.00102583],843 [0.00161634, -0.00056552, -0.00150922],844 [0.0034499, -0.0007821, -0.00268525],845 [0.00095822, -0.00210541, -0.00130173]],846 index=self.vector_params["t"],847 columns=self.vector_params["S"])848 expected_call.rename_axis("S", axis='columns', inplace=True)849 expected_call.rename_axis("t", axis='rows', inplace=True)850 pd_test.assert_frame_equal(test_call, expected_call, check_less_precise=True)851 # put852 test_put = self.put_opt.gamma(**self.vector_params)853 expected_put = copy.deepcopy(-expected_call)854 pd_test.assert_frame_equal(test_put, expected_put, check_less_precise=True)855 # assert call and put gamma coincide856 pd_test.assert_frame_equal(test_call, -test_put)857 def test_vega_scalar(self):858 """Test Vega - scalar case"""859 # call860 test_call = scalarize(self.call_opt.vega(**self.scalar_params))861 expected_call = -0.005145983992073383862 self.assertEqual(test_call, expected_call)863 # put864 test_put = scalarize(self.put_opt.vega(**self.scalar_params))865 expected_put = copy.deepcopy(-expected_call)866 self.assertEqual(test_put, expected_put)867 # assert call and put vega coincide868 self.assertEqual(test_call, -test_put)869 def test_vega_vector_np(self):870 """Test Vega - np.ndarray output case"""871 # call872 test_call = self.call_opt.vega(**self.vector_params)873 expected_call = np.array([[0.00569969, -0.00560099, -0.01304515],874 [0.00752302, -0.00492679, -0.01319465],875 [0.0095413, -0.0041213, -0.01330838],876 [0.01087143, -0.00304268, -0.01264053],877 [0.00042529, -0.00115365, -0.00086306]])878 np_test.assert_allclose(test_call, expected_call, rtol=1e-5)879 # put880 test_put = self.put_opt.vega(**self.vector_params)881 expected_put = copy.deepcopy(-expected_call)882 np_test.assert_allclose(test_put, expected_put, rtol=5e-5)883 # assert call and put vega coincide884 np_test.assert_allclose(test_call, -test_put)885 def test_vega_vector_df(self):886 """Test Vega - pd.DataFrame output case"""887 # request Pandas DataFrame as output format888 self.vector_params["np_output"] = False889 # call890 test_call = self.call_opt.vega(**self.vector_params)891 expected_call = pd.DataFrame(data=[[0.00569969, -0.00560099, -0.01304515],892 [0.00752302, -0.00492679, -0.01319465],893 [0.0095413, -0.0041213, -0.01330838],894 [0.01087143, -0.00304268, -0.01264053],895 [0.00042529, -0.00115365, -0.00086306]],896 index=self.vector_params["t"],897 columns=self.vector_params["S"])898 expected_call.rename_axis("S", axis='columns', inplace=True)899 expected_call.rename_axis("t", axis='rows', inplace=True)900 pd_test.assert_frame_equal(test_call, expected_call, check_less_precise=True)901 # put902 test_put = self.put_opt.vega(**self.vector_params)903 expected_put = copy.deepcopy(-expected_call)904 pd_test.assert_frame_equal(test_put, expected_put, check_less_precise=True)905 # assert call and put vega coincide906 pd_test.assert_frame_equal(test_call, -test_put)907 def test_theta_scalar(self):908 """Test Theta - scalar case"""909 # call910 test_call = scalarize(self.call_opt.theta(**self.scalar_params))911 expected_call = -3.094863279105034e-05912 self.assertEqual(test_call, expected_call)913 # put914 test_put = scalarize(self.put_opt.theta(**self.scalar_params))915 expected_put = 0.00016399568592748338916 self.assertEqual(test_put, expected_put)917 def test_theta_vector_np(self):918 """Test Theta - np.ndarray output case"""919 # call920 test_call = self.call_opt.theta(**self.vector_params)921 expected_call = np.array([[-4.59532646e-04, -2.10225482e-05, 3.62119705e-04],922 [-6.54200322e-04, -3.63343877e-05, 5.11024346e-04],923 [-1.01554953e-03, -6.06935961e-05, 8.07873242e-04],924 [-1.83825681e-03, -1.12254822e-04, 1.58102099e-03],925 [-4.36449645e-04, -4.24665854e-04, 9.75289889e-04]])926 np_test.assert_allclose(test_call, expected_call)927 # put928 test_put = self.put_opt.theta(**self.vector_params)929 expected_put = np.array([[0.0005918, 0.00015329, -0.00022985],930 [0.00078759, 0.00016973, -0.00037763],931 [0.00115006, 0.00019521, -0.00067336],932 [0.00197392, 0.00024792, -0.00144536],933 [0.00057325, 0.00056146, -0.00083849]])934 np_test.assert_allclose(test_put, expected_put, rtol=5e-5)935 def test_theta_vector_df(self):936 """Test Theta - pd.DataFrame output case"""937 # request Pandas DataFrame as output format938 self.vector_params["np_output"] = False939 # call940 test_call = self.call_opt.theta(**self.vector_params)941 expected_call = pd.DataFrame(data=[[-4.59532646e-04, -2.10225482e-05, 3.62119705e-04],942 [-6.54200322e-04, -3.63343877e-05, 5.11024346e-04],943 [-1.01554953e-03, -6.06935961e-05, 8.07873242e-04],944 [-1.83825681e-03, -1.12254822e-04, 1.58102099e-03],945 [-4.36449645e-04, -4.24665854e-04, 9.75289889e-04]],946 index=self.vector_params["t"],947 columns=self.vector_params["S"])948 expected_call.rename_axis("S", axis='columns', inplace=True)949 expected_call.rename_axis("t", axis='rows', inplace=True)950 pd_test.assert_frame_equal(test_call, expected_call, check_less_precise=True)951 # put952 test_put = self.put_opt.theta(**self.vector_params)953 expected_put = pd.DataFrame(data=[[0.0005918, 0.00015329, -0.00022985],954 [0.00078759, 0.00016973, -0.00037763],955 [0.00115006, 0.00019521, -0.00067336],956 [0.00197392, 0.00024792, -0.00144536],957 [0.00057325, 0.00056146, -0.00083849]],958 index=self.vector_params["t"],959 columns=self.vector_params["S"])960 expected_put.rename_axis("S", axis='columns', inplace=True)961 expected_put.rename_axis("t", axis='rows', inplace=True)962 pd_test.assert_frame_equal(test_put, expected_put, check_less_precise=True)963 def test_rho_scalar(self):964 """Test Rho - scalar case"""965 # call966 test_call = scalarize(self.call_opt.rho(**self.scalar_params))967 expected_call = 0.011610379741045512968 self.assertEqual(test_call, expected_call)969 # put970 test_put = scalarize(self.put_opt.rho(**self.scalar_params))971 expected_put = -0.01727818420465756972 self.assertEqual(test_put, expected_put)973 def test_rho_vector_np(self):974 """Test Rho - np.ndarray output case"""975 # call976 test_call = self.call_opt.rho(**self.vector_params)977 expected_call = np.array([[1.21286837e-02, 1.22783358e-02, 7.54978064e-03],978 [1.03369366e-02, 1.12633572e-02, 6.56155667e-03],979 [7.93101136e-03, 9.85705868e-03, 5.12733711e-03],980 [4.36037779e-03, 7.67938163e-03, 2.83056260e-03],981 [2.23107982e-05, 3.15662549e-03, -2.24454016e-04]])982 np_test.assert_allclose(test_call, expected_call)983 # put984 test_put = self.put_opt.rho(**self.vector_params)985 expected_put = np.array([[-1.89006853e-02, -1.90503374e-02, -1.43217822e-02],986 [-1.55126157e-02, -1.64390362e-02, -1.17372358e-02],987 [-1.15090604e-02, -1.34351077e-02, -8.70538615e-03],988 [-6.28675585e-03, -9.60575970e-03, -4.75694066e-03],989 [-2.95908353e-04, -3.43022305e-03, -4.91435388e-05]])990 np_test.assert_allclose(test_put, expected_put)991 def test_rho_vector_df(self):992 """Test Theta - pd.DataFrame output case"""993 # request Pandas DataFrame as output format994 self.vector_params["np_output"] = False995 # call996 test_call = self.call_opt.rho(**self.vector_params)997 expected_call = pd.DataFrame(data=[[1.21286837e-02, 1.22783358e-02, 7.54978064e-03],998 [1.03369366e-02, 1.12633572e-02, 6.56155667e-03],999 [7.93101136e-03, 9.85705868e-03, 5.12733711e-03],1000 [4.36037779e-03, 7.67938163e-03, 2.83056260e-03],1001 [2.23107982e-05, 3.15662549e-03, -2.24454016e-04]],1002 index=self.vector_params["t"],1003 columns=self.vector_params["S"])1004 expected_call.rename_axis("S", axis='columns', inplace=True)1005 expected_call.rename_axis("t", axis='rows', inplace=True)1006 pd_test.assert_frame_equal(test_call, expected_call)1007 # put1008 test_put = self.put_opt.rho(**self.vector_params)1009 expected_put = pd.DataFrame(data=[[-1.89006853e-02, -1.90503374e-02, -1.43217822e-02],1010 [-1.55126157e-02, -1.64390362e-02, -1.17372358e-02],1011 [-1.15090604e-02, -1.34351077e-02, -8.70538615e-03],1012 [-6.28675585e-03, -9.60575970e-03, -4.75694066e-03],1013 [-2.95908353e-04, -3.43022305e-03, -4.91435388e-05]],1014 index=self.vector_params["t"],1015 columns=self.vector_params["S"])1016 expected_put.rename_axis("S", axis='columns', inplace=True)1017 expected_put.rename_axis("t", axis='rows', inplace=True)1018 pd_test.assert_frame_equal(test_put, expected_put)1019 def test_Implied_Vol_scalar(self):1020 """Test Implied Volatility - scalar case"""1021 # call1022 test_call = scalarize(self.call_opt.implied_volatility(**self.scalar_params))1023 expected_call = 0.21024 self.assertAlmostEqual(test_call, expected_call)1025 # put1026 test_put = scalarize(self.put_opt.implied_volatility(**self.scalar_params))1027 expected_put = 0.21028 self.assertAlmostEqual(test_put, expected_put)1029 def test_Implied_Vol_vector_np(self):1030 """Test Implied Volatility - np.ndarray output case"""1031 # call1032 test_call = self.call_opt.implied_volatility(**self.vector_params)1033 expected_call = 0.2 + np.zeros_like(test_call)1034 np_test.assert_allclose(test_call, expected_call, rtol=5e-7)1035 # put1036 test_put = self.put_opt.implied_volatility(**self.vector_params)1037 expected_put = 0.2 + np.zeros_like(test_put)1038 np_test.assert_allclose(test_put, expected_put, rtol=5e-7)1039 def test_Implied_Vol_vector_df(self):1040 """Test Implied Volatility - pd.DataFrame output case"""1041 # request Pandas DataFrame as output format1042 self.vector_params["np_output"] = False1043 # call1044 test_call = self.call_opt.implied_volatility(**self.vector_params)1045 expected_call = pd.DataFrame(data=0.2 + np.zeros_like(test_call),1046 index=self.vector_params["t"],1047 columns=self.vector_params["S"])1048 expected_call.rename_axis("S", axis='columns', inplace=True)1049 expected_call.rename_axis("t", axis='rows', inplace=True)1050 pd_test.assert_frame_equal(test_call, expected_call)1051 # put1052 test_put = self.put_opt.implied_volatility(**self.vector_params)1053 expected_put = pd.DataFrame(data=0.2 + np.zeros_like(test_put),1054 index=self.vector_params["t"],1055 columns=self.vector_params["S"])1056 expected_put.rename_axis("S", axis='columns', inplace=True)1057 expected_put.rename_axis("t", axis='rows', inplace=True)1058 pd_test.assert_frame_equal(test_put, expected_put)1059 def test_complex_parameters_setup(self):1060 """1061 Test complex parameter setup:1062 (S scalar, K and t vector, sigma distributed as Kxt grid, r distributed as Kxt grid)1063 """1064 # call1065 test_call_price = self.call_opt.price(**self.complex_params)1066 test_call_PnL = self.call_opt.PnL(**self.complex_params)1067 test_call_delta = self.call_opt.delta(**self.complex_params)1068 test_call_gamma = self.call_opt.gamma(**self.complex_params)1069 test_call_vega = self.call_opt.vega(**self.complex_params)1070 test_call_theta = self.call_opt.theta(**self.complex_params)1071 test_call_rho = self.call_opt.rho(**self.complex_params)1072 test_call_iv = self.call_opt.implied_volatility(**self.complex_params)1073 expected_call_price = pd.DataFrame(data=[[0.9798568, 0.62471855, 0.47323669, 0.39201772],1074 [0.68363866, 0.50365944, 0.42894149, 0.37368724],1075 [0.87602123, 0.60825314, 0.46889718, 0.36012104]],1076 index=self.complex_params["t"],1077 columns=self.complex_params["K"])1078 expected_call_price.rename_axis("K", axis='columns', inplace=True)1079 expected_call_price.rename_axis("t", axis='rows', inplace=True)1080 expected_call_PnL = pd.DataFrame(data=[[0.68311074, 0.3279725, 0.17649063, 0.09527166],1081 [0.3868926, 0.20691339, 0.13219544, 0.07694118],1082 [0.57927518, 0.31150708, 0.17215112, 0.06337498]],1083 index=self.complex_params["t"],1084 columns=self.complex_params["K"])1085 expected_call_PnL.rename_axis("K", axis='columns', inplace=True)1086 expected_call_PnL.rename_axis("t", axis='rows', inplace=True)1087 expected_call_delta = pd.DataFrame(data=[[0.00448245, 0.02461979, 0.01726052, 0.01248533],1088 [0.01263986, 0.01196584, 0.01011038, 0.00854062],1089 [0.01504177, 0.02568663, 0.02420515, 0.02088546]],1090 index=self.complex_params["t"],1091 columns=self.complex_params["K"])1092 expected_call_delta.rename_axis("K", axis='columns', inplace=True)1093 expected_call_delta.rename_axis("t", axis='rows', inplace=True)1094 expected_call_gamma = pd.DataFrame(data=[[-1.36939276e-03, -8.30886510e-04, -1.59819664e-04, -3.72062630e-05],1095 [-3.79395726e-04, -1.46568014e-04, -7.22169767e-05, -3.73088881e-05],1096 [-1.47523572e-03, -7.66683834e-04, -1.58922692e-04, 1.82659675e-04]],1097 index=self.complex_params["t"],1098 columns=self.complex_params["K"])1099 expected_call_gamma.rename_axis("K", axis='columns', inplace=True)1100 expected_call_gamma.rename_axis("t", axis='rows', inplace=True)1101 expected_call_vega = pd.DataFrame(data=[[-0.00777965, -0.00944069, -0.00272385, -0.00084549],1102 [-0.00559895, -0.00259558, -0.00149204, -0.00088094],1103 [-0.00294643, -0.00170141, -0.00038795, 0.00048643]],1104 index=self.complex_params["t"],1105 columns=self.complex_params["K"])1106 expected_call_vega.rename_axis("K", axis='columns', inplace=True)1107 expected_call_vega.rename_axis("t", axis='rows', inplace=True)1108 expected_call_theta = pd.DataFrame(data=[[1.67739087e-04, 2.81595503e-04, 7.08163129e-05, -1.41282958e-05],1109 [9.90248652e-04, 4.91233384e-04, 3.00397593e-04, 1.78375694e-04],1110 [1.31411352e-02, 8.04031544e-03, 1.61848869e-03, -3.41813594e-03]],1111 index=self.complex_params["t"],1112 columns=self.complex_params["K"])1113 expected_call_theta.rename_axis("K", axis='columns', inplace=True)1114 expected_call_theta.rename_axis("t", axis='rows', inplace=True)1115 expected_call_rho = pd.DataFrame(data=[[-0.00404295, 0.01115923, 0.00757627, 0.00513166],1116 [0.00165411, 0.00208889, 0.00175266, 0.0014392],1117 [0.00013089, 0.00046672, 0.00046837, 0.00041632]],1118 index=self.complex_params["t"],1119 columns=self.complex_params["K"])1120 expected_call_rho.rename_axis("K", axis='columns', inplace=True)1121 expected_call_rho.rename_axis("t", axis='rows', inplace=True)1122 expected_call_iv = pd.DataFrame(data=self.complex_params["sigma"],1123 index=self.complex_params["t"],1124 columns=self.complex_params["K"])1125 expected_call_iv.rename_axis("K", axis='columns', inplace=True)1126 expected_call_iv.rename_axis("t", axis='rows', inplace=True)1127 pd_test.assert_frame_equal(test_call_price, expected_call_price)1128 pd_test.assert_frame_equal(test_call_PnL, expected_call_PnL)1129 pd_test.assert_frame_equal(test_call_delta, expected_call_delta)1130 pd_test.assert_frame_equal(test_call_gamma, expected_call_gamma)1131 pd_test.assert_frame_equal(test_call_vega, expected_call_vega, check_less_precise=True)1132 pd_test.assert_frame_equal(test_call_theta, expected_call_theta)1133 pd_test.assert_frame_equal(test_call_rho, expected_call_rho, check_less_precise=True)1134 pd_test.assert_frame_equal(test_call_iv.iloc[:, :-1], expected_call_iv.iloc[:, :-1])1135 self.assertAlmostEqual(test_call_iv.iloc[-1, -1], expected_call_iv.iloc[-1, -1], places=5)1136 # put1137 test_put_price = self.put_opt.price(**self.complex_params)1138 test_put_PnL = self.put_opt.PnL(**self.complex_params)1139 test_put_delta = self.put_opt.delta(**self.complex_params)1140 test_put_gamma = self.put_opt.gamma(**self.complex_params)1141 test_put_vega = self.put_opt.vega(**self.complex_params)1142 test_put_theta = self.put_opt.theta(**self.complex_params)1143 test_put_rho = self.put_opt.rho(**self.complex_params)1144 test_put_iv = self.put_opt.implied_volatility(**self.complex_params)1145 expected_put_price = pd.DataFrame(data=[[0.01315404, 0.36135198, 0.50594203, 0.58031737],1146 [0.29830713, 0.47471481, 0.54587421, 0.59758286],1147 [0.12151605, 0.38901089, 0.52809366, 0.63659669]],1148 index=self.complex_params["t"],1149 columns=self.complex_params["K"])1150 expected_put_price.rename_axis("K", axis='columns', inplace=True)1151 expected_put_price.rename_axis("t", axis='rows', inplace=True)1152 expected_put_PnL = pd.DataFrame(data=[[-0.65563919, -0.30744125, -0.16285119, -0.08847586],1153 [-0.37048609, -0.19407842, -0.12291901, -0.07121037],1154 [-0.54727717, -0.27978234, -0.14069957, -0.03219654]],1155 index=self.complex_params["t"],1156 columns=self.complex_params["K"])1157 expected_put_PnL.rename_axis("K", axis='columns', inplace=True)1158 expected_put_PnL.rename_axis("t", axis='rows', inplace=True)1159 expected_put_delta = copy.deepcopy(-expected_call_delta)1160 expected_put_gamma = copy.deepcopy(-expected_call_gamma)1161 expected_put_vega = copy.deepcopy(-expected_call_vega)1162 expected_put_theta = pd.DataFrame(data=[[-1.40533310e-04, -2.27564242e-04, 9.66413009e-06, 1.20685566e-04],1163 [-8.55735531e-04, -3.30404740e-04, -1.13446636e-04, 3.45054237e-05],1164 [-1.28951671e-02, -7.76709242e-03, -1.31802569e-03, 3.74582396e-03]],1165 index=self.complex_params["t"],1166 columns=self.complex_params["K"])1167 expected_put_theta.rename_axis("K", axis='columns', inplace=True)1168 expected_put_theta.rename_axis("t", axis='rows', inplace=True)1169 expected_put_rho = pd.DataFrame(data=[[-0.00292173, -0.01807524, -0.01444393, -0.01195132],1170 [-0.00523216, -0.00565392, -0.00530473, -0.00497835],1171 [-0.00040418, -0.00073995, -0.00074152, -0.00068939]],1172 index=self.complex_params["t"],1173 columns=self.complex_params["K"])1174 expected_put_rho.rename_axis("K", axis='columns', inplace=True)1175 expected_put_rho.rename_axis("t", axis='rows', inplace=True)1176 expected_put_iv = pd.DataFrame(data=self.complex_params["sigma"],1177 index=self.complex_params["t"],1178 columns=self.complex_params["K"])1179 expected_put_iv.rename_axis("K", axis='columns', inplace=True)1180 expected_put_iv.rename_axis("t", axis='rows', inplace=True)1181 pd_test.assert_frame_equal(test_put_price, expected_put_price)1182 pd_test.assert_frame_equal(test_put_PnL, expected_put_PnL)1183 pd_test.assert_frame_equal(test_put_delta, expected_put_delta)1184 pd_test.assert_frame_equal(test_put_gamma, expected_put_gamma)1185 pd_test.assert_frame_equal(test_put_vega, expected_put_vega, check_less_precise=True)1186 pd_test.assert_frame_equal(test_put_theta, expected_put_theta)1187 pd_test.assert_frame_equal(test_put_rho, expected_put_rho, check_less_precise=True)1188 pd_test.assert_frame_equal(test_put_iv.iloc[:, :-1], expected_put_iv.iloc[:, :-1])1189 self.assertAlmostEqual(test_put_iv.iloc[-1, -1], expected_put_iv.iloc[-1, -1], places=5)1190 # test gamma and vega consistency1191 pd_test.assert_frame_equal(test_call_delta, -test_put_delta)1192 pd_test.assert_frame_equal(test_call_gamma, -test_put_gamma)1193 pd_test.assert_frame_equal(test_call_vega, -test_put_vega)1194if __name__ == '__main__':...

Full Screen

Full Screen

tests.py

Source:tests.py Github

copy

Full Screen

...299#300## # general.py tests301#302#class TestLook(CommandTest):303# def test_call(self):304# self.execute_cmd("look here")305#class TestHome(CommandTest):306# def test_call(self):307# self.char1.location = self.room1308# self.char1.home = self.room2309# self.execute_cmd("home")310# self.assertEqual(self.char1.location, self.room2)311#class TestPassword(CommandTest):312# def test_call(self):313# self.execute_cmd("@password testpassword = newpassword")314#class TestInventory(CommandTest):315# def test_call(self):316# self.execute_cmd("inv")317#class TestQuit(CommandTest):318# def test_call(self):319# self.execute_cmd("@quit")320#class TestPose(CommandTest):321# def test_call(self):322# self.execute_cmd("pose is testing","TestChar is testing")323#class TestNick(CommandTest):324# def test_call(self):325# self.char1.player.user.is_superuser = False326# self.execute_cmd("nickname testalias = testaliasedstring1")327# self.execute_cmd("nickname/player testalias = testaliasedstring2")328# self.execute_cmd("nickname/object testalias = testaliasedstring3")329# self.assertEqual(u"testaliasedstring1", self.char1.nicks.get("testalias"))330# self.assertEqual(u"testaliasedstring2", self.char1.nicks.get("testalias",nick_type="player"))331# self.assertEqual(u"testaliasedstring3", self.char1.nicks.get("testalias",nick_type="object"))332#class TestGet(CommandTest):333# def test_call(self):334# self.obj1.location = self.room1335# self.execute_cmd("get obj1", "You pick up obj1.")336#class TestDrop(CommandTest):337# def test_call(self):338# self.obj1.location = self.char1339# self.execute_cmd("drop obj1", "You drop obj1.")340#class TestWho(CommandTest):341# def test_call(self):342# self.execute_cmd("who")343#class TestSay(CommandTest):344# def test_call(self):345# self.execute_cmd("say Hello", 'You say, "Hello')346#class TestAccess(CommandTest):347# def test_call(self):348# self.execute_cmd("access")349#class TestEncoding(CommandTest):350# def test_call(self):351# global NOMANGLE352# NOMANGLE = True353# self.char1.db.encoding="utf-8"354# self.execute_cmd("@encoding", "Default encoding:")355# NOMANGLE = False356#357## help.py command tests358#359#class TestHelpSystem(CommandTest):360# def test_call(self):361# self.NOMANGLE = True362# sep = "-"*78 + "\n"363# self.execute_cmd("@help/add TestTopic,TestCategory = Test1", )364# self.execute_cmd("help TestTopic",sep + "Help topic for Testtopic\nTest1" + "\n" + sep)365# self.execute_cmd("@help/merge TestTopic = Test2", "Added the new text right after")366# self.execute_cmd("help TestTopic", sep + "Help topic for Testtopic\nTest1 Test2")367# self.execute_cmd("@help/append TestTopic = Test3", "Added the new text as a")368# self.execute_cmd("help TestTopic",sep + "Help topic for Testtopic\nTest1 Test2\n\nTest3")369# self.execute_cmd("@help/delete TestTopic","Deleted the help entry")370# self.execute_cmd("help TestTopic","No help entry found for 'TestTopic'")371#372## system.py command tests373#class TestPy(CommandTest):374# def test_call(self):375# self.execute_cmd("@py 1+2", [">>> 1+2", "<<< 3"])376#class TestScripts(CommandTest):377# def test_call(self):378# script = create.create_script(None, "test")379# self.execute_cmd("@scripts", "id")380#class TestObjects(CommandTest):381# def test_call(self):382# self.execute_cmd("@objects", "Database totals")383## Cannot be tested since we don't have an active server running at this point.384## class TestListService(CommandTest):385## def test_call(self):386## self.execute_cmd("@service/list", "---")387#class TestVersion(CommandTest):388# def test_call(self):389# self.execute_cmd("@version", '---')390#class TestTime(CommandTest):391# def test_call(self):392# self.execute_cmd("@time", "Current server uptime")393#class TestServerLoad(CommandTest):394# def test_call(self):395# self.execute_cmd("@serverload", "Server load")396#class TestPs(CommandTest):397# def test_call(self):398# self.execute_cmd("@ps","Non-timed scripts")399#400## admin.py command tests401#402#class TestBoot(CommandTest):403# def test_call(self):404# self.execute_cmd("@boot TestChar2","You booted TestChar2.")405#class TestDelPlayer(CommandTest):406# def test_call(self):407# self.execute_cmd("@delplayer TestChar2","Booting and informing player ...")408#class TestEmit(CommandTest):409# def test_call(self):410# self.execute_cmd("@emit Test message", "Emitted to room1.")411#class TestUserPassword(CommandTest):412# def test_call(self):413# self.execute_cmd("@userpassword TestChar2 = newpass", "TestChar2 - new password set to 'newpass'.")414#class TestPerm(CommandTest):415# def test_call(self):416# self.execute_cmd("@perm TestChar2 = Builders", "Permission 'Builders' given to")417## cannot test this here; screws up the test suite418##class TestPuppet(CommandTest):419## def test_call(self):420## self.execute_cmd("@puppet TestChar3", "You now control TestChar3.")421## self.execute_cmd("@puppet TestChar", "You now control TestChar.")422#class TestWall(CommandTest):423# def test_call(self):424# self.execute_cmd("@wall = This is a test message", "TestChar shouts")425#426#427## building.py command tests428#429#class TestObjAlias(BuildTest):430# def test_call(self):431# self.execute_cmd("@alias obj1 = obj1alias, obj1alias2", "Aliases for")432# self.execute_cmd("look obj1alias2", "obj1")433#class TestCopy(BuildTest):434# def test_call(self):435# self.execute_cmd("@copy obj1 = obj1_copy;alias1;alias2", "Copied obj1 to 'obj1_copy'")436# self.execute_cmd("look alias2","obj1_copy")437#class TestSet(BuildTest):438# def test_call(self):439# self.execute_cmd("@set obj1/test = value", "Created attribute obj1/test = value")440# self.execute_cmd("@set obj1/test", "Attribute obj1/test = value")441# self.assertEqual(self.obj1.db.test, u"value")442#class TestCpAttr(BuildTest):443# def test_call(self):444# self.execute_cmd("@set obj1/test = value")445# self.execute_cmd("@set obj2/test2 = value2")446# #self.execute_cmd("@cpattr obj1/test = obj2/test") # can't be tested since instances changes447# #self.assertEqual(self.obj2.db.test, u"value")448#class TestMvAttr(BuildTest):449# def test_call(self):450# self.execute_cmd("@set obj1/test = value")451# self.execute_cmd("@mvattr obj1/test = obj2")452# #self.assertEqual(self.obj2.db.test, u"value")453# #self.assertEqual(self.obj1.db.test, None)454#class TestCreate(BuildTest):455# def test_call(self):456# self.execute_cmd("@create testobj;alias1;alias2")457# self.execute_cmd("look alias1", "testobj")458#class TestDebug(BuildTest):459# def test_call(self):460# self.execute_cmd("@debug/obj obj1")461#class TestDesc(BuildTest):462# def test_call(self):463# self.execute_cmd("@desc obj1 = Test object", "The description was set on")464# #self.assertEqual(self.obj1.db.desc, u"Test object")465#class TestDestroy(BuildTest):466# def test_call(self):467# self.execute_cmd("@destroy obj1, obj2", "obj1 was destroyed.\nobj2 was destroyed.")468#class TestFind(BuildTest):469# def test_call(self):470# self.execute_cmd("@find obj1", "One Match")471#class TestDig(BuildTest):472# def test_call(self):473# self.execute_cmd("@dig room3;roomalias1;roomalias2 = north;n,south;s")474# self.execute_cmd("@find room3", "One Match")475# self.execute_cmd("@find roomalias1", "One Match")476# self.execute_cmd("@find roomalias2", "One Match")477# self.execute_cmd("@find/room roomalias2", "One Match")478# self.execute_cmd("@find/exit south", "One Match")479# self.execute_cmd("@find/exit n", "One Match")480#class TestUnLink(BuildTest):481# def test_call(self):482# self.execute_cmd("@dig room3;roomalias1, north, south")483# self.execute_cmd("@unlink north")484#class TestLink(BuildTest):485# def test_call(self):486# self.execute_cmd("@dig room3;roomalias1, north, south")487# self.execute_cmd("@unlink north")488# self.execute_cmd("@link north = room3")489#class TestHome(BuildTest):490# def test_call(self):491# self.obj1.db_home = self.obj2.dbobj492# self.obj1.save()493# self.execute_cmd("@home obj1")494# self.assertEqual(self.obj1.db_home, self.obj2.dbobj)495#class TestCmdSets(BuildTest):496# def test_call(self):497# self.execute_cmd("@cmdsets")498# self.execute_cmd("@cmdsets obj1")499#class TestName(BuildTest):500# def test_call(self):501# self.execute_cmd("@name obj1 = Test object", "Object's name changed to 'Test object'.")502# #self.assertEqual(self.obj1.key, u"Test object")503#class TestOpen(BuildTest):504# def test_call(self):505# self.execute_cmd("@dig room4;roomalias4")506# self.execute_cmd("@open testexit4;aliasexit4 = roomalias4", "Created new Exit")507#class TestTypeclass(BuildTest):508# def test_call(self):509# self.execute_cmd("@typeclass obj1 = src.objects.objects.Character", "obj's type is now")510# #self.assertEqual(self.obj1.db_typeclass_path, u"src.objects.objects.Character")511#class TestSet(BuildTest):512# def test_call(self):513# self.execute_cmd("@set box1/test = value")514# self.execute_cmd("@wipe box1", "Wiped")515# self.assertEqual(self.obj1.db.all, [])516#class TestLock(BuildTest):517# # lock functionality itseld is tested separately518# def test_call(self):519# self.char1.permissions = ["TestPerm"]520# self.execute_cmd("@lock obj1 = test:perm(TestPerm)")521# #self.assertEqual(True, self.obj1.access(self.char1, u"test"))522#class TestExamine(BuildTest):523# def test_call(self):524# self.execute_cmd("examine obj1", "------------")525#class TestTeleport(BuildTest):526# def test_call(self):527# self.execute_cmd("@tel obj1 = room1")528# self.assertEqual(self.obj1.location.key, self.room1.key)529#class TestScript(BuildTest):530# def test_call(self):531# self.execute_cmd("@script TestChar = examples.bodyfunctions.BodyFunctions", "Script successfully added")532#533## Comms commands534#535#class TestChannelCreate(CommandTest):536# def test_call(self):537# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")538# self.execute_cmd("testchan1 Hello", "[testchannel1] TestChar: Hello")539#class TestAddCom(CommandTest):540# def test_call(self):541# self.execute_cmd("@cdestroy testchannel1", "Channel 'testchannel1'")542# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")543# self.execute_cmd("addcom chan1 = testchannel1")544# self.execute_cmd("addcom chan2 = testchan1")545# self.execute_cmd("delcom testchannel1")546# self.execute_cmd("addcom testchannel1" "You now listen to the channel channel.")547#class TestDelCom(CommandTest):548# def test_call(self):549# self.execute_cmd("@cdestroy testchannel1", "Channel 'testchannel1'")550# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")551# self.execute_cmd("addcom chan1 = testchan1")552# self.execute_cmd("addcom chan2 = testchan1b")553# self.execute_cmd("addcom chan3 = testchannel1")554# self.execute_cmd("delcom chan1", "Your alias 'chan1' for ")555# self.execute_cmd("delcom chan2", "Your alias 'chan2' for ")556# self.execute_cmd("delcom testchannel1" "You stop listening to")557#class TestAllCom(CommandTest):558# def test_call(self):559# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")560# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")561# self.execute_cmd("allcom off")562# self.execute_cmd("allcom on")563# self.execute_cmd("allcom destroy")564#class TestChannels(CommandTest):565# def test_call(self):566# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")567# self.execute_cmd("@cdestroy testchannel1", "Channel 'testchannel1'")568#class TestCBoot(CommandTest):569# def test_call(self):570# self.execute_cmd("@cdestroy testchannel1", "Channel 'testchannel1'")571# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")572# self.execute_cmd("addcom testchan = testchannel1")573# self.execute_cmd("@cboot testchannel1 = TestChar", "TestChar boots TestChar from channel.")574#class TestCemit(CommandTest):575# def test_call(self):576# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")577# self.execute_cmd("@cemit testchan1 = Testing!", "[testchannel1] Testing!")578#class TestCwho(CommandTest):579# def test_call(self):580# self.execute_cmd("@ccreate testchannel1;testchan1;testchan1b = This is a test channel")581# self.execute_cmd("@cwho testchan1b", "Channel subscriptions")582#583# OOC commands584#class TestOOC_and_IC(CommandTest): # can't be tested it seems, causes errors in other commands (?)585# def test_call(self):586# self.execute_cmd("@ooc", "\nYou go OOC.")587# self.execute_cmd("@ic", "\nYou become TestChar")588# Unloggedin commands...

Full Screen

Full Screen

tasks.py

Source:tasks.py Github

copy

Full Screen

1import json2import os3import random4if os.name == "nt":5 import multiprocessing6else:7 import billiard as multiprocessing8from .LoadTester import load_tests, abstract9from .LoadTester.proc_func import process_function10from .celery import app11from .models import TestCall, Result12import typing13import inspect14import requests15from datetime import datetime16import time17from .serializers import TestCallSerializer18def filter_classes(o):19 return inspect.isclass(o) and 'LoadTesterBase' in map(lambda x: x.__name__, inspect.getmro(o))20@app.task21def run_test(test_call_str: str):22 test_call_dict = TestCallSerializer(test_call_str).instance23 test_call = TestCall.objects.get(pk = test_call_dict['id'])24 classes = inspect.getmembers(load_tests, filter_classes)25 print(classes)26 print(test_call)27 needed_class = list(filter(lambda x: x[0] == test_call.test.class_name, classes))28 if len(needed_class) != 1:29 raise TypeError('Cannot find described class: %s' % test_call.test.class_name)30 needed_class = needed_class[0]31 counter = multiprocessing.Value('i', 0)32 lock = multiprocessing.Lock()33 processes = []34 for i in range(test_call.num_users):35 from django import db36 db.connections.close_all()37 proc = multiprocessing.Process(target=process_function, args=(needed_class, test_call.max_calls, counter, lock, test_call_dict))38 proc.start()39 processes.append(proc)40 timestamp = time.time()41 est = test_call.max_calls / test_call.num_users42 rand = random.randint(5, 30)43 m_t = min(random.randint(720, 900), (rand if rand > est else est) + random.randint(0, test_call.num_users))44 for proc in processes:45 print("WAITING FOR: ", proc)46 proc.join(timeout=(m_t - max((time.time() - timestamp), 0)))47 for proc in processes:48 if proc.is_alive():49 proc.terminate()50 try:51 print("WAITING FISHED")52 result = requests.post("%s/rest-auth/login/" % os.getenv("BACKEND_URL"),53 json={"username": os.getenv("BACKEND_USER"), "password": os.getenv("BACKEND_PASSWORD")})54 print("STARTING FILE WRITTING")55 with open('prices%s.txt' % test_call.start_date.strftime("%m-%d-%Y %H-%M-%S"), 'w') as f:56 f.write(json.dumps(requests.get("%s/price_history/" % os.getenv("BACKEND_URL"), headers={"OBCIAZNIK": "DUPA", "Authorization": "Bearer %s" % result.json()['token']}).json()))57 with open('transactions%s.txt' % test_call.start_date.strftime("%m-%d-%Y %H-%M-%S"), 'w') as f:58 f.write(json.dumps(requests.get("%s/transaction/" % os.getenv("BACKEND_URL"), headers={"OBCIAZNIK": "DUPA", "Authorization": "Bearer %s" % result.json()['token']}).json()))59 print("FILE FINISHED")60 except Exception:61 pass62 test_call.is_finished = True63 test_call.end_date = datetime.now()64 test_call.save()...

Full Screen

Full Screen

pipeline.py

Source:pipeline.py Github

copy

Full Screen

...3import joinDataFrames as joindf4import toCSVDataFrame as tocsv5import selectDataFrame as selectdf6import json7msg_oh = fromcsv.api.test_call(fromcsv.test.ORDER_HEADERS)8info_str = json.dumps(msg_oh.attributes, indent=4)9print(info_str)10msg_oh = sampledf.api.test_call(msg_oh,sampledf.test.BIGDATA)11info_str = json.dumps(msg_oh.attributes, indent=4)12print(info_str)13msg_od = fromcsv.api.test_call(fromcsv.test.ORDER_DETAILS)14info_str = json.dumps(msg_od.attributes, indent=4)15print(info_str)16msg = joindf.api.test_call(msg_oh,msg_od,joindf.test.ORDER_HEADER_DETAIL)17info_str = json.dumps(msg.attributes, indent=4)18print(info_str)19#msg = selectdf.api.test_call(msg)20#info_str = json.dumps(msg.attributes, indent=4)21#print(info_str)22msg_pmd = fromcsv.api.test_call(fromcsv.test.PRODUCTS_MD)23info_str = json.dumps(msg_pmd.attributes, indent=4)24print(info_str)25msg = joindf.api.test_call(msg,msg_pmd,joindf.test.ORDER_PRODUCT_MD)26info_str = json.dumps(msg.attributes, indent=4)27print(info_str)28csv = tocsv.api.test_call(msg)29with open(r"/Users/d051079/OneDrive - SAP SE/Datahub-Dev/data/sample_pos.csv", 'w') as fd:30 if isinstance(csv.body,list) :31 for s in csv.body :32 fd.write(s)33 else :34 fd.write(csv.body)...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Testify automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful