# How to represent this structural time series model efficiently?

**URL:** <https://discourse.pymc.io/t/how-to-represent-this-structural-time-series-model-efficiently/2036>\
**Category:** Questions\
**Created:** [October 8, 2018, 11:15pm UTC](https://discourse.pymc.io/t/how-to-represent-this-structural-time-series-model-efficiently/2036 "2018-10-08T23:15:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![bmoon](https://avatars.discourse-cdn.com/v4/letter/b/4bbf92/32.png) [@bmoon](https://discourse.pymc.io/u/bmoon)\
**Post date:** [October 8, 2018, 11:15pm UTC](https://discourse.pymc.io/t/how-to-represent-this-structural-time-series-model-efficiently/2036/1 "2018-10-08T23:15:43Z")

</div>

I’m new to PyMC3 and trying to write a fairly simple time series model without having to resort to loops. I’m trying to implement the structural time series model from “Machine Learning: A Probabilistic Perspective” by Murphy:

![Capture](https://canada1.discourse-cdn.com/flex036/uploads/pymc3/original/2X/d/d566484bc1b6b7f9592de8d78a218a4793b6413d.png)

where y\_t is the observed value, a\_t is “local level”, and b\_t is “local linear trend.”

To my understanding, loops are inefficient in PyMC3, so i’m trying to avoid them. I know I can write b\_t as a GaussianRandomWalk, but then I’m at a loss for how to proceed from there. I can write

```
a_t - a_{t-1} ~ N(b_{t-1}, Q)

```

so that I can take a cumulative sum and obtain the time series, but the problem is that it doesn’t look like PyMC3 supports the cumulative sum operation according to [its math docs.](https://docs.pymc.io/api/math.html) Is there a way to write this efficiently? Thanks!

---

<div class="post-metadata">

**Author:** ![DanWeitzenfeld](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.pymc.io/danweitzenfeld/32/30_2.png) [@DanWeitzenfeld](https://discourse.pymc.io/u/DanWeitzenfeld)\
**Post date:** [October 9, 2018, 12:58am UTC](https://discourse.pymc.io/t/how-to-represent-this-structural-time-series-model-efficiently/2036/2 "2018-10-09T00:58:07Z")

</div>

You can model this using [`GaussianRandomWalk`](https://docs.pymc.io/api/distributions/timeseries.html#pymc3.distributions.timeseries.GaussianRandomWalk).

e.g. this very partial sketch:

b = GaussianRandomWalk(‘b’, sd=epsilon\_b)  
a = GaussianRandomWalk(‘a’, mu=b, sd=epislon\_a)  
y = pm.Normal(‘y’, mu=a, sd=epsilon\_y)
