Hi,
Do you have on your mind to add any machine learning library in backtrader or any ml sample?
Rgds,
Jj
Hi,
Do you have on your mind to add any machine learning library in backtrader or any ml sample?
Rgds,
Jj
ok, thanks, i will wait up Standard Deviation. Congrats on the community!!!!
This code could be adapted to use two timeseries backtrader:
https://github.com/vikasrtr/pyLinearRegression/blob/master/models/LinearRegression.py
https://github.com/vikasrtr/pyLinearRegression/blob/master/models/LinearRegressionGradientDescent.py
def linreg(X, Y):
"""
Linear regression y = ax + b
"""
if len(X) != len(Y): raise ValueError, 'unequal length'
N = len(X)
Sx = Sy = Sxx = Syy = Sxy = 0.0
for x, y in map(None, X, Y):
Sx = Sx + x
Sy = Sy + y
Sxx = Sxx + x*x
Syy = Syy + y*y
Sxy = Sxy + x*y
det = Sxx * N - Sx * Sx
a, b = (Sxy * N - Sy * Sx)/det, (Sxx * Sy - Sx * Sxy)/det
meanerror = residual = 0.0
for x, y in map(None, X, Y):
meanerror = meanerror + (y - Sy/N)**2
residual = residual + (y - a * x - b)**2
RR = 1 - residual/meanerror
ss = residual / (N-2)
Var_a, Var_b = ss * N / det, ss * Sxx / det
return a, b, RR
My idea is to use linear regression to test these posts:
https://www.quantopian.com/posts/how-to-build-a-pairs-trading-strategy-on-quantopian
https://www.quantinsti.com/blog/pair-trading-strategy-backtesting-using-quantstrat/
if X and Y are cointegrated:
calculate Beta between X and Y
calculate spread as X - Beta * Y
calculate z-score of spread
# entering trade (spread is away from mean by two sigmas):
if z-score > 2:
sell spread (sell 1000 of X, buy 1000 * Beta of Y)
if z-score < -2:
buy spread (buy 1000 of X, sell 1000 * Beta of Y)
# exiting trade (spread converged close to mean):
if we're short spread and z-score < 1:
close the trades
if we're long spread and z-score > -1:
close the trades
loop: repeat above on each new bar, recalculating rolling Beta and spread etc.
Thanks, i was using the above code, i have changed and now it is working well.
self.ols=OLS_Transformation(self.data0,self.data1)
self.spread_mean = bt.indicators.MovingAverageSimple(self.ols.spread, period=self.p.period)
self.spread_std = bt.indicators.StandardDeviation(self.ols.spread, period=self.p.period)
I think a new feature is mandatory, check cointegration between both pairs.
import pandas as pd
import backtrader as bt
class is Cointegrated(bt.indicators.PeriodN):
_mindatas = 2 # ensure at least 2 data feeds are passed
lines = (('cointegration'),)
def next(self):
y, x = (d for d in (self.data0, self.data1))
results = coint(x,y)
self.lines.cointegration[0] = results[1]
# you should define a p-value limit and compare with the line value before operating
I have tested and it is working well. could you add in the next release? Also, if you consider important, half-life quantopian post help people to calibrate the period in the pair trading strategy.
https://www.quantopian.com/posts/pair-trade-with-cointegration-and-mean-reversion-tests
Is there any future development that consists of adding kraken as broker in backtrader?
ok, thanks, i will wait impatiently this feature:
class St(bt.Strategy):
def buildTimers(self):
#Start trading
timers={}
timerStart=self.add_timer(
when=self.p.start,
offset=self.p.offset,
repeat=self.p.repeat,
weekdays=self.p.weekdays,
)
timers['timerStart']=timerStart.p.tid
#Timer Bin Size
timerBinSize=self.add_timer(
when=self.p.start,
offset=self.p.offset,
repeat=datetime.timedelta(seconds=self.bin_size),
weekdays=self.p.weekdays,
)
timers['timerBinSize']=timerBinSize.p.tid
#Start trading
timerEnd=self.add_timer(
when=self.p.end,
offset=self.p.offset,
repeat=self.p.repeat,
weekdays=self.p.weekdays,
)
timers['timerEnd']=timerEnd.p.tid
return timers
def __init__(self):
self.bin_size=self.p.bin_size
self.limit_orders = []
self.order_book=None
self.timers=self.buildTimers()
def build_timer2(self):
timerDimingFrequency=self.add_timer(
when=self.p.start,
offset=self.p.offset,
repeat=datetime.timedelta(seconds=self.bin_size),
weekdays=self.p.weekdays,
)
self.timers['timerDimingFrequency']=timerDimingFrequency.p.tid
def notify_timer(self, timer, when, *args, **kwargs):
for key, value in self.timers.copy().items():
print(key,value)
if value==timer.p.tid:
if key=='timerStart':
print('strategy starts '+str(when) )
elif key=='timerBinSize':
print('bin starts ' +str(when) )
self.build_timer2()
elif key=='timerEnd':
Hi,
I would like to add a new timer when a timer begins and eliminate when the first timer finishes. is it possible?
def buildTimers(self):
#Start trading
timers={}
timerStart=self.add_timer(
when=self.p.start,
offset=self.p.offset,
repeat=datetime.timedelta(seconds=360),
weekdays=self.p.weekdays,
)
timers['timerStart']=timerStart.p.tid
def notify_timer(self, timer, when, *args, **kwargs):
for key, value in self.timers.items():
if value==timer.p.tid and key=='timerStart':
timerDimingFrequency=self.add_timer(
when=self.p.start,
offset=self.p.offset,
repeat=datetime.timedelta(seconds=10),
weekdays=self.p.weekdays,
)
I am not receiving the notification of the second timer, do you know what is the problem?
Rgds,
JJ
Another choice is to consider the bid offer spread as a measure of transactions costs:
https://ajayshahblog.blogspot.com.es/2012/05/costs-in-buying-versus-costs-in-selling.html
what is your opinion?
The problem, when you consider the mid price as close price, is that threre is a big difference between bid-mid and ask-mid and your error when the asset is active (EUR/USD), is very big. I have reviewd github repository and these projects could solve my problem:
https://github.com/danielktaylor/PyLimitBook
https://github.com/davecliff/BristolStockExchange
Hello,
I would like to back test a strategy using a real order book, is there any way to build an order book with bid and ask, I have both bid and ask second series and I would like that if I buy with market order, the broker use ask prices and if you sell , the broker use bid prices. Also if you use limit orders the broker should use the correct time series
Is there any way to cover this funcionality with backtrader?
Rgds,
Jj
I think i have got good values, I have changed the init values:
('delta',1e-7 ),
('vt',1e-3),
I think the problem is here:
# Q_t is the variance of the prediction of observations and hence
# \sqrt{Q_t} is the standard deviation of the predictions
Qt = F.dot(self.R).dot(F.T) + self.p.vt
The post said:"variance of the last observations", i think we have to take n qt , calculate variance and then the sqrt . What do you think?