def handle_intraday_close(self): self.intraday_risk_metrics = \ risk.RiskMetricsIterative(self.sim_params) # increment the day counter before we move markers forward. self.day_count += 1.0 # move the market day markers forward if self.market_close < trading.environment.last_trading_day: _, self.market_close = \ trading.environment.next_open_and_close(self.market_open) else: self.market_close = self.sim_params.last_close
def __init__(self, sim_params): self.sim_params = sim_params self.period_start = self.sim_params.period_start self.period_end = self.sim_params.period_end self.last_close = self.sim_params.last_close first_day = self.sim_params.first_open self.market_open, self.market_close = \ trading.environment.get_open_and_close(first_day) self.total_days = self.sim_params.days_in_period self.capital_base = self.sim_params.capital_base self.cumulative_risk_metrics = \ risk.RiskMetricsIterative(self.period_start, self.period_end) self.emission_rate = sim_params.emission_rate # Temporarily hold these here as we work on streaming benchmarks. self.all_benchmark_returns = pd.Series( index=trading.environment.trading_days) # this performance period will span the entire simulation. self.cumulative_performance = PerformancePeriod( # initial cash is your capital base. self.capital_base, # the cumulative period will be calculated over the entire test. self.period_start, self.period_end, # don't save the transactions for the cumulative # period keep_transactions=False, keep_orders=False, # don't serialize positions for cumualtive period serialize_positions=False) # this performance period will span just the current market day self.todays_performance = PerformancePeriod( # initial cash is your capital base. self.capital_base, # the daily period will be calculated for the market day self.market_open, self.market_close, keep_transactions=True, keep_orders=True, serialize_positions=True) self.saved_dt = self.period_start self.returns = [] # one indexed so that we reach 100% self.day_count = 0.0 self.txn_count = 0 self.event_count = 0 self.progress = 0.0
def test_minute_risk(self): risk_metrics = risk.RiskMetricsIterative(self.sim_params) first_dt = self.sim_params.first_open second_dt = self.sim_params.first_open + datetime.timedelta(minutes=1) risk_metrics.update(first_dt, 1.0, 2.0) self.assertEquals(1, len(risk_metrics.alpha)) risk_metrics.update(second_dt, 3.0, 4.0) self.assertEquals(2, len(risk_metrics.alpha))
def __init__(self, trading_environment): self.trading_environment = trading_environment self.trading_day = datetime.timedelta(hours=6, minutes=30) self.calendar_day = datetime.timedelta(hours=24) self.started_at = datetime.datetime.utcnow().replace(tzinfo=pytz.utc) self.period_start = self.trading_environment.period_start self.period_end = self.trading_environment.period_end self.market_open = self.trading_environment.first_open self.market_close = self.market_open + self.trading_day self.progress = 0.0 self.total_days = self.trading_environment.days_in_period # one indexed so that we reach 100% self.day_count = 0.0 self.capital_base = self.trading_environment.capital_base self.returns = [] self.txn_count = 0 self.event_count = 0 self.last_dict = None self.cumulative_risk_metrics = risk.RiskMetricsIterative( self.period_start, self.trading_environment) # this performance period will span the entire simulation. self.cumulative_performance = PerformancePeriod( # initial positions are empty positiondict(), # initial portfolio positions have zero value 0, # initial cash is your capital base. self.capital_base, # the cumulative period will be calculated over the entire test. self.period_start, self.period_end) # this performance period will span just the current market day self.todays_performance = PerformancePeriod( # initial positions are empty positiondict(), # initial portfolio positions have zero value 0, # initial cash is your capital base. self.capital_base, # the daily period will be calculated for the market day self.market_open, self.market_close, # save the transactions for the daily periods keep_transactions=True)
def test_risk_metrics_returns(self): trading.environment = trading.TradingEnvironment() # Advance start date to first date in the trading calendar if trading.environment.is_trading_day(self.start_date): start_date = self.start_date else: start_date = trading.environment.next_trading_day(self.start_date) self.all_benchmark_returns = pd.Series({ x.date: x.returns for x in trading.environment.benchmark_returns if x.date >= self.start_date }) start_index = trading.environment.trading_days.searchsorted(start_date) end_date = trading.environment.trading_days[start_index + len(RETURNS)] sim_params = SimulationParameters(start_date, end_date) risk_metrics_refactor = risk.RiskMetricsIterative(sim_params) todays_date = start_date cur_returns = [] for i, ret in enumerate(RETURNS): todays_return_obj = DailyReturn(todays_date, ret) cur_returns.append(todays_return_obj) try: risk_metrics_original = risk.RiskMetricsBatch( start_date=start_date, end_date=todays_date, returns=cur_returns) except Exception as e: #assert that when original raises exception, same #exception is raised by risk_metrics_refactor np.testing.assert_raises( type(e), risk_metrics_refactor.update, todays_date, self.all_benchmark_returns[todays_return_obj.date]) continue risk_metrics_refactor.update( todays_date, ret, self.all_benchmark_returns[todays_return_obj.date]) # Move forward day counter to next trading day todays_date = trading.environment.next_trading_day(todays_date) self.assertEqual(risk_metrics_original.start_date, risk_metrics_refactor.start_date) self.assertEqual(risk_metrics_original.end_date, risk_metrics_refactor.algorithm_returns.index[-1]) self.assertEqual(risk_metrics_original.treasury_period_return, risk_metrics_refactor.treasury_period_return) np.testing.assert_allclose(risk_metrics_original.benchmark_returns, risk_metrics_refactor.benchmark_returns, rtol=0.001) np.testing.assert_allclose(risk_metrics_original.algorithm_returns, risk_metrics_refactor.algorithm_returns, rtol=0.001) risk_original_dict = risk_metrics_original.to_dict() risk_refactor_dict = risk_metrics_refactor.to_dict() self.assertEqual(set(risk_original_dict.keys()), set(risk_refactor_dict.keys())) err_msg_format = """\ "In update step {iter}: {measure} should be {truth} but is {returned}!""" for measure in risk_original_dict.iterkeys(): if measure == 'max_drawdown': np.testing.assert_almost_equal( risk_refactor_dict[measure], risk_original_dict[measure], err_msg=err_msg_format.format( iter=i, measure=measure, truth=risk_original_dict[measure], returned=risk_refactor_dict[measure])) else: if isinstance(risk_original_dict[measure], numbers.Real): np.testing.assert_allclose( risk_original_dict[measure], risk_refactor_dict[measure], rtol=0.001, err_msg=err_msg_format.format( iter=i, measure=measure, truth=risk_original_dict[measure], returned=risk_refactor_dict[measure])) else: np.testing.assert_equal( risk_original_dict[measure], risk_refactor_dict[measure], err_msg=err_msg_format.format( iter=i, measure=measure, truth=risk_original_dict[measure], returned=risk_refactor_dict[measure]))
def __init__(self, sim_params): self.sim_params = sim_params self.period_start = self.sim_params.period_start self.period_end = self.sim_params.period_end self.last_close = self.sim_params.last_close first_day = self.sim_params.first_open self.market_open, self.market_close = \ trading.environment.get_open_and_close(first_day) self.total_days = self.sim_params.days_in_period self.capital_base = self.sim_params.capital_base self.emission_rate = sim_params.emission_rate self.emission_rate = sim_params.emission_rate self.perf_periods = [] if self.emission_rate == 'daily': self.all_benchmark_returns = pd.Series( index=trading.environment.trading_days) self.intraday_risk_metrics = None self.cumulative_risk_metrics = \ risk.RiskMetricsIterative(self.sim_params) elif self.emission_rate == 'minute': self.all_benchmark_returns = pd.Series( index=pd.date_range(self.sim_params.first_open, self.sim_params.last_close, freq='Min')) self.intraday_risk_metrics = \ risk.RiskMetricsIterative(self.sim_params) self.cumulative_risk_metrics = \ risk.RiskMetricsIterative(self.sim_params) self.cumulative_risk_metrics.initialize_daily_indices() self.minute_performance = PerformancePeriod( # initial cash is your capital base. self.capital_base, # the cumulative period will be calculated over the # entire test. self.period_start, self.period_end, # don't save the transactions for the cumulative # period keep_transactions=False, keep_orders=False, # don't serialize positions for cumualtive period serialize_positions=False) self.perf_periods.append(self.minute_performance) # this performance period will span the entire simulation from # inception. self.cumulative_performance = PerformancePeriod( # initial cash is your capital base. self.capital_base, # the cumulative period will be calculated over the entire test. self.period_start, self.period_end, # don't save the transactions for the cumulative # period keep_transactions=False, keep_orders=False, # don't serialize positions for cumualtive period serialize_positions=False) self.perf_periods.append(self.cumulative_performance) # this performance period will span just the current market day self.todays_performance = PerformancePeriod( # initial cash is your capital base. self.capital_base, # the daily period will be calculated for the market day self.market_open, self.market_close, keep_transactions=True, keep_orders=True, serialize_positions=True) self.perf_periods.append(self.todays_performance) self.saved_dt = self.period_start self.returns = [] # one indexed so that we reach 100% self.day_count = 0.0 self.txn_count = 0 self.event_count = 0
def test_risk_metrics_returns(self): risk_metrics_refactor = risk.RiskMetricsIterative( self.start_date, self.trading_env) todays_date = self.start_date cur_returns = [] for i, ret in enumerate(RETURNS): todays_return_obj = risk.DailyReturn( todays_date, ret ) cur_returns.append(todays_return_obj) # Move forward day counter to next trading day todays_date += self.oneday while not self.trading_env.is_trading_day(todays_date): todays_date += self.oneday try: risk_metrics_original = risk.RiskMetricsBatch( start_date=self.start_date, end_date=todays_date, returns=cur_returns, trading_environment=self.trading_env ) except Exception as e: #assert that when original raises exception, same #exception is raised by risk_metrics_refactor np.testing.assert_raises( type(e), risk_metrics_refactor.update, ret) continue risk_metrics_refactor.update(ret) self.assertEqual( risk_metrics_original.start_date, risk_metrics_refactor.start_date) self.assertEqual( risk_metrics_original.end_date, risk_metrics_refactor.end_date) self.assertEqual( risk_metrics_original.treasury_duration, risk_metrics_refactor.treasury_duration) self.assertEqual( risk_metrics_original.treasury_curve, risk_metrics_refactor.treasury_curve) self.assertEqual( risk_metrics_original.treasury_period_return, risk_metrics_refactor.treasury_period_return) self.assertEqual( risk_metrics_original.benchmark_returns, risk_metrics_refactor.benchmark_returns) self.assertEqual( risk_metrics_original.algorithm_returns, risk_metrics_refactor.algorithm_returns) risk_original_dict = risk_metrics_original.to_dict() risk_refactor_dict = risk_metrics_refactor.to_dict() self.assertEqual(set(risk_original_dict.keys()), set(risk_refactor_dict.keys())) err_msg_format = """\ "In update step {iter}: {measure} should be {truth} but is {returned}!""" for measure in risk_original_dict.iterkeys(): if measure == 'max_drawdown': np.testing.assert_almost_equal( risk_refactor_dict[measure], risk_original_dict[measure], err_msg=err_msg_format.format( iter=i, measure=measure, truth=risk_original_dict[measure], returned=risk_refactor_dict[measure])) else: np.testing.assert_equal( risk_original_dict[measure], risk_refactor_dict[measure], err_msg_format.format( iter=i, measure=measure, truth=risk_original_dict[measure], returned=risk_refactor_dict[measure]) )