# How to Create Kalman Filter in Python – Part VII

Contributor:
QuantInsti
Visit: QuantInsti

In the final installment of this series, Rekhit Pachanekar demonstrates how to code in Python to create a sample pairs trading script. See Part IPart II , Part III,  Part IVPart V and Part VI of this series for details on the statistical terms and concepts used for creating Kalman Filter.

In pairs trading strategy we buy one stock and sell the other stock choosing the quantity as hedge ratio.

# Use the observed values of the price to get a rolling mean and z_score
mean, cov = kf.filter(ratio.values)
data[‘mean’] = mean.squeeze()
data[‘cov’] = cov.squeeze()
data[‘std’] = np.sqrt(data[‘cov’])
data = data.dropna()

data[‘ma’] = data[‘ratio’].rolling(5).mean()
data[‘z_score’] = (data[‘ma’] – data[‘mean’])/data[‘std’]

# Initialise positions as zero
data[‘position_1’] = np.nan
data[‘position_2’] = np.nan

# Generate buy, sell and square off signals as: z<-1 buy, z>1 sell and -1 for i in range (data.shape[0]):
if data[‘z_score’].iloc[i] < -1:
data[‘position_1’].iloc[i] = 1
data[‘position_2’].iloc[i] = -round(data[‘ratio’].iloc[i],0)
if data[‘z_score’].iloc[i] > 1:
data[‘position_1’].iloc[i] = -1
data[‘position_2’].iloc[i] = round(data[‘ratio’].iloc[i],0)
if (abs(data[‘z_score’].iloc[i]) < 1) & (abs(data['z_score'].iloc[i]) > 0):
data[‘position_1’].iloc[i] = 0
data[‘position_2’].iloc[i] = 0

# Calculate returns
data[‘returns’] = ((data[‘BAJAJ’]-data[‘BAJAJ’].shift(1))/data[‘BAJAJ’].shift(1))*data[‘position_1’].shift(1)+ ((data[‘HERO’]-data[‘HERO’].shift(1))/data
[‘HERO’].shift(1))*data[‘position_2’].shift(1)
data[‘returns’].sum()

The output is: 0.12282433836398741

All data and information provided in this article are for informational purposes only. QuantInsti® makes no representations as to accuracy, completeness, currentness, suitability, or validity of any information in this article and will not be liable for any errors, omissions, or delays in this information or any losses, injuries, or damages arising from its display or use. All information is provided on an as-is basis.

##### Disclosure: Interactive Brokers

Information posted on IBKR Traders’ Insight that is provided by third-parties and not by Interactive Brokers does NOT constitute a recommendation by Interactive Brokers that you should contract for the services of that third party. Third-party participants who contribute to IBKR Traders’ Insight are independent of Interactive Brokers and Interactive Brokers does not make any representations or warranties concerning the services offered, their past or future performance, or the accuracy of the information provided by the third party. Past performance is no guarantee of future results.

This material is from QuantInsti and is being posted with permission from QuantInsti. The views expressed in this material are solely those of the author and/or QuantInsti and IBKR is not endorsing or recommending any investment or trading discussed in the material. This material is not and should not be construed as an offer to sell or the solicitation of an offer to buy any security. To the extent that this material discusses general market activity, industry or sector trends or other broad based economic or political conditions, it should not be construed as research or investment advice. To the extent that it includes references to specific securities, commodities, currencies, or other instruments, those references do not constitute a recommendation to buy, sell or hold such security. This material does not and is not intended to take into account the particular financial conditions, investment objectives or requirements of individual customers. Before acting on this material, you should consider whether it is suitable for your particular circumstances and, as necessary, seek professional advice.

In accordance with EU regulation: The statements in this document shall not be considered as an objective or independent explanation of the matters. Please note that this document (a) has not been prepared in accordance with legal requirements designed to promote the independence of investment research, and (b) is not subject to any prohibition on dealing ahead of the dissemination or publication of investment research.

Any trading symbols displayed are for illustrative purposes only and are not intended to portray recommendations.

##### Disclosure: Displaying Symbols on Video

Any stock, options or futures symbols displayed are for illustrative purposes only and are not intended to portray recommendations.