Show Sidebar Hide Sidebar

# Convolution in Python

Learn how to perform convolution between two signals in Python.

#### New to Plotly?¶

You can set up Plotly to work in online or offline mode, or in jupyter notebooks.
We also have a quick-reference cheatsheet (new!) to help you get started!

#### Imports¶

The tutorial below imports NumPy, Pandas, SciPy and Plotly.

In [1]:
import plotly.plotly as py
import plotly.graph_objs as go
from plotly.tools import FigureFactory as FF

import numpy as np
import pandas as pd
import scipy

from scipy import signal


#### Import Data¶

Let us import some stock data to apply convolution on.

In [2]:
stock_data = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/stockdata.csv')
df = stock_data[0:15]

table = FF.create_table(df)
py.iplot(table, filename='stockdata-peak-fitting')

Out[2]:

#### Convolve Two Signals¶

Convolution is a type of transform that takes two functions f and g and produces another function via an integration. In particular, the convolution $(f*g)(t)$ is defined as:

\begin{align*} \int_{-\infty}^{\infty} {f(\tau)g(t - \tau)d\tau} \end{align*}

We can use convolution in the discrete case between two n-dimensional arrays.

In [5]:
x = range(15)
y_saw = signal.sawtooth(t=x)

data_sample = list(stock_data['SBUX'][0:100])
data_sample2 = list(stock_data['AAPL'][0:100])
convolve_y = signal.convolve(y_saw, data_sample2)

trace1 = go.Scatter(
x = range(len(data_sample)),
y = data_sample,
mode = 'lines',
name = 'SBUX'
)

trace2 = go.Scatter(
x = range(len(data_sample)),
y = data_sample2,
mode = 'lines',
name = 'AAPL'
)

trace3 = go.Scatter(
x = range(len(convolve_y)),
y = convolve_y,
mode = 'lines',
name = 'Convolution'
)

data = [trace1, trace2, trace3]
py.iplot(data, filename='convolution-of-two-signals')

Out[5]:
Still need help?