def fetch_quotes(ticker_id_dict): global logger global logger_alert # timestamp start_time = datetime.datetime.now() fetch_time = chop_microseconds(start_time) count = -1 try: # build query url for api baseurl = "https://query.yahooapis.com/v1/public/yql?" yql_query = "select * from yahoo.finance.quote where symbol in ('" ticker_url = "','".join(ticker_id_dict.keys()) yql_query = yql_query + ticker_url + "')" yql_url = baseurl + urllib.urlencode({'q': yql_query}) + \ "&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback=" # get data for i in range(5): try: result = urllib2.urlopen(yql_url).read() log_string = '(QUERY:' + yql_url + '),SUCCESS' logger.info(log_string) break except: log_string = '(QUERY:' + yql_url + '),FAIL' logger.info(log_string) if (i == 4): return data = json.loads(result) quote_data = data['query']['results']['quote'] # create objects quotes = [Entry.Quote(id=ticker_id_dict[q['symbol']], price=unicode2int(q['LastTradePriceOnly']), volume=q['Volume'], time=fetch_time) for q in quote_data] count = len(quotes) # write results into db Entry.Quote.add(quotes) result = 'True' except Exception as e: result = 'False' logger_alert.exception('fetch_error@' + str(fetch_time)) finish_time = datetime.datetime.now() log_string = "[({0}),({1}),{2},{3}]".format(start_time, finish_time, result, count) logger.info(log_string)
def buy(self, portfolio, stock, shares, price): # get order time start_time = datetime.datetime.now() order_time = chop_microseconds(start_time) try: # do calculation total = price * shares + self.commission # get portfolio, cash position, and stock id port = Portfolio.search(name=portfolio)[0] st = Stock.search(ticker=stock)[0] cash = Position.search(portfolio=port['id'], stock=0)[0] if cash['total_cost'] < total: result = 'False' self.logger_alert.exception( 'Order_error: buy@' + str(order_time) + ': portfolio %s not enough balance' % portfolio) else: # add or update position positions = Position.search(portfolio=port['id'], stock=st['id']) if positions == []: pos = Position(portfolio=port['id'], stock=st['id'], shares=shares, avg_cost=total / shares, total_cost=total, aggr_cost=total) Position.add([pos]) else: pos = positions[0] pos['shares'] += shares pos['total_cost'] += total pos['aggr_cost'] += total pos['avg_cost'] = pos['total_cost'] / pos['shares'] pos.save() # update cash cash['shares'] -= total cash['total_cost'] -= total cash.save() # record transaction trans = Transaction(time=order_time, portfolio=port['id'], stock=st['id'], action='buy', shares=shares, price=price, total=total) Transaction.add([trans]) result = 'True' except Exception: result = 'False' self.logger_alert.exception('Order_error: buy@' + str(order_time)) log_string = '%s: portfolio %s bought %d shares %s @ $%d/share. %s.' % ( str(order_time), portfolio, shares, stock, price, result) self.logger.info(log_string)
def short(self, portfolio, stock, shares, price): # get order time start_time = datetime.datetime.now() order_time = chop_microseconds(start_time) try: # do calculation total = price * shares - self.commission # get portfolio, cash, and stock id port = Portfolio.search(name=portfolio)[0] st = Stock.search(ticker=stock)[0] cash = Position.search(portfolio=port['id'], stock=0)[0] # add or update position result = Position.search(portfolio=port['id'], stock=st['id']) if result == []: pos = Position(portfolio=port['id'], stock=st['id'], shares=(-shares), avg_cost=total / shares, total_cost=(-total), aggr_cost=(-total)) Position.add([pos]) else: pos = result[0] if pos['shares'] > 0: result = 'False' self.logger_alert.exception( 'Order_error: short@' + str(order_time) + ': portfolio %s has long position' % portfolio) else: pos['shares'] -= shares pos['total_cost'] -= total pos['avg_cost'] = pos['total_cost'] / pos['shares'] pos['aggr_cost'] -= total pos.save() # update cash cash['shares'] += total cash['total_cost'] += total cash.save() # record transaction trans = Transaction(time=order_time, portfolio=port['id'], stock=st['id'], action='short', shares=(-shares), price=price, total=(-total)) Transaction.add([trans]) result = 'True' except Exception: result = 'False' self.logger_alert.exception('Order_error: short@' + str(order_time)) log_string = '%s: portfolio %s shortsold %d shares %s @ $%d/share. %s.' % ( str(order_time), portfolio, shares, stock, price, result) self.logger.info(log_string)
def sell(self, portfolio, stock, shares, price): # get order time start_time = datetime.datetime.now() order_time = chop_microseconds(start_time) try: # do calculation total = price * shares - self.commission # get portfolio, position, cash, and stock id port = Portfolio.search(name=portfolio)[0] st = Stock.search(ticker=stock)[0] cash = Position.search(portfolio=port['id'], stock=0)[0] pos = Position.search(portfolio=port['id'], stock=st['id'])[0] if pos['shares'] < shares: result = 'False' self.logger_alert.exception( 'Order_error: sell@' + str(order_time) + ': portfolio %s not enough shares' % portfolio) else: # update position pos['total_cost'] -= pos['total_cost'] * shares / pos['shares'] pos['shares'] -= shares pos['aggr_cost'] -= total if pos['shares'] == 0: pos['avg_cost'] = 0 pos.save() # update cash cash['shares'] += total cash['total_cost'] += total cash.save() # record transaction trans = Transaction(time=order_time, portfolio=port['id'], stock=st['id'], action='sell', shares=(-shares), price=price, total=(-total)) Transaction.add([trans]) result = 'True' except Exception: result = 'False' self.logger_alert.exception('Order_error: sell@' + str(order_time)) log_string = '%s: portfolio %s sold %d shares %s @ $%d/share. %s.' % ( str(order_time), portfolio, shares, stock, price, result) self.logger.info(log_string)
record = Indicator.search(id=self.id, time=self.quotes[self.period - 1]['time']) k_1 = 50 d_1 = 50 if 'k' in record[0].keys() and record[0]['k'] > 0: k_1 = record[0]['k'] if 'd' in record[0].keys() and record[0]['d'] > 0: d_1 = record[0]['d'] rsv = (self.price(self.period) - self.low(self.period - 9, self.period)) / ( self.high(self.period - 9, self.period) - self.low(self.period - 9, self.period)) * 100 k = rsv / 3 + 2 * k_1 / 3 d = k / 3 + 2 * d_1 / 3 j = 3 * d - 2 * k return k, d, j def boll(self): pass def wr(self): pass def vr(self): pass def record(self): pass if __name__ == '__main__': time = chop_microseconds(datetime.datetime(2015, 7, 31, 4, 0, 0)) cal = iCalculator('YHOO', time, 30, 30)