Pairs trading research and execution on backtrader - any tips?
Hi, I am new to backtrader. Wonder if there is any existing frameworks on pair trading which I can learn and build from, in python / backtrader space.
Paska Houso last edited by
There is a Pair Trading contributed sample for
backtraderin the sources under
But I recall that the
OLStechnique it uses may be broken due to changes in the OLS API. This thread tackled it a few days ago:
add_constantwas missing after some API got updated.
Can you please elaborate on the above please. Or anyone else with the knowledge.
Diving into the problem, it stems from the class below. Pardon the code rendering, what should I do to render the code display properly?
Is there any copy and paste solution I can use to get it working? Think the issue lies in 'sm.add_constant(p1, prepend=prepend_constant)'
I have referred to https://stackoverflow.com/questions/2820453/display-html-code-in-html and https://community.backtrader.com/topic/734/ols_slope_interceptn/7 but to no avail.
Calculates a linear regression using
squares) of data1 on data0
prepend_constantto influence the paramter
_mindatas = 2 # ensure at least 2 data feeds are passed
packages = ( ('pandas', 'pd'), ('statsmodels.api', 'sm'), ) lines = ('slope', 'intercept',) params = ( ('period', 10), ('prepend_constant', True), ) def next(self): p0 = pd.Series(self.data0.get(size=self.p.period)) p1 = pd.Series(self.data1.get(size=self.p.period)) p1 = sm.add_constant(p1, prepend=prepend_constant) slope, intercept = sm.OLS(p0, p1).fit().params self.lines.slope = slope self.lines.intercept = intercept
tommark last edited by tommark
Took me 2 full days to realize that I only needed to restart my kernel to reset the namespace after making the edits
jxm262 last edited by
hi @tommark , I'm getting the same error as you mentioned
preprend_constant is not defined.
Can you please let me know what you meant by restarting the kernel in your case? I was assuming you meant restart the actual python interpreter (or your machine)? I'm not actually running on a Jupyter notebook or anything, so was a bit confused on your comment.
Anyway, after looking at @jirathh 's last comment here - https://community.backtrader.com/topic/734/ols_slope_interceptn/12, I took a wild guess and changed that line offending line to this -
p1 = sm.add_constant(p1, prepend=True)
Seems to work, but I haven't dug into any details on the actual root cause yet.
the 'self.params' should be intact
jxm262 last edited by
ah perfect, that works.