本文整理汇总了Python中pykalman.KalmanFilter方法的典型用法代码示例。如果您正苦于以下问题:Python pykalman.KalmanFilter方法的具体用法?Python pykalman.KalmanFilter怎么用?Python pykalman.KalmanFilter使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pykalman
的用法示例。
在下文中一共展示了pykalman.KalmanFilter方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_Filters
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def test_Filters(self):
for model in [self.model, self.mvnmodel]:
x, y = model.sample_path(500)
for filter_, props in [
(SISR, {'particles': 500}),
(APF, {'particles': 500}),
(UKF, {}),
(SISR, {'particles': 500, 'proposal': Linearized(alpha=None)}),
(APF, {'particles': 500, 'proposal': Linearized()}),
(SISR, {'particles': 50, 'proposal': Unscented()})
]:
filt = filter_(model, **props).initialize().longfilter(y)
filtmeans = filt.result.filter_means.numpy()
# ===== Run Kalman ===== #
if model is self.model:
kf = pykalman.KalmanFilter(transition_matrices=1., observation_matrices=1.)
else:
kf = pykalman.KalmanFilter(transition_matrices=[[0.5, 1 / 3], [0, 1.]], observation_matrices=[1, 2])
filterestimates = kf.filter(y.numpy())
if filtmeans.ndim < 2:
filtmeans = filtmeans[:, None]
rel_error = np.median(np.abs((filtmeans - filterestimates[0]) / filterestimates[0]))
ll = kf.loglikelihood(y.numpy())
rel_ll_error = np.abs((ll - filt.result.loglikelihood.sum().numpy()) / ll)
assert rel_error < 0.05 and rel_ll_error < 0.05
示例2: test_kalman_filter
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def test_kalman_filter(self):
kf = KalmanFilter(transition_matrices = [[1, 1], [0, 1]], observation_matrices = [[0.1, 0.5], [-0.3, 0.0]])
measurements = np.asarray([[1,0], [0,0], [0,1]]) # 3 observations
kf = kf.em(measurements, n_iter=5)
(filtered_state_means, filtered_state_covariances) = kf.filter(measurements)
(smoothed_state_means, smoothed_state_covariances) = kf.smooth(measurements)
return filtered_state_means
示例3: test_kalman_missing
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def test_kalman_missing(self):
kf = KalmanFilter(transition_matrices = [[1, 1], [0, 1]], observation_matrices = [[0.1, 0.5], [-0.3, 0.0]])
measurements = np.asarray([[1,0], [0,0], [0,1]]) # 3 observations
measurements = np.ma.asarray(measurements)
measurements[1] = np.ma.masked
kf = kf.em(measurements, n_iter=5)
(filtered_state_means, filtered_state_covariances) = kf.filter(measurements)
(smoothed_state_means, smoothed_state_covariances) = kf.smooth(measurements)
return filtered_state_means
示例4: test_online_update
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def test_online_update(self):
kf = KalmanFilter(transition_matrices = [[1, 1], [0, 1]], observation_matrices = [[0.1, 0.5], [-0.3, 0.0]])
measurements = np.asarray([[1,0], [0,0], [0,1]]) # 3 observations
measurements = np.ma.asarray(measurements)
measurements[1] = np.ma.masked # measurement at timestep 1 is unobserved
kf = kf.em(measurements, n_iter=5)
(filtered_state_means, filtered_state_covariances) = kf.filter(measurements)
for t in range(1, 3):
filtered_state_means[t], filtered_state_covariances[t] = \
kf.filter_update(filtered_state_means[t-1], filtered_state_covariances[t-1], measurements[t])
return filtered_state_means
示例5: getSmoothTrack
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def getSmoothTrack(self, radarPeriod):
from pykalman import KalmanFilter
roughTrackArray = self.backtrackMeasurement()
initialNode = self.getInitial()
depth = initialNode.depth()
initialState = initialNode.x_0
for i, m in enumerate(roughTrackArray):
if m is None:
roughTrackArray[i] = [np.NaN, np.NaN]
measurements = np.ma.asarray(roughTrackArray)
for i, m in enumerate(measurements):
if np.isnan(np.sum(m)):
measurements[i] = np.ma.masked
assert measurements.shape[1] == 2, str(measurements.shape)
if depth < 2:
pos = measurements.filled(np.nan)
vel = np.empty_like(pos) * np.nan
return pos, vel, False
kf = KalmanFilter(transition_matrices=model.Phi(radarPeriod),
observation_matrices=model.C_RADAR,
initial_state_mean=initialState)
kf = kf.em(measurements, n_iter=5)
(smoothed_state_means, _) = kf.smooth(measurements)
smoothedPositions = smoothed_state_means[:, 0:2]
smoothedVelocities = smoothed_state_means[:, 2:4]
assert smoothedPositions.shape == measurements.shape, \
str(smoothedPositions.shape) + str(measurements.shape)
assert smoothedVelocities.shape == measurements.shape, \
str(smoothedVelocities.shape) + str(measurements.shape)
return smoothedPositions, smoothedVelocities, True
示例6: LogLikelihoodWrapper
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def LogLikelihoodWrapper(parameters, y_data, x_data, stage, lambda_g, lambda_z, xi_00, P_00):
if stage == 1:
stage, A, H, R, Q, F, x_data, y_data = Rstar.UnpackStage1(parameters, y_data, x_data)
elif stage == 2:
stage, A, H, R, Q, F = Rstar.UnpackStage2(parameters, lambda_g)
elif stage == 3:
stage, A, H, R, Q, F = Rstar.UnpackStage3(parameters, lambda_g, lambda_z)
else:
pass # PROGRAM SHOULD STOP HERE
exogenous_variables = (A.dot(x_data.T)).transpose()
loglike = pykalman.KalmanFilter(transition_matrices=F,
transition_offsets=np.zeros((xi_00.shape[0])),
transition_covariance=Q,
observation_matrices=H,
observation_offsets=exogenous_variables,
observation_covariance=R,
initial_state_mean=xi_00.reshape(xi_00.shape[0]),
initial_state_covariance=P_00).loglikelihood(y_data)
return loglike
示例7: KalmanStatesWrapper
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def KalmanStatesWrapper(parameters, y_data, x_data, stage, lambda_g, lambda_z, xi_00, P_00):
if stage == 1:
stage, A, H, R, Q, F, x_data, y_data = Rstar.UnpackStage1(parameters, y_data, x_data)
elif stage == 2:
stage, A, H, R, Q, F = Rstar.UnpackStage2(parameters, lambda_g)
elif stage == 3:
stage, A, H, R, Q, F = Rstar.UnpackStage3(parameters, lambda_g, lambda_z)
else:
pass # PROGRAM SHOULD STOP HERE
exogenous_variables = (A.dot(x_data.T)).transpose() # NEED TO CHECK THE DIMENSION
kf = pykalman.KalmanFilter(transition_matrices=F,
transition_offsets=np.zeros((xi_00.shape[0])),
transition_covariance=Q,
observation_matrices=H,
observation_offsets=exogenous_variables,
observation_covariance=R,
initial_state_mean=xi_00.reshape(xi_00.shape[0]),
initial_state_covariance=P_00)
# SHOULD I PUT THIS ON A DATAFRAME?
filtered_states, filtered_cov = kf.filter(y_data)
smoothed_states, smoothed_cov = kf.smooth(y_data)
# If we are on the first stage, we should retrend the esimated states
if stage == 1:
T = filtered_states.shape[0]
filtered_states = filtered_states + parameters[4]*np.concatenate((np.arange(1, T+1, 1).reshape((T, 1)),
np.arange(0, T, 1).reshape((T, 1)),
np.arange(-1, T-1, 1).reshape((T, 1))), axis=1)
smoothed_states = smoothed_states + parameters[4] * np.concatenate((np.arange(1, T + 1, 1).reshape((T, 1)),
np.arange(0, T, 1).reshape((T, 1)),
np.arange(-1, T - 1, 1).reshape((T, 1))), axis=1)
return filtered_states, filtered_cov, smoothed_states, smoothed_cov
示例8: __init__
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def __init__(self, strategy, onBarFunc, setting=None):
# OnBar事件回调函数
self.onBarFunc = onBarFunc
# 周期变更事件回调函数
self.onPeriodChgFunc = None
# K 线服务的策略
self.strategy = strategy
self.shortSymbol = EMPTY_STRING # 商品的短代码
self.minDiff = 1 # 商品的最小价格单位
self.round_n = 4 # round() 小数点的截断数量
self.activeDayJump = False # 隔夜跳空
self.is_7x24 = False
# 当前的Tick
self.curTick = None
self.lastTick = None
self.curTradingDay = EMPTY_STRING
# K线保存数据
self.bar = None # K线数据对象
self.lineBar = [] # K线缓存数据队列
self.barFirstTick = False # K线的第一条Tick数据
self.export_filename = None
self.export_fields = []
# 创建内部变量
self.init_properties()
self.init_indicators()
if setting:
self.setParam(setting)
# 修正精度
if self.minDiff < 1:
self.round_n = 7
## 导入卡尔曼过滤器
if self.inputKF:
try:
self.kf = KalmanFilter(transition_matrices=[1],
observation_matrices=[1],
initial_state_mean=0,
initial_state_covariance=1,
observation_covariance=1,
transition_covariance=0.01)
except :
self.writeCtaLog(u'导入卡尔曼过滤器失败,需先安装 pip install pykalman')
self.inputKF = False
示例9: __recountKF
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def __recountKF(self):
"""计算卡尔曼过滤器均线"""
min_len = 20
if not self.inputKF or self.kf is None:
return
if len(self.lineStateMean) == 0 or len(self.lineStateCovar) == 0:
listClose = []
# 3、获取前InputN周期(不包含当前周期)的K线
if self.mode == self.TICK_MODE:
if len(self.lineBar)<2:
return
listClose.append(self.lineBar[-2].close)
else:
listClose.append(self.lineBar[-1].close)
try:
self.kf = KalmanFilter(transition_matrices=[1],
observation_matrices=[1],
initial_state_mean=listClose[-1],
initial_state_covariance=1,
transition_covariance=0.01)
except:
self.writeCtaLog(u'导入卡尔曼过滤器失败,需先安装 pip install pykalman')
self.inputKF = False
state_means, state_covariances = self.kf.filter(np.array(listClose, dtype=float))
m = state_means[-1].item()
c = state_covariances[-1].item()
else:
m = self.lineStateMean[-1]
c = self.lineStateCovar[-1]
if self.mode == self.TICK_MODE:
o = self.lineBar[-2].close
else:
o = self.lineBar[-1].close
state_means, state_covariances = self.kf.filter_update(filtered_state_mean=m,
filtered_state_covariance=c,
observation=np.array(o, dtype=float))
m = state_means[-1].item()
c = state_covariances[-1].item()
if len(self.lineStateMean) > min_len:
del self.lineStateMean[0]
if len(self.lineStateCovar) > min_len:
del self.lineStateCovar[0]
self.lineStateMean.append(m)
self.lineStateCovar.append(c)
示例10: update_enter_exit_levels
# 需要导入模块: import pykalman [as 别名]
# 或者: from pykalman import KalmanFilter [as 别名]
def update_enter_exit_levels(self):
if (self.kf is None):
Y = np.log(pd.Series(self.data0.get(size=self.max_lookback, ago=0)).values)[:, np.newaxis]
X = np.log(pd.Series(self.data1.get(size=self.max_lookback, ago=0)).values)[:, np.newaxis]
# observation matrix
C = np.hstack((np.ones_like(X), X))
C = C.reshape(self.max_lookback, 1, 2)
# state transition matrix
I = np.array([[[1, 0],
[0, 1]]])
T = I.repeat(self.max_lookback - 1, axis = 0)
self.kf = KalmanFilter(em_vars=['transition_covariance',
'observation_covariance',
'initial_state_mean',
'initial_state_covariance'],
transition_matrices=T,
observation_matrices=C,
n_dim_state=2,
n_dim_obs=1)
# run EM algorithm
self.kf.em(X=Y, n_iter=10)
self.spread_std = math.sqrt(self.kf.observation_covariance[0][0])
# filtering
filtered_state_means, filtered_state_covariances = self.kf.filter(X=Y)
self.filtered_state_means, self.filtered_state_covariances = filtered_state_means[-1], filtered_state_covariances[-1]
# update entry and exit levels
self.upper_limit = self.enter_threshold_size * self.spread_std
self.lower_limit = -1 * self.enter_threshold_size * self.spread_std
self.up_medium = self.exit_threshold_size * self.spread_std
self.low_medium = -1 * self.exit_threshold_size * self.spread_std
self.alpha, self.intercept = self.filtered_state_means[1], self.filtered_state_means[0]
self.allow_trade = False
else:
self.alpha, self.intercept = self.filtered_state_means[1], self.filtered_state_means[0]
observation_t = np.array([math.log(self.data0[0])])
observation_matrix_t = np.array([1, math.log(self.data1[0])]).reshape(1, 2)
I = np.array([[[1, 0],
[0, 1]]])
self.filtered_state_means, self.filtered_state_covariances = (
self.kf.filter_update(
self.filtered_state_means,
self.filtered_state_covariances,
observation=observation_t,
transition_matrix=I.reshape(2, 2),
observation_matrix=observation_matrix_t
)
)
self.allow_trade = True