def addBar(self, instrument, bar, frequency): instrument = normalize_instrument(instrument) instrumentId = self.__getOrCreateInstrument(instrument) timeStamp = dt.datetime_to_timestamp(bar.getDateTime()) try: sql = "insert into bar (instrument_id, frequency, timestamp, open, high, low, close, volume, adj_close) values (?, ?, ?, ?, ?, ?, ?, ?, ?)" params = [ instrumentId, frequency, timeStamp, bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose(), bar.getVolume(), bar.getAdjClose() ] self.__connection.execute(sql, params) except sqlite3.IntegrityError: sql = "update bar set open = ?, high = ?, low = ?, close = ?, volume = ?, adj_close = ?" \ " where instrument_id = ? and frequency = ? and timestamp = ?" params = [ bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose(), bar.getVolume(), bar.getAdjClose(), instrumentId, frequency, timeStamp ] self.__connection.execute(sql, params)
def adjustBars(instrument, bars, startdate, enddate): bars = [] bars_in_dtrange = [bar for bar in bars if startdate.replace(tzinfo=None) <= bar.getDateTime() <= enddate.replace(tzinfo=None)] bars_in_dtrange.sort(key=lambda bar: bar.getDateTime(), reverse=True) k = 0 splitdataList = [] dividendList = [] for bar in bars_in_dtrange: splitdata = bar.getSplit() dividend = bar.getDividend() if splitdata != 1.0: splitdataList.append(bar.getSplit()) if dividend != 0.0: adjFactor = (bar.getClose() + bar.getDividend()) / bar.getClose() dividendList.append(adjFactor) #### Special case.... end date / analysis date nothing to do.. if (k==0): bar = BasicBar(bar.getDateTime(), bar.getOpen() , bar.getHigh(), bar.getLow(), bar.getClose(), bar.getVolume(), bar.getClose(), Frequency.DAY) bars.append(bar) else: #### Adjust OHLC & Volume data for split adjustments and dividend adjustments Open = bar.getOpen() High = bar.getHigh() Low = bar.getLow() Close = bar.getClose() Volume = bar.getVolume() ### adjust data for splits for split in splitdataList: Open = Open / split High = High / split Low = Low / split Close = Close /split Volume = Volume * split ### adjust data for dividends for adjFactor in dividendList: Open = Open / adjFactor High = High / adjFactor Low = Low / adjFactor Close = Close / adjFactor Volume = Volume * adjFactor bar = BasicBar(bar.getDateTime(), Open , High, Low, Close, Volume, Close, Frequency.DAY) bars.append(bar) k +=1 feed = Feed(Frequency.DAY, 1024) return feed.loadBars(instrument+"_adjusted", bars)
def fillMarketOrder(self, broker_, order, bar): # Calculate the fill size for the order. fillSize = self.__calculateFillSize(broker_, order, bar) if fillSize == 0: broker_.getLogger().debug( "Not enough volume to fill %s market order [%s] for %s share/s" % ( order.getInstrument(), order.getId(), order.getRemaining() ) ) return None # Unless its a fill-on-close order, use the open price. if order.getFillOnClose(): price = bar.getClose(broker_.getUseAdjustedValues()) else: price = bar.getOpen(broker_.getUseAdjustedValues()) assert price is not None # Don't slip prices when the bar represents the trading activity of a single trade. if bar.getFrequency() != pyalgotrade.bar.Frequency.TRADE: price = self.__slippageModel.calculatePrice( order, price, fillSize, bar, self.__volumeUsed[order.getInstrument()] ) return FillInfo(price, fillSize)
def compute_BBands(instrument, startdate, enddate ): from pyalgotrade.talibext import indicator bBandsPeriod = 20 #### No of periods..... feed = redis_build_feed_EOD_RAW(instrument, startdate, enddate) barsDictForCurrAdj = {} barsDictForCurrAdj[instrument] = feed.getBarSeries(instrument) feedLookbackEndAdj = xiquantPlatform.xiQuantAdjustBars(barsDictForCurrAdj, startdate, enddate) feedLookbackEndAdj.adjustBars() closeDS = feedLookbackEndAdj.getCloseDataSeries(instrument + "_adjusted") upper, middle, lower = indicator.BBANDS(closeDS, len(closeDS), bBandsPeriod, 2.0, 2.0) dateTimes = feedLookbackEndAdj.getDateTimes(instrument + "_adjusted") upperDS = numpy_to_highchartds(dateTimes, upper, startdate, enddate) middleDS = numpy_to_highchartds(dateTimes, middle, startdate, enddate) lowerDS = numpy_to_highchartds(dateTimes, lower, startdate, enddate) ##########Display price seriesin the center of Bolinger bands......################## barDS = feedLookbackEndAdj.getBarSeries(instrument + "_adjusted") adj_Close_Series = [] for bar in barDS: dt = bar.getDateTime() sec = calendar.timegm(dt.timetuple()) dtInMilliSeconds = int(sec * 1000) adjPrice_val = [dtInMilliSeconds, bar.getOpen(), bar.getHigh(), \ bar.getLow(), bar.getClose()] adj_Close_Series.append(adjPrice_val) return upperDS, middleDS, lowerDS, adj_Close_Series
def fillMarketOrder(self, broker_, order, bar): broker_.getLogger().debug('fillMarketOrder') # Calculate the fill size for the order. fillSize = self.__calculateFillSize(broker_, order, bar) if fillSize == 0: broker_.getLogger().debug( "Not enough volume to fill %s market order [%s] for %s share/s" % (order.getInstrument(), order.getId(), order.getRemaining())) return None # Unless its a fill-on-close order, use the open price. if order.getFillOnClose(): broker_.getLogger().debug('fillMarketOrder -> getFillOnClose()') price = bar.getClose(broker_.getUseAdjustedValues()) else: broker_.getLogger().debug('fillMarketOrder -> getFillOnOpen()') price = bar.getOpen(broker_.getUseAdjustedValues()) assert price is not None # Don't slip prices when the bar represents the trading activity of a single trade. if bar.getFrequency() != pyalgotrade.bar.Frequency.TRADE: price = self.__slippageModel.calculatePrice( order, price, fillSize, bar, self.__volumeUsed[order.getInstrument()]) broker_.getLogger().debug('fillMarketOrder, return FillInfo') return FillInfo(price, fillSize)
def onBars(self, bars): lower = self.__bbands.getLowerBand()[-1] upper = self.__bbands.getUpperBand()[-1] if lower is None: return shares = self.getBroker().getShares(self.__instrument) bar = bars[self.__instrument] if shares == 0 and bar.getClose() < lower: sharesToBuy = int(self.getBroker().getCash(False) / bar.getClose()) self.__position = self.enterLong(self.__instrument, sharesToBuy, False) elif shares > 0 and bar.getClose() > upper: self.__position.exitMarket()
def onBars(self, bars): # get Close price and budget ... bar = bars[self.__instrument] price = bar.getClose() # history prices prices = self.getFeed()[ self.__instrument].getCloseDataSeries()[-self.__RLhistory:] # if list is shorter than history, prepend zeros target_length = self.__RLhistory if len(prices) < target_length: prices_lst = [0] * (target_length - len(prices)) + prices else: prices_lst = prices # array shape manipulations budget = np.array([self.__RLinitialCash]).reshape(1, 1) n_coins = np.array([self.__RLncoins]).reshape(1, 1) i_prices = np.array(prices_lst).reshape(1, self.__RLhistory) current_state = np.asmatrix(np.hstack((i_prices, budget, n_coins))) current_portfolio = self.getBroker().getEquity() action = self.__RLpolicy.select_action(current_state) # If a position was not opened, check if policy gave "Buy" action and enter a long position. if self.__position is None: if action == "Buy": self.info("Policy action 'BUY'. Buy at %s" % price) try: self.__position = self.enterLongLimit( self.__instrument, price, self.__posSize, True) self.__RLncoins += self.__posSize except Exception as e: self.error("Failed to buy: %s" % e) else: pass # Check if we have to close the position. elif not self.__position.exitActive() and action == "Sell": try: self.info("Policy action 'SELL'. Sell at %s" % price) self.__position.exitLimit(price) self.__RLncoins -= self.__posSize except Exception as e: self.error("Failed to sell: %s" % e) else: pass new_portfolio = self.getBroker().getCash() + self.__RLncoins * price reward = new_portfolio - current_portfolio n_coins = np.array([self.__RLncoins]).reshape(1, 1) next_state = np.asmatrix(np.hstack((i_prices, budget, n_coins))) self.__RLpolicy.update_q(current_state, reward, next_state)
def onBars(self, bars): for instrument in bars.getInstruments(): bar = bars[instrument] self.info("%s: %s %s %s %s %s %s" % ( instrument, bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose(), bar.getAdjClose(), bar.getVolume(), ))
def fillMarketOrder(self, order, broker_, bar): fillSize = self.__calculateFillSize(order, broker_, bar) if fillSize == 0: return None ret = None if order.getFillOnClose(): price = bar.getClose(broker_.getUseAdjustedValues()) else: price = bar.getOpen(broker_.getUseAdjustedValues()) if price is not None: ret = FillInfo(price, fillSize) return ret
def checkEnterSignal(self, bar): price = bar.getClose() if not self.buyWaitSignal: #check buywait if (self.UPPER[-1] / self.MIDDLE[-1] - 1) < 0.05: pass elif price < self.LOWER[-1]: self.buyWaitSignal = True print bar.getDateTime(), '--------buy wait' elif self.buyWaitSignal and self.checkMinCondition() == 'UP': self.buyWaitSignal = False return True return False
def addBar(self, instrument, bar, frequency): instrument = normalize_instrument(instrument) instrumentId = self.__getOrCreateInstrument(instrument) timeStamp = dt.datetime_to_timestamp(bar.getDateTime()) try: sql = "insert into bar (instrument_id, frequency, timestamp, open, high, low, close, volume, adj_close) values (?, ?, ?, ?, ?, ?, ?, ?, ?)" params = [instrumentId, frequency, timeStamp, bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose(), bar.getVolume(), bar.getAdjClose()] self.__connection.execute(sql, params) except sqlite3.IntegrityError: sql = "update bar set open = ?, high = ?, low = ?, close = ?, volume = ?, adj_close = ?" \ " where instrument_id = ? and frequency = ? and timestamp = ?" params = [bar.getOpen(), bar.getHigh(), bar.getLow(), bar.getClose(), bar.getVolume(), bar.getAdjClose(), instrumentId, frequency, timeStamp] self.__connection.execute(sql, params)
def fillMarketOrder(self, order, broker_, bar): fillSize = self.__calculateFillSize(order, broker_, bar) if fillSize == 0: broker_.getLogger().debug("Not enough volume to fill %s market order [%s] for %d share/s" % (order.getInstrument(), order.getId(), order.getRemaining())) return None ret = None if order.getFillOnClose(): price = bar.getClose(broker_.getUseAdjustedValues()) else: price = bar.getOpen(broker_.getUseAdjustedValues()) if price is not None: ret = FillInfo(price, fillSize) return ret
def checkExitSignal(self, bar): price = bar.getClose() if (bar.getDateTime() - self.holdDay) < timedelta(days=1): # 持有期大于一天 return if not self.sellWaitSignal: #check sellwait if bar.getDateTime().strftime('%Y-%m-%d') == '2016-09-07': print bar.getDateTime(), '---', price, '---', self.UPPER[-1] if price > self.UPPER[-1]: self.sellWaitSignal = True print bar.getDateTime(), '--------sell wait' elif self.sellWaitSignal and self.checkMinCondition() == 'DOWN': self.sellWaitSignal = False return True return False
def onBars(self, bars): # 1.判断日期符合 是否买入卖出 __value = 0 t = self.__handlelist__[self.__order__]['time'] d = datetime.strptime(t, '%Y-%m-%d') if bars.getDateTime() == d: if self.__handlelist__[self.__order__]['position'] == 'buy': # print self.__handlelist__[self.__order__]['amount'] # print self.__handlelist__[self.__order__]['price'] # print self.__handlelist__[self.__order__]['commission'] self.__cost__ += self.__handlelist__[ self.__order__]['amount'] * self.__handlelist__[ self.__order__]['price'] * ( 1 + self.__handlelist__[self.__order__]['commission']) if self.__position__.has_key( self.__handlelist__[self.__order__]['code']): self.__position__[self.__handlelist__[self.__order__] ['code']] += self.__handlelist__[ self.__order__]['amount'] else: self.__position__.setdefault( self.__handlelist__[self.__order__]['code'], self.__handlelist__[self.__order__]['amount']) if self.__handlelist__[self.__order__]['position'] == 'sell': self.__cost__ -= self.__handlelist__[ self.__order__]['amount'] * self.__handlelist__[ self.__order__]['price'] * ( 1 + self.__handlelist__[self.__order__]['commission']) self.__position__[self.__handlelist__[self.__order__][ 'code']] -= self.__handlelist__[self.__order__]['amount'] self.__order__ -= 1 #2、计算持仓价值 for key in self.__position__: bar = bars.getBar(key) if bar is not None: __value += bar.getClose() * self.__position__[key] self.__profit__ = __value - self.__cost__ self.profit.append(self.__profit__) self.date.append(bars.getDateTime().strftime('%Y-%m-%d')) self.cost.append(self.__cost__) self.value.append(__value)
def onBars(self, bars): if self.__atr[-1] is None or self.__atr[-15] is None: return preAtr = self.__atr[-15] nowAtr = self.__atr[-1] per = nowAtr * 0.75 if self.__position is None: if per > preAtr: sharesToBuy = int(self.getBroker().getCash(False) / bar.getClose()) self.__position = self.enterLong(self.__instrument, sharesToBuy, True) # Enter a buy market order for 10 shares. The order is good till canceled. # self.__position = self.enterLong(self.__instrument, 10, True) #print dir(self.__position) # Check if we have to exit the position. elif per < preAtr and not self.__position.exitActive(): self.__position.exitMarket()
def onBars(self, bars): # If a position was not opened, check if we should enter a long position. bar = bars[self.__instrument] # filter datetime ################################################################################### filterCon = len(self.__close) < max( self.__bollingerlength, self.__malength, self.__closelength) self.__filterCon.append(filterCon) if filterCon: return # record position #################################################################################### if self.__longPos is not None and self.__shortPos is None: self.__p.append(1) elif self.__longPos is None and self.__shortPos is not None: self.__p.append(-1) else: self.__p.append(0) # calculate ccMA #################################################################################### ccMACon1 = self.__longPos is not None or self.__shortPos is not None ccMACon2 = self.__malength > self.__ccMAlength if ccMACon1 and ccMACon2: self.__malength = self.__malength - 1 elif not ccMACon1: self.__malength = 50 self.__ccMA = np.mean(self.__close[-self.__malength:]) # print self.__malength, self.__ccMA self.__MA.append(self.__ccMA) self.__ccMACon1.append(ccMACon1) self.__ccMACon2.append(ccMACon2) #open and close condition ###################################################################################### self.__enterLong1 = (cross.cross_above(self.__high, self.__UpperBand) > 0) self.__enterLong2 = (bar.getClose() >= max( self.__close[-self.__closelength:])) self.__enter = ((self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() > float(self.__space) / 1000) # print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() self.__enterShort1 = cross.cross_below(self.__low, self.__LowerBand) > 0 self.__enterShort2 = bar.getClose() <= min( self.__close[-self.__closelength:]) self.__exitLong1 = (bar.getClose() < self.__ccMA) self.__exitLong2 = (self.__ccMA < self.__UpperBand[-1]) self.__exitShort1 = (bar.getClose() > self.__ccMA) self.__exitShort2 = (self.__ccMA > self.__LowerBand[-1]) self.__enterCon.append(self.__enter) self.__enterLongCon1.append(self.__enterLong1) self.__enterLongCon2.append(self.__enterLong2) self.__enterShortCon1.append(self.__enterShort1) self.__enterShortCon2.append(self.__enterShort2) self.__exitLongCon1.append(self.__exitLong1) self.__exitLongCon2.append(self.__exitLong2) self.__exitShortCon1.append(self.__exitShort1) self.__exitShortCon2.append(self.__exitShort2) #open and close ####################################################################################### if self.__longPos is not None: if self.exitLongSignal(): self.__longPos.exitMarket() # if self.__shortPos is not None: # print 11 # self.info("intend long close") # print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() elif self.__shortPos is not None: if self.exitShortSignal(): self.__shortPos.exitMarket() # self.info("intend short close") # print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() else: if self.enterLongSignal(): shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice()) self.__longPos = self.enterLong(self.__instrument, shares) # self.info("intend long open") # print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() elif self.enterShortSignal(): shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice()) self.__shortPos = self.enterShort(self.__instrument, shares)
def onBars(self, bars): # get Close price and budget ... bar = bars[self.__instrument] price = bar.getClose() # history prices prices = self.getFeed()[ self.__instrument].getCloseDataSeries()[-self.__RLhistory:] # if list is shorter than history, prepend zeros target_length = self.__RLhistory if len(prices) < target_length: prices_lst = [0] * (target_length - len(prices)) + prices else: prices_lst = prices # array shape manipulations budget = np.array([self.__RLinitialCash]).reshape(1, 1) n_coins = np.array([self.__RLncoins]).reshape(1, 1) i_prices = np.array(prices_lst).reshape(1, self.__RLhistory) current_state = np.asmatrix(np.hstack((i_prices, budget, n_coins))) current_portfolio = self.getBroker().getEquity() action = self.__RLpolicy.select_action(current_state) # If a position was not opened, check if policy gave "Buy" action and enter a long position. if self.__position is None: if action == "Buy": self.info("Policy action 'BUY'. Trying to Buy at %s" % self.__ask) try: self.__position = self.enterLongLimit( self.__instrument, self.__ask, self.__posSize, True) self.__RLncoins += self.__posSize # update DB update_df = pd.DataFrame( { "Start time": [self.__start_time], "Action": [action], "Portfolio value": [self.getResult()] }, index=[ datetime.datetime.now().strftime( '%Y-%m-%d %H:%M:%S') ]) pandas_to_db(update_df, "trader", "rl_papertrade") except Exception as e: self.error("Failed to buy: %s" % e) else: pass # Check if we have to close the position. elif not self.__position.exitActive() and action == "Sell": try: self.info("Policy action 'SELL'. Trying to Sell at %s" % self.__bid) self.__position.exitLimit(self.__bid) self.__RLncoins -= self.__posSize # update DB update_df = pd.DataFrame( { "Start time": [self.__start_time], "Action": [action], "Portfolio value": [self.getResult()] }, index=[ datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S') ]) pandas_to_db(update_df, "trader", "rl_papertrade") except Exception as e: self.error("Failed to sell: %s" % e) else: pass new_portfolio = self.getBroker().getCash() + self.__RLncoins * price reward = new_portfolio - current_portfolio n_coins = np.array([self.__RLncoins]).reshape(1, 1) next_state = np.asmatrix(np.hstack((i_prices, budget, n_coins))) self.__RLpolicy.update_q(current_state, reward, next_state)
def updateParams(self, bar): self.day_closeDataList.append(bar.getClose()) closeDataArray = np.array(self.day_closeDataList) self.day_closeDataList.pop(-1) self.UPPER, self.MIDDLE, self.LOWER = ta.BBANDS( closeDataArray.astype('float'), 20, 2, 2, 0)
def onBars(self, bars): # If a position was not opened, check if we should enter a long position. bar = bars[self.__instrument] # filter datetime ################################################################################### filterCon = len(self.__close) < max(self.__bollingerlength, self.__malength, self.__closelength) self.__filterCon.append(filterCon) if filterCon: return # record position #################################################################################### if self.__longPos is not None and self.__shortPos is None: self.__p.append(1) elif self.__longPos is None and self.__shortPos is not None: self.__p.append(-1) else: self.__p.append(0) # calculate ccMA #################################################################################### ccMACon1 = self.__longPos is not None or self.__shortPos is not None ccMACon2 = self.__malength > self.__ccMAlength if ccMACon1 and ccMACon2: self.__malength = self.__malength - 1 elif not ccMACon1: self.__malength = 50 self.__ccMA = np.mean(self.__close[-self.__malength:]) # print self.__malength, self.__ccMA self.__MA.append(self.__ccMA) self.__ccMACon1.append(ccMACon1) self.__ccMACon2.append(ccMACon2) #open and close condition ###################################################################################### self.__enterLong1 = (cross.cross_above(self.__high, self.__UpperBand) > 0) self.__enterLong2 = (bar.getClose() >= max(self.__close[-self.__closelength:])) self.__enter = ((self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() > float(self.__space) / 1000) # print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() self.__enterShort1 = cross.cross_below(self.__low, self.__LowerBand) > 0 self.__enterShort2 = bar.getClose() <= min(self.__close[-self.__closelength:]) self.__exitLong1 = (bar.getClose() < self.__ccMA) self.__exitLong2 = (self.__ccMA < self.__UpperBand[-1]) self.__exitShort1 = (bar.getClose() > self.__ccMA) self.__exitShort2 = (self.__ccMA > self.__LowerBand[-1]) self.__enterCon.append(self.__enter) self.__enterLongCon1.append(self.__enterLong1) self.__enterLongCon2.append(self.__enterLong2) self.__enterShortCon1.append(self.__enterShort1) self.__enterShortCon2.append(self.__enterShort2) self.__exitLongCon1.append(self.__exitLong1) self.__exitLongCon2.append(self.__exitLong2) self.__exitShortCon1.append(self.__exitShort1) self.__exitShortCon2.append(self.__exitShort2) #open and close ####################################################################################### if self.__longPos is not None: if self.exitLongSignal(): self.__longPos.exitMarket() # if self.__shortPos is not None: # print 11 # self.info("intend long close") # print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() elif self.__shortPos is not None: if self.exitShortSignal(): self.__shortPos.exitMarket() # self.info("intend short close") # print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() else: if self.enterLongSignal(): shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice()) self.__longPos = self.enterLong(self.__instrument, shares) # self.info("intend long open") # print (self.__UpperBand[-1] - self.__LowerBand[-1]) / bar.getClose() elif self.enterShortSignal(): shares = int(self.getBroker().getCash() * 0.2 / bars[self.__instrument].getPrice()) self.__shortPos = self.enterShort(self.__instrument, shares)
def adjustBars(self): for key, value in self.__barsDict.iteritems(): basicbars = [] bars = value bars_in_dtrange = [bar for bar in bars if self.__startdate.replace(tzinfo=None) <= bar.getDateTime() <= self.__enddate.replace(tzinfo=None)] bars_in_dtrange.sort(key=lambda bar: bar.getDateTime(), reverse=True) k = 0 splitdataList = [] dividendList = [] for bar in bars_in_dtrange: splitdata = float(bar.getSplit()) dividend = float(bar.getDividend()) if splitdata != 1.0: splitdataList.append(bar.getSplit()) if dividend != 0.0: adjFactor = (bar.getClose() + bar.getDividend()) / bar.getClose() dividendList.append(adjFactor) #### Special case.... end date / analysis date nothing to do.. if (k==0): bar = BasicBar(bar.getDateTime(), bar.getOpen() , bar.getHigh(), bar.getLow(), bar.getClose(), bar.getVolume(), bar.getClose(), Frequency.DAY) basicbars.append(bar) else: #### Adjust OHLC & Volume data for split adjustments and dividend adjustments Open = bar.getOpen() High = bar.getHigh() Low = bar.getLow() Close = bar.getClose() Volume = bar.getVolume() ### adjust data for splits for split in splitdataList: Open = Open / split High = High / split Low = Low / split Close = Close /split Volume = Volume * split ### adjust data for dividends for adjFactor in dividendList: Open = Open / adjFactor High = High / adjFactor Low = Low / adjFactor Close = Close / adjFactor Volume = Volume * adjFactor bar = BasicBar(bar.getDateTime(), Open , High, Low, Close, Volume, Close, Frequency.DAY) basicbars.append(bar) k +=1 DateTimes = [] OpenSeries = SequenceDataSeries(4000) HighSeries = SequenceDataSeries(4000) LowSeries = SequenceDataSeries(4000) CloseSeries = SequenceDataSeries(4000) VolumeSeries = SequenceDataSeries(4000) TypicalSeries = SequenceDataSeries(4000) barSeries = BarDataSeries(4000) basicbars.sort(key=lambda bar: bar.getDateTime(), reverse=False) for bar in basicbars: DateTimes.append(bar.getDateTime()) OpenSeries.appendWithDateTime(bar.getDateTime(), bar.getOpen()) HighSeries.appendWithDateTime(bar.getDateTime(), bar.getHigh()) LowSeries.appendWithDateTime(bar.getDateTime(), bar.getLow()) CloseSeries.appendWithDateTime(bar.getDateTime(), bar.getClose()) VolumeSeries.appendWithDateTime(bar.getDateTime(), bar.getVolume()) TypicalSeries.appendWithDateTime(bar.getDateTime(), (bar.getClose()+bar.getHigh()+bar.getLow())/3.0) barSeries.appendWithDateTime(bar.getDateTime(), bar) self.__DateTimes[key+"_adjusted"] = DateTimes self.__OpenDataSeries[key+"_adjusted"] = OpenSeries self.__HighDataSeries[key+"_adjusted"] = HighSeries self.__LowDataSeries[key+"_adjusted"] = LowSeries self.__CloseDataSeries[key+"_adjusted"] = CloseSeries self.__VolumeDataSeries[key+"_adjusted"] = VolumeSeries self.__TypicalDataSeries[key+"_adjusted"] = TypicalSeries self.__barSeries[key+"_adjusted"] = barSeries
def onBars(self, bars): bar = bars[self.__instrument] self.info(bar.getClose())
def __addBar(self, symbol, bar, cursor): string = ("INSERT INTO data (`symbol`, `date`,`milliseconds`, `open`, `close`, `high`, `low`, `volume`) " + "VALUES ('{0:s}', '{1:%Y-%m-%d %H:%M:%S}', '{4:d}','{2:f}', '{2:f}', '{2:f}', '{2:f}', '{3:f}')") queryStr = string.format(symbol, bar.getDateTime(), bar.getClose(), bar.getVolume(), bar.getMilliSeconds()) cursor.execute(queryStr)
def onBars(self, bars): # 每一个数据都会抵达这里 bar = bars[self.__instrument] self.info("%s %s %s" % (bar.getClose(), self.__sma[-1], self.__sma_rsi[-1])) # 我们打印输出收盘价与两分钟均线值
def onBars(self, bars): bar = bars[self.__instrument] # tmp_dtime = bar.getDateTime() self.__dtime = bar.getDateTime() if (None is self.lastDate): self.lastDate = self.__dtime.date() else: if (self.lastDate != self.__dtime.date()): self.lastDate = self.__dtime.date() self.__resetORHL() else: self.barIntradayCount += 1 ## intraday dynamics if (self.openrange > self.barIntradayCount): if bar.getHigh() > self.orh: self.orh = bar.getHigh() if bar.getLow() < self.orl: self.orl = bar.getLow() elif (self.openrange == self.barIntradayCount): self.__resetAC() elif (self.__dtime.time() > self.exitIntradayTradeTime): self.exitAllPositions() else: self.__clos = bar.getClose() self.__dynamics(self.__clos) if (0 == self.stateA): tmp_0 = self.processEvent1() if (1 <= tmp_0): self.action_init2up() elif (-1 >= tmp_0): self.action_init2down() else: if (1 == self.stateA): if (6 == self.stateB): tmp_6 = self.processEvent1() if (1 <= tmp_6): self.action_upempty2duo() elif (-2 == tmp_6): self.action_upempty2kong() elif (2 == self.stateB): tmp_2 = self.processEvent3() if (1 == tmp_2): self.action_upduo2exit_time() elif (4 == self.stateB): tmp_4 = self.processEvent3() if (1 == tmp_4): self.action_upkong2exit_time() else: # self.stateA == -1 if (6 == self.stateB): tmp_6 = self.processEvent1() if (2 == tmp_6): self.action_downempty2duo() elif (-1 >= tmp_6): self.action_downempty2kong() elif (2 == self.stateB): tmp_2 = self.processEvent3() if (1 == tmp_2): self.action_downduo2exit_time() elif (4 == self.stateB): tmp_4 = self.processEvent3() if (1 == tmp_4): self.action_downkong2exit_time()
def resampledOnBar(self, bars): bar = bars[self.__instrument] # pyalgotrade.bar.BasicBar object # print("Date: {} Close: {} PriceHigh: {}" .format(bar.getDateTime(), round(bar.getClose(),2), round(bar.getHigh(),2) )) shares = int(self.getBroker().getCash() * 0.5 / bar.getHigh()) # 80% of cash stock # print("this is current total cash {}" .format(round(self.getBroker().getCash(),2))) # print("shares is {}" .format(shares)) print("Date: {} Open: {} Close: {} PriceLow: {} PriceHigh: {} ".format(bar.getDateTime(), round(bar.getOpen(), 2), round(bar.getClose(), 2),round(bar.getLow()), round(bar.getHigh()))) if self.__position is None: self.__position = self.enterLong(self.__instrument, shares, False, True) # this to enter market order # pyalgotrade.strategy.position.LongPosition object print("enter long for {} shares at {} price".format(shares, bar.getPrice())) print("remaining cash is " + str(self.getBroker().getCash())) print("position is " + str(self.__position.getShares())) elif not self.__position.exitActive(): # Returns True if the exit order is active # if not exit orders being active self.__position.exitMarket(True) # this just submits the market order and self.__position becomes none print("exit for {} shares at {} price".format(self.__position.getShares(), bar.getPrice())) print("remaining cash is " + str(self.getBroker().getCash())) print("position is " + str(self.__position.getShares()))