ranaroussi / qtpylib

QTPyLib, Pythonic Algorithmic Trading
http://qtpylib.io
Apache License 2.0
2.15k stars 511 forks source link

Bar calculation in function on_tick_received seems wrong. #68

Closed ryanaaa closed 7 years ago

ryanaaa commented 7 years ago

In the function of on_tick_received in the file blotter.py 1.

_raw_bars = self._raw_bars[symbol].copy()
_raw_bars = _raw_bars.append(tick_data)

_raw_bars get a copy from self._raw_bars[symbol], Then append the new tick_data to this copy. But not any code like self._raw_bars[symbol] = _raw_bars is invoked to keep this change. This cause self._raw_bars[symbol] not changed always. and the ohlc always the value of the last tick.

2. I think Change if len(self._bars[symbol].index) > previous_bar_count to if len(self._bars[symbol].index) > previous_bar_count and previous_bar_count > 0 is more reasonable

To be more concrete. I think do something like this: Change

if len(self._bars[symbol].index) > previous_bar_count:

    bar = self._bars[symbol].to_dict(orient='records')[0]
    bar["symbol"]       = symbol
    bar["symbol_group"] = tick['symbol_group']
    bar["asset_class"]  = tick['asset_class']
    bar["timestamp"]    = self._bars[symbol].index[0].strftime(
        ibDataTypes["DATE_TIME_FORMAT_LONG"])

    bar["kind"] = "BAR"
    self.broadcast(bar, "BAR")
    self.log2db(bar, "BAR")

    self._bars[symbol] = self._bars[symbol][-1:]
    _raw_bars.drop(_raw_bars.index[:], inplace=True)
    self._raw_bars[symbol] = _raw_bars

to

if len(self._bars[symbol].index) > previous_bar_count and previous_bar_count > 0:

    bar = self._bars[symbol].to_dict(orient='records')[0]
    bar["symbol"]       = symbol
    bar["symbol_group"] = tick['symbol_group']
    bar["asset_class"]  = tick['asset_class']
    bar["timestamp"]    = self._bars[symbol].index[0].strftime(
        ibDataTypes["DATE_TIME_FORMAT_LONG"])

    bar["kind"] = "BAR"
    self.broadcast(bar, "BAR")
    self.log2db(bar, "BAR")

    self._bars[symbol] = self._bars[symbol][-1:]
    _raw_bars.drop(_raw_bars.index[:], inplace=True)
self._raw_bars[symbol] = _raw_bars
ranaroussi commented 7 years ago

There's not need... _raw_bars gets resampled to 1M OHLCV data and then it isn't needed anymore