本文整理汇总了Python中backtrader.date2num函数的典型用法代码示例。如果您正苦于以下问题:Python date2num函数的具体用法?Python date2num怎么用?Python date2num使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了date2num函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: _getnexteos
def _getnexteos(self):
'''Returns the next eos using a trading calendar if available'''
if self._clone:
return self.data._getnexteos()
if not len(self):
return datetime.datetime.min, 0.0
dt = self.lines.datetime[0]
dtime = num2date(dt)
if self._calendar is None:
nexteos = datetime.datetime.combine(dtime, self.p.sessionend)
nextdteos = self.date2num(nexteos) # locl'ed -> utc-like
nexteos = num2date(nextdteos) # utc
while dtime > nexteos:
nexteos += datetime.timedelta(days=1) # already utc-like
nextdteos = date2num(nexteos) # -> utc-like
else:
# returns times in utc
_, nexteos = self._calendar.schedule(dtime, self._tz)
nextdteos = date2num(nexteos) # nextos is already utc
return nexteos, nextdteos
开发者ID:aaron8tang,项目名称:backtrader,代码行数:25,代码来源:feed.py
示例2: dopostinit
def dopostinit(cls, _obj, *args, **kwargs):
_obj, args, kwargs = \
super(MetaAbstractDataBase, cls).dopostinit(_obj, *args, **kwargs)
_obj._name = _obj.p.name
_obj._compression = _obj.p.compression
_obj._timeframe = _obj.p.timeframe
if _obj.p.sessionstart is None:
_obj.p.sessionstart = datetime.time(0, 0, 0)
if _obj.p.sessionend is None:
_obj.p.sessionend = datetime.time(23, 59, 59)
if isinstance(_obj.p.fromdate, datetime.date):
# push it to the end of the day, or else intraday
# values before the end of the day would be gone
_obj.p.fromdate = datetime.datetime.combine(
_obj.p.fromdate, _obj.p.sessionstart)
if isinstance(_obj.p.todate, datetime.date):
# push it to the end of the day, or else intraday
# values before the end of the day would be gone
_obj.p.todate = datetime.datetime.combine(
_obj.p.todate, _obj.p.sessionend)
_obj.fromdate = date2num(_obj.p.fromdate)
_obj.todate = date2num(_obj.p.todate)
_obj.sessionstart = time2num(_obj.p.sessionstart)
_obj.sessionend = time2num(_obj.p.sessionend)
# hold datamaster points corresponding to own
_obj.mlen = list()
return _obj, args, kwargs
开发者ID:nooperpudd,项目名称:backtrader,代码行数:35,代码来源:feed.py
示例3: dopostinit
def dopostinit(cls, _obj, *args, **kwargs):
_obj, args, kwargs = \
super(MetaAbstractDataBase, cls).dopostinit(_obj, *args, **kwargs)
_obj._name = _obj.p.name
_obj._compression = _obj.p.compression
_obj._timeframe = _obj.p.timeframe
if isinstance(_obj.p.sessionstart, datetime.datetime):
_obj.p.sessionstart = _obj.p.sessionstart.time()
if _obj.p.sessionstart is None:
_obj.p.sessionstart = datetime.time(0, 0, 0)
if isinstance(_obj.p.sessionend, datetime.datetime):
_obj.p.sessionend = _obj.p.sessionend.time()
if _obj.p.sessionend is None:
_obj.p.sessionend = datetime.time(23, 59, 59)
if isinstance(_obj.p.fromdate, datetime.date):
# push it to the end of the day, or else intraday
# values before the end of the day would be gone
_obj.p.fromdate = datetime.datetime.combine(
_obj.p.fromdate, _obj.p.sessionstart)
if isinstance(_obj.p.todate, datetime.date):
# push it to the end of the day, or else intraday
# values before the end of the day would be gone
_obj.p.todate = datetime.datetime.combine(
_obj.p.todate, _obj.p.sessionend)
_obj.fromdate = date2num(_obj.p.fromdate)
_obj.todate = date2num(_obj.p.todate)
_obj.sessionstart = time2num(_obj.p.sessionstart)
_obj.sessionend = time2num(_obj.p.sessionend)
# hold datamaster points corresponding to own
_obj.mlen = list()
_obj._barstack = collections.deque() # for filter operations
_obj._filters = list()
_obj._ffilters = list()
for fp in _obj.p.filters:
if inspect.isclass(fp):
fp = fp(_obj)
if hasattr(fp, 'last'):
_obj._ffilters.append((fp, [], {}))
_obj._filters.append((fp, [], {}))
return _obj, args, kwargs
开发者ID:fulQuan,项目名称:backtrader,代码行数:53,代码来源:feed.py
示例4: _load
def _load(self):
try:
row = next(self._rows)
except StopIteration:
return False
# Set the standard datafields - except for datetime
for datafield in self.datafields[1:]:
# get the column index
colidx = getattr(self.params, datafield)
if colidx < 0:
# column not present -- skip
continue
# get the line to be set
line = getattr(self.lines, datafield)
# indexing for pandas: 1st is colum, then row
line[0] = row[colidx]
# datetime
colidx = getattr(self.params, self.datafields[0])
tstamp = row[colidx]
# convert to float via datetime and store it
dt = tstamp.to_pydatetime()
dtnum = date2num(dt)
# get the line to be set
line = getattr(self.lines, self.datafields[0])
line[0] = dtnum
# Done ... return
return True
开发者ID:remroc,项目名称:backtrader,代码行数:35,代码来源:pandafeed.py
示例5: _load_history
def _load_history(self, msg):
dtobj = datetime.utcfromtimestamp(int(msg['time']) / 10 ** 6)
dt = date2num(dtobj)
if dt <= self.lines.datetime[-1]:
return False # time already seen
# Common fields
self.lines.datetime[0] = dt
self.lines.volume[0] = float(msg['volume'])
self.lines.openinterest[0] = 0.0
# Put the prices into the bar
if self.p.bidask:
if not self.p.useask:
self.lines.open[0] = float(msg['openBid'])
self.lines.high[0] = float(msg['highBid'])
self.lines.low[0] = float(msg['lowBid'])
self.lines.close[0] = float(msg['closeBid'])
else:
self.lines.open[0] = float(msg['openAsk'])
self.lines.high[0] = float(msg['highAsk'])
self.lines.low[0] = float(msg['lowAsk'])
self.lines.close[0] = float(msg['closeAsk'])
else:
self.lines.open[0] = float(msg['openMid'])
self.lines.high[0] = float(msg['highMid'])
self.lines.low[0] = float(msg['lowMid'])
self.lines.close[0] = float(msg['closeMid'])
return True
开发者ID:aaron8tang,项目名称:backtrader,代码行数:30,代码来源:oanda.py
示例6: _load
def _load(self):
try:
row = next(self._rows)
except StopIteration:
return False
# Set the standard datafields - except for datetime
for datafield in self.datafields[1:]:
# get the column index
colidx = getattr(self.params, datafield)
if colidx < 0:
# column not present -- skip
continue
# get the line to be set
line = getattr(self.lines, datafield)
line[0] = row[colidx]
# datetime - assumed blaze always serves a native datetime.datetime
colidx = getattr(self.params, self.datafields[0])
dt = row[colidx]
dtnum = date2num(dt)
# get the line to be set
line = getattr(self.lines, self.datafields[0])
line[0] = dtnum
# Done ... return
return True
开发者ID:adriantorrie,项目名称:backtrader,代码行数:30,代码来源:blaze.py
示例7: _load
def _load(self):
if self._state == self._ST_NOTFOUND:
return False # nothing can be done
while True:
try:
# tmout <> 0 only if resampling/replaying, else no waking up
tmout = self._qcheck * bool(self.resampling)
msg = self.q.get(timeout=tmout)
except queue.Empty:
return None
if msg is None:
return False # end of stream
if msg == self.store._RT_SHUTDOWN:
self.put_notification(self.DISCONNECTED)
return False # VC has exited
if msg == self.store._RT_DISCONNECTED:
self.put_notification(self.CONNBROKEN)
continue
if msg == self.store._RT_CONNECTED:
self.put_notification(self.CONNECTED)
self.put_notification(self.DELAYED)
continue
if msg == self.store._RT_LIVE:
if self._laststatus != self.LIVE:
self.put_notification(self.LIVE)
continue
if msg == self.store._RT_DELAYED:
if self._laststatus != self.DELAYED:
self.put_notification(self.DELAYED)
continue
if isinstance(msg, integer_types):
self.put_notification(self.UNKNOWN, msg)
continue
# it must be a bar
bar = msg
# Put the tick into the bar
self.lines.open[0] = bar.Open
self.lines.high[0] = bar.High
self.lines.low[0] = bar.Low
self.lines.close[0] = bar.Close
self.lines.volume[0] = bar.Volume
self.lines.openinterest[0] = bar.OpenInterest
# Convert time to "market" time (096 exception)
dt = self.NULLDATE + timedelta(days=bar.Date) - self._mktoffset
self.lines.datetime[0] = date2num(dt)
return True
开发者ID:aaron8tang,项目名称:backtrader,代码行数:58,代码来源:vcdata.py
示例8: _load_rtbar
def _load_rtbar(self, rtbar):
# Datetime transformation
self.lines.datetime[0] = date2num(rtbar.time)
# Put the tick into the bar
self.lines.open[0] = rtbar.open
self.lines.high[0] = rtbar.high
self.lines.low[0] = rtbar.low
self.lines.close[0] = rtbar.close
self.lines.volume[0] = rtbar.volume
self.lines.openinterest[0] = 0
return True
开发者ID:avayayu,项目名称:hyzou,代码行数:13,代码来源:ibData.py
示例9: push_commissionreport
def push_commissionreport(self, cr):
with self._lock_orders:
ex = self.executions.pop(cr.m_execId)
oid = ex.m_orderId
order = self.orderbyid[oid]
ostatus = self.ordstatus[oid].pop(ex.m_cumQty)
position = self.getposition(order.data, clone=False)
pprice_orig = position.price
size = ex.m_shares if ex.m_side[0] == 'B' else -ex.m_shares
price = ex.m_price
# use pseudoupdate and let the updateportfolio do the real update?
psize, pprice, opened, closed = position.update(size, price)
# split commission between closed and opened
comm = cr.m_commission
closedcomm = comm * closed / size
openedcomm = comm - closedcomm
comminfo = order.comminfo
closedvalue = comminfo.getoperationcost(closed, pprice_orig)
openedvalue = comminfo.getoperationcost(opened, price)
# default in m_pnl is MAXFLOAT
pnl = cr.m_realizedPNL if closed else 0.0
# The internal broker calc should yield the same result
# pnl = comminfo.profitandloss(-closed, pprice_orig, price)
# Use the actual time provided by the execution object
# The report from TWS is in actual local time, not the data's tz
dt = date2num(datetime.strptime(ex.m_time, '%Y%m%d %H:%M:%S'))
# Need to simulate a margin, but it plays no role, because it is
# controlled by a real broker. Let's set the price of the item
margin = order.data.close[0]
order.execute(dt, size, price,
closed, closedvalue, closedcomm,
opened, openedvalue, openedcomm,
margin, pnl,
psize, pprice)
if ostatus.status == self.FILLED:
order.completed()
self.ordstatus.pop(oid) # nothing left to be reported
else:
order.partial()
if oid not in self.tonotify: # Lock needed
self.tonotify.append(oid)
开发者ID:remroc,项目名称:backtrader,代码行数:51,代码来源:ibbroker.py
示例10: _frombars
def _frombars(self):
dtime, price = self._fillbars.popleft()
price = self.p.fill_price or price
self.lines.datetime[0] = date2num(dtime)
self.lines.open[0] = price
self.lines.high[0] = price
self.lines.low[0] = price
self.lines.close[0] = price
self.lines.volume[0] = self.p.fill_vol
self.lines.openinterest[0] = self.p.fill_oi
return True
开发者ID:adriantorrie,项目名称:backtrader,代码行数:14,代码来源:datafiller.py
示例11: _load_rtvolume
def _load_rtvolume(self, rtvol):
# Datetime transformation
self.lines.datetime[0] = date2num(rtvol.datetime)
# Put the tick into the bar
tick = rtvol.price
self.lines.open[0] = tick
self.lines.high[0] = tick
self.lines.low[0] = tick
self.lines.close[0] = tick
self.lines.volume[0] = rtvol.size
self.lines.openinterest[0] = 0
return True
开发者ID:avayayu,项目名称:hyzou,代码行数:14,代码来源:ibData.py
示例12: _load
def _load(self):
if self.f is None:
return False # cannot load more
try:
bardata = self.f.read(self._barsize)
except IOError:
self.f = None # cannot return, nullify file
return False # cannot load more
if not bardata or len(bardata) < self._barsize:
self.f = None # cannot return, nullify file
return False # cannot load more
try:
bdata = unpack(self._barfmt, bardata)
except:
self.f = None
return False
# First Date
y, md = divmod(bdata[0], 500) # Years stored as if they had 500 days
m, d = divmod(md, 32) # Months stored as if they had 32 days
dt = datetime(y, m, d)
# Time
if self._dtsize > 1: # Minute Bars
# Daily Time is stored in seconds
hhmm, ss = divmod(bdata[1], 60)
hh, mm = divmod(hhmm, 60)
dt = dt.replace(hour=hh, minute=mm, second=ss)
else: # Daily Bars
dt = datetime.combine(dt, self.p.sessionend)
self.lines.datetime[0] = date2num(dt) # Store time
# Get the rest of the fields
o, h, l, c, v, oi = bdata[self._dtsize:]
self.lines.open[0] = o
self.lines.high[0] = h
self.lines.low[0] = l
self.lines.close[0] = c
self.lines.volume[0] = v
self.lines.openinterest[0] = oi
return True # a bar has been successfully loaded
开发者ID:aaron8tang,项目名称:backtrader,代码行数:46,代码来源:vchartfile.py
示例13: _load_rtbar
def _load_rtbar(self, rtbar, hist=False):
# A complete 5 second bar made of real-time ticks is delivered and
# contains open/high/low/close/volume prices
# The historical data has the same data but with 'date' instead of
# 'time' for datetime
dt = date2num(rtbar.time if not hist else rtbar.date)
if dt <= self.lines.datetime[-1] and not self.p.latethrough:
return False # cannot deliver earlier than already delivered
self.lines.datetime[0] = dt
# Put the tick into the bar
self.lines.open[0] = rtbar.open
self.lines.high[0] = rtbar.high
self.lines.low[0] = rtbar.low
self.lines.close[0] = rtbar.close
self.lines.volume[0] = rtbar.volume
self.lines.openinterest[0] = 0
return True
开发者ID:Aulla,项目名称:backtrader,代码行数:19,代码来源:ibdata.py
示例14: _adjusttime
def _adjusttime(self, index=0):
'''
Adjusts the time of calculated bar (from underlying data source) by
using the timeframe to the appropriate boundary taken int account
compression
Depending on param ``rightedge`` uses the starting boundary or the
ending one
'''
# Get current time
tm = self.lines.datetime.time(0)
# Get the point of the day in the time frame unit (ex: minute 200)
point = self._gettmpoint(tm)
# Apply compression to update the point position (comp 5 -> 200 // 5)
point = (point // self.p.compression)
# If rightedge (end of boundary is activated) add it
if point % self.p.compression:
point += self.p.rightedge
# Restore point to the timeframe units by de-applying compression
point *= self.p.compression
# Get hours, minutes, seconds and microseconds
if self._timeframe == TimeFrame.Minutes:
ph, pm = divmod(point, 60)
ps = 0
pus = 0
elif self._timeframe == TimeFrame.Seconds:
ph, pm = divmod(point, 60 * 60)
pm, ps = divmod(pm, 60)
pus = 0
elif self._timeframe == TimeFrame.MicroSeconds:
ph, pm = divmod(point, 60 * 60 * 1e6)
pm, psec = divmod(pm, 60 * 1e6)
ps, pus = divmod(psec, 1e6)
# Get current datetime value which was taken from data
dt = self.lines.datetime.datetime(index)
# Replace intraday parts with the calculated ones and update it
dt = dt.replace(hour=ph, minute=pm, second=ps, microsecond=pus)
self.lines.datetime[0] = date2num(dt)
开发者ID:beforewind,项目名称:backtrader,代码行数:42,代码来源:resampler.py
示例15: _load
def _load(self):
if self.f is None:
# if no file ... no parsing
return False
# Read the needed amount of binary data
bardata = self.f.read(self.barsize)
if not bardata:
# if no data was read ... game over say "False"
return False
# use struct to unpack the data
bdata = struct.unpack(self.barfmt, bardata)
# Years are stored as if they had 500 days
y, md = divmod(bdata[0], 500)
# Months are stored as if they had 32 days
m, d = divmod(md, 32)
# put y, m, d in a datetime
dt = datetime.datetime(y, m, d)
if self.dtsize > 1: # Minute Bars
# Daily Time is stored in seconds
hhmm, ss = divmod(bdata[1], 60)
hh, mm = divmod(hhmm, 60)
# add the time to the existing atetime
dt = dt.replace(hour=hh, minute=mm, second=ss)
self.lines.datetime[0] = date2num(dt)
# Get the rest of the unpacked data
o, h, l, c, v, oi = bdata[self.dtsize:]
self.lines.open[0] = o
self.lines.high[0] = h
self.lines.low[0] = l
self.lines.close[0] = c
self.lines.volume[0] = v
self.lines.openinterest[0] = oi
# Say success
return True
开发者ID:adriantorrie,项目名称:backtrader,代码行数:41,代码来源:vchart.py
示例16: _load_rtvolume
def _load_rtvolume(self, rtvol):
# A single tick is delivered and is therefore used for the entire set
# of prices. Ideally the
# contains open/high/low/close/volume prices
# Datetime transformation
dt = date2num(rtvol.datetime)
if dt <= self.lines.datetime[-1] and not self.p.latethrough:
return False # cannot deliver earlier than already delivered
self.lines.datetime[0] = dt
# Put the tick into the bar
tick = rtvol.price
self.lines.open[0] = tick
self.lines.high[0] = tick
self.lines.low[0] = tick
self.lines.close[0] = tick
self.lines.volume[0] = rtvol.size
self.lines.openinterest[0] = 0
return True
开发者ID:Aulla,项目名称:backtrader,代码行数:21,代码来源:ibdata.py
示例17: __call__
def __call__(self, data):
'''
Return Values:
- False: data stream was not touched
- True: data stream was manipulated (bar outside of session times and
- removed)
'''
datadt = data.datetime.datetime()
newdt = datetime(datadt.year,
datadt.month,
datadt.day,
datadt.hour,
datadt.minute,
0)
dseconds = (datadt - newdt).seconds
if dseconds <= self.p.jitter:
data.datetime[0] = backtrader.date2num(newdt)
return True
return False
开发者ID:joequant,项目名称:sptrader,代码行数:21,代码来源:jitter.py
示例18: _load_tick
def _load_tick(self, msg):
dtobj = datetime.utcfromtimestamp(int(msg['time']) / 10 ** 6)
dt = date2num(dtobj)
if dt <= self.lines.datetime[-1]:
return False # time already seen
# Common fields
self.lines.datetime[0] = dt
self.lines.volume[0] = 0.0
self.lines.openinterest[0] = 0.0
# Put the prices into the bar
tick = float(msg['ask']) if self.p.useask else float(msg['bid'])
self.lines.open[0] = tick
self.lines.high[0] = tick
self.lines.low[0] = tick
self.lines.close[0] = tick
self.lines.volume[0] = 0.0
self.lines.openinterest[0] = 0.0
return True
开发者ID:aaron8tang,项目名称:backtrader,代码行数:21,代码来源:oanda.py
示例19: _fillbar
def _fillbar(self, data, dtime):
# Prepare an array of the needed size
bar = [float('Nan')] * data.size()
# Fill datetime
bar[data.DateTime] = date2num(dtime)
# Fill the prices
price = self.p.fill_price or data.close[-1]
for pricetype in [data.Open, data.High, data.Low, data.Close]:
bar[pricetype] = price
# Fill volume and open interest
bar[data.Volume] = self.p.fill_vol
bar[data.OpenInterest] = self.p.fill_oi
# Fill extra lines the data feed may have defined beyond DateTime
for i in range(data.DateTime + 1, data.size()):
bar[i] = data.lines[i][0]
# Add tot he stack of bars to save
data._add2stack(bar)
return True
开发者ID:adriantorrie,项目名称:backtrader,代码行数:24,代码来源:session.py
示例20: load
def load(self):
while True:
# move data pointer forward for new bar
self.forward()
if self._fromstack(): # bar is available
return True
if not self._fromstack(stash=True):
_loadret = self._load()
if not _loadret: # no bar use force to make sure in exactbars
# the pointer is undone this covers especially (but not
# uniquely) the case in which the last bar has been seen
# and a backwards would ruin pointer accounting in the
# "stop" method of the strategy
self.backwards(force=True) # undo data pointer
# return the actual returned value which may be None to
# signal no bar is available, but the data feed is not
# done. False means game over
return _loadret
# Get a reference to current loaded time
dt = self.lines.datetime[0]
# A bar has been loaded, adapt the time
if self._tzinput:
# Input has been converted at face value but it's not UTC in
# the input stream
dtime = num2date(dt) # get it in a naive datetime
# localize it
dtime = self._tzinput.localize(dtime) # pytz compatible-ized
self.lines.datetime[0] = dt = date2num(dtime) # keep UTC val
# Check standard date from/to filters
if dt < self.fromdate:
# discard loaded bar and carry on
self.backwards()
continue
if dt > self.todate:
# discard loaded bar and break out
self.backwards(force=True)
break
# Pass through filters
retff = False
for ff, fargs, fkwargs in self._filters:
# previous filter may have put things onto the stack
if self._barstack:
for i in range(len(self._barstack)):
self._fromstack(forward=True)
retff = ff(self, *fargs, **fkwargs)
else:
retff = ff(self, *fargs, **fkwargs)
if retff: # bar removed from systemn
break # out of the inner loop
if retff: # bar removed from system - loop to get new bar
continue # in the greater loop
# Checks let the bar through ... notify it
return True
# Out of the loop ... no more bars or past todate
return False
开发者ID:aaron8tang,项目名称:backtrader,代码行数:66,代码来源:feed.py
注:本文中的backtrader.date2num函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论