def main(): start_date = str_to_date("2017-01-01") end_date = str_to_date("2018-01-01") session_builder = container.resolve( BacktestTradingSessionBuilder) # type: BacktestTradingSessionBuilder session_builder.set_backtest_name('SPY w. stop ' + str(SpxWithStopLoss.percentage)) session_builder.set_initial_cash(1000000) session_builder.set_commission_model(IBCommissionModel()) ts = session_builder.build(start_date, end_date) ts.use_data_preloading(SpxWithStopLoss.ticker, RelativeDelta(days=40)) SpxWithStopLoss(ts) ts.start_trading() actual_end_value = ts.portfolio.get_portfolio_timeseries()[-1] expected_value = 1137843 print("Expected End Value = {}".format(expected_value)) print("Actual End Value = {}".format(actual_end_value)) print("DIFF = {}".format(expected_value - actual_end_value)) test = TestCase() test.assertAlmostEqual(expected_value, actual_end_value, delta=10)
def test_parse_rinex_glo_nav(self): navigations = parse_rinex('../../test_data/log_000.15g') g = navigations['R03'] z1, z2 = sorted([g[0], g[1]], key=lambda x: x.date) t1, t2 = z1.eph[8], z2.eph[8] delta_t = dt.timedelta(seconds=t2-t1) TestCase.assertAlmostEqual(self, delta_t.total_seconds(), 5469.878906, places=10)
def check_result_row(row, test_obj: unittest.TestCase): if type(row[0]) == float: test_obj.assertAlmostEqual(row[0], row[1], places=row[2]) elif type(row[0]) == int: test_obj.assertEqual(row[0], row[1]) elif type(row[0]) == tuple: # e.g. (tuple, tuple, int) for i in range(0, len(row[0])): check_result_row((row[0][i], row[1][i], row[2]), test_obj)
def test_parse_rinex_glo_nav(self): """ Test GLONASS RINEX file """ navigations = parse_rinex('log_000.15g') g = navigations['R03'] z1, z2 = sorted([g[0], g[1]], key=lambda x: x.date) t1, t2 = z1.eph[8], z2.eph[8] delta_t = dt.timedelta(seconds=t2-t1) TestCase.assertAlmostEqual(self, delta_t.total_seconds(), 5469.878906, places=10)
def assert_arrays_almost_equal(test: unittest.TestCase, actuals: np.ndarray, desires: np.ndarray, dif_ratio=1e-3, limit=1e-8): assert(isinstance(actuals, np.ndarray)) assert(isinstance(desires, np.ndarray)) test.assertEqual(len(actuals.shape), len(desires.shape)) for _, (a, b) in enumerate(zip(actuals.shape, desires.shape)): test.assertEqual(a, b) for _, (input, ref) in enumerate(zip(actuals.ravel(), desires.ravel())): delta = max(abs(ref * dif_ratio), limit) test.assertAlmostEqual(input, ref, delta=delta)
def test_parse_ionex(self): ionex = "../../test_data/iter_0/igsg0010.16i" M = parse_ionex(ionex) dttimes = [dt.datetime(2016, 1, 1, x, 00) for x in range(24)] p = (60.1, 30.1) correct_vals = [0.913819144802, 0.896627150059, 0.782946952107, 0.643969126833, 0.55367705622, 0.553352311325, 0.617950565843, 0.906993007108, 1.10022271455, 1.33549389609, 1.66625306657, 1.60813672016, 1.4551818746, 1.28501554961, 0.919015063122, 0.570271520356, 0.420219894161, 0.389369129134, 0.388706649548, 0.291458543284, 0.243870426367, 0.268882278182, 0.342268129559, 0.374430863963] vals = [M(p, tt) for tt in dttimes] for i in xrange(len(vals)): TestCase.assertAlmostEqual(self, correct_vals[i], vals[i])
def test_to_relative(dvh, query_extensions): test_case = TestCase() prescribed_dose = 7000.0 dvh.to_relative_dose(DoseValue(7000, DoseUnit.cGy)) assert dvh.dose_unit == DoseUnit.Percent # Test min dose % min_dose_pp = dvh.min_dose min_dose_target = DoseValue(3457.0138887638896 / prescribed_dose * 100, DoseUnit.Percent) test_case.assertAlmostEqual(min_dose_pp, min_dose_target) # Test mean dose % mean_dose_pp = dvh.mean_dose mean_dose = 6949.34536891202 mean_dose_target = DoseValue(mean_dose / prescribed_dose * 100, DoseUnit.Percent) test_case.assertAlmostEqual(mean_dose_pp, mean_dose_target) # Test max dose % max_dose_pp = dvh.max_dose max_dose = 7631.604166666671 max_dose_target = DoseValue(max_dose / prescribed_dose * 100, DoseUnit.Percent) test_case.assertAlmostEqual(max_dose_pp, max_dose_target) # test dose D95%[%] query_str = 'D95%[%]' # read query into que object query_extensions.read(query_str) # execute the static method md = query_extensions.query_dose(dvh, query_extensions) test_case.assertAlmostEqual(md.value, 6103.854532025905 / 7000.0 * 100)
def test_parse_ionex(self): ionex = "../../test_data/iter_0/igsg0010.16i" M = parse_ionex(ionex) dttimes = [dt.datetime(2016, 1, 1, x, 00) for x in range(24)] p = (60.1, 30.1) correct_vals = [ 0.913819144802, 0.896627150059, 0.782946952107, 0.643969126833, 0.55367705622, 0.553352311325, 0.617950565843, 0.906993007108, 1.10022271455, 1.33549389609, 1.66625306657, 1.60813672016, 1.4551818746, 1.28501554961, 0.919015063122, 0.570271520356, 0.420219894161, 0.389369129134, 0.388706649548, 0.291458543284, 0.243870426367, 0.268882278182, 0.342268129559, 0.374430863963 ] vals = [M(p, tt) for tt in dttimes] for i in xrange(len(vals)): TestCase.assertAlmostEqual(self, correct_vals[i], vals[i])
def assertDictAlmostEqual(test_case: unittest.TestCase, a, b, places=None, msg=None, delta=None): test_case.assertIsInstance(a, dict) test_case.assertIsInstance(b, dict) test_case.assertEqual(set(a.keys()), set(b.keys())) for k in a.keys(): test_case.assertAlmostEqual(a[k], b[k], places=places, msg=msg, delta=delta)
def generator(sample_lines, batch_size): num_samples = len(sample_lines) test = TestCase() while 1: lines = shuffle(sample_lines) for offset in range(0, num_samples, batch_size): batch_lines = lines[offset:offset + batch_size] images = [] steering_angles = [] for line in batch_lines: (line_images, line_steering_angles) = preprocess(line) test.assertAlmostEqual(sum(line_steering_angles), 0.0) images.extend(line_images) steering_angles.extend(line_steering_angles) X_train = np.array(images) y_train = np.array(steering_angles) yield X_train, y_train
def test_bouncing_collision(self): p1 = Particle(1, [0, 0.5, 0], [0, 0, 0], 0.1) p2 = Particle(2, [0, 0, 0], [0, 0, 0], 0.1, density=1e99, get_gravity=lambda dummy: [0, 0, 0]) col = Collision(p1, p2, 1e5, restitution=0.8) timestep = 0.0005 last_time = 0 for time in np.arange(0, 10, timestep): delta_t = time - last_time col.calculate(delta_t) p1.iterate(delta_t) p2.iterate(delta_t) last_time = time predicted_overlap = p1.get_mass() * vect.mag(p1.get_gravity(p1)) / col.stiffness print("Predicted overlap = {0}".format(predicted_overlap)) print("Calculated overlap = {0}".format(col.get_particle_overlap())) print("Percentage difference = {0}".format(100 * predicted_overlap / col.get_particle_overlap() - 100)) TestCase.assertAlmostEqual(self, predicted_overlap, col.get_particle_overlap()) particles_to_paraview([p1, p2], "bounce_col", "../../run/bounce_collision/")
def assert_velocity_properties(test_case: unittest.TestCase, data: SeismicData, velocity_prop: VelocityProperties) -> None: test_case.assertIsNotNone(data) test_case.assertIsNotNone(data.velocity_properties) test_case.assertIsNotNone(velocity_prop) for prop in dir(data.velocity_properties): if "_" in prop[0:1] or prop == "count" or prop == "index": continue if getattr(data.velocity_properties, prop) is None: test_case.assertIsNone(getattr(velocity_prop, prop)) else: try: float(getattr(data.velocity_properties, prop)) test_case.assertAlmostEqual(getattr(data.velocity_properties, prop), getattr(velocity_prop, prop), 3) except ValueError: test_case.assertEqual(getattr(data.velocity_properties, prop), getattr(velocity_prop, prop))
def assertAlmostEqual(self, a, b): if isinstance(a, str): return TestCase.assertEqual(self, a, b) if isinstance(a, numbers.Real): return TestCase.assertAlmostEqual(self, a, b) if isinstance(a, dict): a, b = sorted(a.items()), sorted(b.items()) a, b = list(a), list(b) self.assertEqual(len(a), len(b)) all(self.assertAlmostEqual(x, y) for x, y in zip(a, b))
def assert_equality( test: unittest.TestCase, key, res1, res2, delta, ignore_binary_metric=False, ignore_array_metric=False ): # res1, res2: values to compare if type(res1) == bytes: if ignore_binary_metric: return else: test.assertEqual(res1, res2, msg=f"on key {key}") elif type(res1).__module__ == "numpy": if ignore_array_metric: return else: for x1, x2 in zip(np.reshape(res1, [-1]), np.reshape(res2, [-1])): if str(res1.dtype).startswith("int"): test.assertEqual(x1, x2, msg=f"on key {key}") else: test.assertAlmostEqual(res1, res2, delta=delta, msg=f"on key {key}") else: test.assertAlmostEqual(res1, res2, delta=delta, msg=f"on key {key}")
def assert_velocity_properties(test_case: unittest.TestCase, data: SeismicData, velocity_prop: VelocityProperties) -> None: test_case.assertIsNotNone(data) test_case.assertIsNotNone(data.velocity_properties) test_case.assertIsNotNone(velocity_prop) for prop in dir(data.velocity_properties): if "_" in prop[0:1] or prop == "count" or prop == "index": continue if getattr(data.velocity_properties, prop) is None: test_case.assertIsNone(getattr(velocity_prop, prop)) else: try: float(getattr(data.velocity_properties, prop)) test_case.assertAlmostEqual( getattr(data.velocity_properties, prop), getattr(velocity_prop, prop), 3) except ValueError: test_case.assertEqual(getattr(data.velocity_properties, prop), getattr(velocity_prop, prop))
def main(): start_date = str_to_date("2010-01-01") end_date = str_to_date("2011-01-01") session_builder = container.resolve(BacktestTradingSessionBuilder) # type: BacktestTradingSessionBuilder session_builder.set_backtest_name('Simple_MA') session_builder.set_initial_cash(1000000) ts = session_builder.build(start_date, end_date) ts.use_data_preloading(SimpleMAStrategy.ticker, RelativeDelta(days=40)) SimpleMAStrategy(ts) ts.start_trading() actual_end_value = ts.portfolio.get_portfolio_timeseries()[-1] expected_value = 898294.64 print("Expected End Value = {}".format(expected_value)) print("Actual End Value = {}".format(actual_end_value)) print("DIFF = {}".format(expected_value - actual_end_value)) test = TestCase() test.assertAlmostEqual(expected_value, actual_end_value, places=2)
def compare_models(test_case: unittest.TestCase, format_model1: FormatModel, format_model2: FormatModel): test_case.assertEqual(format_model1.languages, format_model2.languages) for lang in format_model1.languages: # clean None values in format_model1 to match asdf cleaning:` test_case.assertEqual(format_model1[lang]._origin_config.keys(), format_model2[lang]._origin_config.keys()) c = { k: v for k, v in format_model1[lang].origin_config["trainable_rules"].items() if v is not None } test_case.assertEqual( c, format_model2[lang].origin_config["trainable_rules"]) for rule1, rule2 in zip(format_model1[lang].rules, format_model2[lang].rules): test_case.assertEqual(rule1.stats[0], rule2.stats[0]) test_case.assertAlmostEqual(rule1.stats[1], rule2.stats[1]) for r1, r2 in zip(rule1.attrs, rule2.attrs): test_case.assertEqual(r1[0], r2[0]) test_case.assertEqual(r1[1], r2[1]) test_case.assertAlmostEqual(r1[2], r2[2], places=6)
def assertAlmostEqualFixedPrecision(self, found, expected, digits=0): BaseTestCase.assertAlmostEqual(self, found, expected, digits)
def test_complex(self): TestCase.assertAlmostEqual(self, Calculator.evaluate("2.2 + 2 + 1"), 5.2) TestCase.assertAlmostEqual(self, Calculator.evaluate("2.2 + 2 * 1"), 4.2) TestCase.assertAlmostEqual(self, Calculator.evaluate("2.2 + 2 * 9"), 20.2) TestCase.assertAlmostEqual(self, Calculator.evaluate("2.2 - 2 * 9"), 2.2 - 2 * 9) TestCase.assertAlmostEqual(self, Calculator.evaluate("(2.2 - 2) * 9"), (2.2 - 2) * 9) TestCase.assertAlmostEqual(self, Calculator.evaluate("2 / 2 + 3 * 4 - 6"), 7) TestCase.assertAlmostEqual(self, Calculator.evaluate("2 / (2 + 3) * 4 - 6"), 2 / (2 + 3) * 4 - 6) TestCase.assertAlmostEqual(self, Calculator.evaluate("2 / (2 + 3) * 4 - 6"), 2 / (2 + 3) * 4 - 6)
def test_evaluate(self): foo = Calculator.evaluate("2 + 2") TestCase.assertAlmostEqual(self, 4, foo) TestCase.assertAlmostEqual(self, Calculator.evaluate("2 - 2"), 0) TestCase.assertAlmostEqual(self, Calculator.evaluate("2 * 2"), 4) TestCase.assertAlmostEqual(self, Calculator.evaluate("2 / 2"), 1) assert Calculator.evaluate("2.1 + 2") == 4.1 TestCase.assertAlmostEqual(self, Calculator.evaluate("1.9 - 2"), -0.1) assert Calculator.evaluate("2.1 * 2") == 4.2 TestCase.assertAlmostEqual(self, Calculator.evaluate("2.2 / 2"), 1.1)
self._min_value = value self.setValue(self.value()) def setMaximum(self, value): if value < self._min_value: raise ValueError("Minimum limit cannot be higher than maximum") self._max_value = value self.setValue(self.value()) def minimum(self): return self._min_value def maximum(self): return self._max_value if __name__ == '__main__': from PyQt5.QtWidgets import * from PyQt5.QtCore import Qt import sys from unittest import TestCase app = QApplication(sys.argv) ex = DoubleSlider(Qt.Horizontal) ex.setMinimum(0) ex.setMaximum(100) TestCase.assertAlmostEqual(ex.minimum(), 0.0, delta=0.001) TestCase.assertAlmostEqual(ex.maximum(), 1.0, delta=0.001) ex.show() sys.exit(app.exec_())
def assertAlmostEqual(self, A, B, delta=None, **kws): if delta is None: return _TestCase.assertAlmostEqual(self, A, B, **kws) if abs(B-A)>delta: self.fail('%s!=%s (diff=%g)'%(A,B,abs(B-A)))
def assertAlmostEqualFixedPrecision(self, found, expected, digits = 0): BaseTestCase.assertAlmostEqual(self, found, expected, digits)
def steering_angle_distribution(samples): steering_angles = list(map(lambda pair: pair[1], samples)) test = TestCase() test.assertAlmostEqual(sum(steering_angles), 0.0) show_steering_angle_distribution(steering_angles)