def test_module_block(self): # Expression with one function def. dsl_source = """ def sqr(n): n ** 2 sqr(3) """ dsl_module = dsl_parse(dsl_source) self.assertIsInstance(dsl_module, Module) self.assertEqual(str(dsl_module), dsl_source.strip()) dsl_expr = dsl_compile(dsl_source) self.assertEqual(dsl_expr.evaluate(), 9) dsl_value = dsl_eval(dsl_source) self.assertEqual(dsl_value, 9) # Expression with two function defs. dsl_source = """ def add(a, b): a + b def mul(a, b): a if b == 1 else add(a, mul(a, b - 1)) mul(3, 3) """ dsl_module = dsl_parse(dsl_source) self.assertIsInstance(dsl_module, Module) self.assertEqual(str(dsl_module), dsl_source.strip()) dsl_expr = dsl_compile(dsl_source) # self.assertEqual(str(dsl_expr), "") self.assertEqual(dsl_expr.evaluate(), 9) dsl_value = dsl_eval(dsl_source) self.assertEqual(dsl_value, 9)
def calc_value(self, dsl_source, observation_date): # Todo: Rename 'allRvs' to 'simulatedPrices'? evaluation_kwds = DslNamespace({ 'observation_date': observation_date, 'interest_rate': '2.5', 'market_calibration': { '#1-LAST-PRICE': 10, '#1-ACTUAL-HISTORICAL-VOLATILITY': 50, '#2-LAST-PRICE': 10, '#2-ACTUAL-HISTORICAL-VOLATILITY': 50, '#1-#2-CORRELATION': 0.0, 'NBP-LAST-PRICE': 10, 'NBP-ACTUAL-HISTORICAL-VOLATILITY': 50, 'TTF-LAST-PRICE': 11, 'TTF-ACTUAL-HISTORICAL-VOLATILITY': 40, 'BRENT-LAST-PRICE': 90, 'BRENT-ACTUAL-HISTORICAL-VOLATILITY': 60, 'NBP-TTF-CORRELATION': 0.4, 'BRENT-TTF-CORRELATION': 0.5, 'BRENT-NBP-CORRELATION': 0.3, }, 'path_count': 200000, # 'simulated_price_repo': { # 'sim1#12011-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1#12011-01-03': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1#12011-06-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1#12012-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1#12012-01-02': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1#12012-01-03': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1#12012-06-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1#12013-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # # 'sim1#22011-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1#22012-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # # 'sim1TTF2012-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1NBP2012-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1TTF2013-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # 'sim1NBP2013-01-01': Mock(spec=SimulatedPrice, value=numpy.array([10])), # }, 'simulation_id': 'sim1', 'first_market_name': '#1', }) return dsl_eval(dsl_source, evaluation_kwds=evaluation_kwds)
market_calibration = {} observation_date = datetime.datetime( int(''.join(str(observation_date)[0:4])), int(''.join(str(observation_date)[4:6])), int(''.join(str(observation_date)[6:8])) ).replace(tzinfo=quantdsl.semantics.utc) try: result = dsl_eval( dsl_source, filename=source_url if source_url != '-' else 'STDIN', is_parallel=True, market_calibration=market_calibration, interest_rate=interest_rate, path_count=num_paths, observation_date=observation_date, is_multiprocessing=bool(multiprocessing_pool), pool_size=multiprocessing_pool, is_verbose=is_verbose, is_show_source=show_source, price_process_name=price_process, ) except DslError, e: print "Failed to dsl_eval DSL source:" print dsl_source print print "Error:", e print else: if is_verbose: sys.stdout.write("Result: ")
def main(source, observation_date=defaultObservationTime, calibration=None, num_paths=DEFAULT_PATH_COUNT, price_process=DEFAULT_PRICE_PROCESS_NAME, interest_rate=2.5, multiprocessing_pool=0, quiet=False, show_source=False): """ Evaluates 'Quant DSL' code in SOURCE, given price process parameters in CALIBRATION. """ import quantdsl import quantdsl.semantics if multiprocessing_pool is None: multiprocessing_pool = mp.cpu_count() source_url = source calibration_url = calibration is_verbose = not quiet def get_resource(url): if url == '-': return sys.stdin.read() elif url.startswith('file://'): return open(url[7:]).read() elif url.startswith('http://'): import requests return requests.get(url) elif os.path.exists(url) and os.path.isfile(url): return open(url).read() else: raise DslError("Can't open resource: %s" % url) # Todo: Make this work with Python 3. print("DSL source from: %s" % source_url) print() dsl_source = get_resource(source_url) if calibration_url: print("Calibration from: %s" % calibration_url) print() market_calibration_json = get_resource(calibration_url) try: market_calibration = json.loads(market_calibration_json) except Exception: msg = "Unable to load JSON from %s: %s" % (calibration_url, market_calibration_json) raise ValueError(msg) else: market_calibration = {} observation_date = datetime.datetime( int(''.join(str(observation_date)[0:4])), int(''.join(str(observation_date)[4:6])), int(''.join(str(observation_date)[6:8]))).replace(tzinfo=UTC) try: result = dsl_eval( dsl_source, filename=source_url if source_url != '-' else 'STDIN', is_parallel=True, market_calibration=market_calibration, interest_rate=interest_rate, path_count=num_paths, observation_date=observation_date, is_multiprocessing=bool(multiprocessing_pool), pool_size=multiprocessing_pool, is_verbose=is_verbose, is_show_source=show_source, price_process_name=price_process, ) except DslError as e: print("Failed to dsl_eval DSL source:") print(dsl_source) print() print("Error:", e) print() else: if is_verbose: sys.stdout.write("Result: ") sys.stdout.flush() print(json.dumps(result, indent=4, sort_keys=True))