Example #1
0
    def sample_from_filtered(filter_state, size=1):
        """
        Samples process parameters values given smoothed observations.
        Static method, can be used as stand-along function.

        Args:
            filter_state:  instance of CovarianceState of dimensionality 3
            size:          int or None, number of samples to draw

        Returns:
            sampled process parameters of size [size] each, packed as OUEstimatorState tuple

        """
        assert isinstance(filter_state, CovarianceState),\
            'Expected filter_state as instance of CovarianceState, got: {}'.format(type(filter_state))

        sample = np.random.multivariate_normal(filter_state.mean,
                                               filter_state.covariance,
                                               size=size)

        return OUEstimatorState(
            mu=sample[:, 0],
            log_theta=sample[:, 1],
            log_sigma=sample[:, 2],
        )
Example #2
0
    def sample_naive_unbiased(state, size=1):
        """
        Samples process parameters values given observed values and smoothed covariance.
        Static method, can be used as stand-along function.

        Args:
            state:  instance of OUProcessState
            size:   int or None, number of samples to draw

        Returns:
            sampled process parameters of size [size] each, packed as OUEstimatorState tuple

        """
        assert isinstance(state, OUProcessState), \
            'Expected filter_state as instance of `OUProcessState`, got: {}'.format(type(state))

        # naive_mean = (np.asarray(state.observation) + state.filtered.mean) / 2
        naive_mean = np.asarray(state.observation)
        sample = np.random.multivariate_normal(naive_mean,
                                               state.filtered.covariance,
                                               size=size)

        return OUEstimatorState(
            mu=sample[:, 0],
            log_theta=sample[:, 1],
            log_sigma=sample[:, 2],
        )
Example #3
0
    def generate_bivariate_trajectory_fn(batch_size,
                                         size,
                                         state,
                                         reconstruct=False,
                                         u_recon=None):
        """
        Generates batch of time-series realisations given model state.
        Static method, can be used as stand-along function.

        Args:
            batch_size:     uint, number of trajectories to generates
            size:           uint, trajectory length to generate
            state:          instance of BivariateTSModelState;
            reconstruct:    bool, if True - return time-series along with P, S trajectories, return None otherwise
            u_recon:        reconstruction matrix of size [2, 2] or None; required if reconstruct=True;

        Returns:
            generated P and S processes realisations of size [batch_size, 2, size];
            generated time-series reconstructions of size [batch_size, 2, size] or None;
        """
        assert isinstance(state, BivariateTSModelState), \
            'Expected `state` as instance of BivariateTSModelState, got: {}'.format(type(state))

        if reconstruct:
            assert u_recon is not None, 'reconstruct=True but reconstruction matrix is not provided.'

        # Unpack:
        p_state = state.p.process
        s_state = state.s.process

        # Get all samples for single batch (faster):
        p_params = OUProcess.sample_naive_unbiased(p_state, 1)
        s_params = OUProcess.sample_naive_unbiased(s_state, 1)

        # Concatenate batch-wise:
        parameters = OUEstimatorState(
            mu=np.concatenate([p_params.mu, s_params.mu]),
            log_theta=np.concatenate([p_params.log_theta, s_params.log_theta]),
            log_sigma=np.concatenate([p_params.log_sigma, s_params.log_sigma]),
        )
        driver_df = np.asarray([p_state.driver_df, s_state.driver_df])

        # Access multivariate generator_fn directly to get batch of 2d correlated OU's:
        batch_2d = OUProcess.generate_multivariate_trajectory_fn(
            batch_size=batch_size,
            size=size,
            parameters=parameters,
            t_df=driver_df,
            covariance=state.ps_stat.covariance)
        batch_2d = np.swapaxes(batch_2d, 1, 2)

        if reconstruct:
            x = np.matmul(u_recon, batch_2d) * state.stat.variance[None, :, None] ** .5 \
                + state.stat.mean[None, :, None]

        else:
            x = None

        return batch_2d, x
    def get_random_state(mu=(0, 0),
                         theta=(.1, 1),
                         sigma=(0.1, 1),
                         driver_df=(3, 50),
                         variance=1e-2):
        """
        Samples random uniform process state w.r.t. parameters intervals given.

        Args:
            mu:         iterable of floats as [lower_bound, upper_bound], OU Mu sampling interval
            theta:      iterable of positive floats as [lower_bound, upper_bound], OU Theta sampling interval
            sigma:      iterable of positive floats as [lower_bound, upper_bound], OU Sigma sampling interval
            driver_df:  iterable of positive floats as [lower_bound > 2, upper_bound],
                        student-t driver degrees of freedom sampling interval
            variance:   filtered observation variance (same and fixed for all params., covariance assumed diagonal)

        Returns:
            instance of OUProcessState
        """
        # TODO: random log-uniform sampling for mu, theta, sigma i.f.f. log_prices are used as in BivariatePriceModel
        sample = dict()
        for name, param, low_threshold in zip(
            ['mu', 'theta', 'sigma', 'driver_df'],
            [mu, theta, sigma, driver_df],
            [-np.inf, 1e-8, 1e-8, 2.999],
        ):
            interval = np.asarray(param)
            assert interval.ndim == 1 and interval[0] <= interval[-1], \
                ' Expected param `{}` as iterable of ordered values as: [lower_bound, upper_bound], got: {}'.format(
                    name, interval
                )
            assert interval[0] > low_threshold, \
                'Expected param `{}` lower bound be bigger than {}, got: {}'.format(name, low_threshold, interval[0])
            sample[name] = np.random.uniform(low=interval[0],
                                             high=interval[-1])

        observation = OUEstimatorState(mu=sample['mu'],
                                       log_theta=np.log(sample['theta']),
                                       log_sigma=np.log(sample['sigma']))
        filtered = CovarianceState(
            mean=np.asarray(observation),
            variance=np.ones(3) * variance,
            covariance=np.eye(3) * variance,
        )
        return OUProcessState(
            observation=observation,
            filtered=filtered,
            driver_df=sample['driver_df'],
        )