def order(self, args={}): error = self.__validate(args) if error is not None: return Response().from_error(error) #asset type symbol = args["symbol"] asset_type = args["asset_type"] trade_type = args["order_type"] symbol_obj = db.session.query(StockSymbol).filter( StockSymbol.symbol == symbol ).first() #check existence of symbol if symbol_obj is None: return Response(msg="El symbol {} no existe".format(symbol)).get() #stock if trade_type == "B": self.__buy(symbol, args) if trade_type == "S": self.__sell(symbol, args) try: db.session.commit() return Response(msg="Orden de compra ejecutada").get() except: return Response(success=False,msg="Error al guardar la orden de compra").get()
def song_search(keyword): """ 搜索音乐 /netease/song/keyword/search :return: """ try: if keyword is None or keyword is '' or len(keyword) is 0: return Response.error(keyword, message='keyword can not be null.') return Response.success(MusicooService.song_search(keyword).to_json()) except Exception as e: log.error('[Musicoo] ip: {};\t\terror: {}'.format(request.remote_addr, e)) return Response.error()
def get(self, args={}): response_list = [] #get actual user trades trades = self.get_trades() #get balance balance_list, error = self._refresh_balance(trades) if error is not None: return Response().from_error(error) for element, create in balance_list: response_list.append(element) return Response(input_data=response_list).get()
def get_option_eod_data(self, args={}): contract_symbol = args["symbol"] jsonrsp = False if "json" in args and args["json"] == True: jsonrsp = True endpoint = "{0}/options/{1}/chart".format(self.base_endpoint, contract_symbol) headers = {'Content-Type': 'application/json'} params = {"token": self.key} rsp = requests.get(endpoint, params=params, headers=headers) data = rsp.json() elem = next(iter(data)) last_trade_date = elem["lastTradeDate"] last_update = date.today() quote = Quote(asset_type="options", symbol=contract_symbol, price_date=last_trade_date, open=elem["open"], high=elem["high"], low=elem["low"], close=elem["close"], volume=elem["volume"], last_update=last_update, last_price_date=last_trade_date) if jsonrsp: return Response(input_data=quote).get() return quote
def load(self, args={}): key = app.config["ALPHAVANTAGE_KEY"] # replace the "demo" apikey below with your own key from https://www.alphavantage.co/support/#api-key CSV_URL = 'https://www.alphavantage.co/query?function=LISTING_STATUS&apikey={}'.format(key) with requests.Session() as s: download = s.get(CSV_URL) decoded_content = download.content.decode('utf-8') cr = csv.reader(decoded_content.splitlines(), delimiter=',') my_list = list(cr) rownumber = 0 for row in my_list: rownumber+=1 if rownumber >1: symbol = StockSymbol( symbol=row[0], name=row[1], exchange=row[2], asset_type=row[3] ) db.session.add(symbol) db.session.commit() return Response(msg="Se ha cargado correctamente los símbolos").get()
def song(keyword): """ url,歌词,detail /netease/song/1379444316 /netease/song/差不多姑娘 :param keyword: :return: """ try: if keyword is None or keyword is '' or len(keyword) is 0: return Response.error(keyword, message='keyword can not be null.') return Response.success(MusicooService.song(keyword).to_json()) except Exception as e: log.error('[Musicoo] ip: {};\t\terror: {}'.format(request.remote_addr, e)) return Response.error()
def songs_search(keyword, offset, limit): """ 搜索音乐们 /netease/songs/keyword/search :param keyword 关键字 :param offset 页数 :param limit 数量 :return: """ try: if keyword is None or keyword is '' or len(keyword) is 0: return Response.error(keyword, message='keyword can not be null.') return Response.success(MusicooService.songs_search(keyword, offset=offset, limit=limit)) except Exception as e: log.error('[Musicoo] ip: {};\t\terror: {}'.format(request.remote_addr, e)) return Response.error()
def song_lyric(song_id): """ 获取音乐歌词 /netease/song/1379444316/lyric :param song_id: :return: """ try: if song_id is None or song_id is '' or len(song_id) is 0: return Response.error(song_id, message='song_id can not be null.') if song_id.isdigit() is False: return Response.error(song_id, message='song_id must be digit.') return Response.success(MusicooService.song_lyric(song_id).to_json()) except Exception as e: log.error('[Musicoo] ip: {};\t\terror: {}'.format(request.remote_addr, e)) return Response.error()
def playlist_songs(playlist_id=''): """ 获取歌单列表,音乐 id、音乐名等等 /netease/playlist/3778678/songs :param playlist_id: eg 3778678 :return: """ try: if playlist_id is None or playlist_id is '' or len(playlist_id) is 0: return Response.error(playlist_id, message='playlist_id can not be null.') if playlist_id.isdigit() is False: return Response.error(playlist_id, message='song_id must be digit.') return Response.success( MusicooService.playlist_songs(playlist_id).to_json()) except Exception as e: log.error('[Musicoo] ip: {};\t\terror: {}'.format( request.remote_addr, e)) return Response.error()
def search(self, args={}): search_text="%{}%".format(args["symbol"]) #asset_type =args["asset_type"] symbol_list = db.session.query( StockSymbol ).filter( StockSymbol.symbol.ilike(search_text)#, #StockSymbol.asset_type == asset_type ).all() return Response(input_data=symbol_list).get()
def get_list(self, args={}): dm = DataManager() active_holdings = db.session.query( StockTrade.symbol, StockTrade.asset_type, func.min(StockTrade.trade_date).label('holding_since'), func.sum(StockTrade.buy_price).label("sum_buy_price"), func.sum(StockTrade.buy_price_per_trade).label("sum_buy_price_per_trade"), func.sum(StockTrade.sell_price).label("sum_sell_price"), func.sum(StockTrade.shares_balance).label("sum_shares_balance"), func.min(StockTrade.trade_date).label("min_trade_date") ).filter( StockTrade.shares_balance != 0 ).group_by(StockTrade.symbol)\ .all() #shares_balance * current_price results = [] for elem in active_holdings: elem_dict = Converter.to_dict(elem) quote, error = dm.get_last_quote(elem.symbol) if error is not None: return Response().from_error(error) else: if quote is None: continue if quote.asset_type == "options": price = self.__options_price(elem_dict, quote) results.append(price) continue if quote.asset_type == "Stock": price = self.__stocks_price(elem_dict, quote) results.append(price) continue return Response(input_data=results).get()
def load(self, args={}): symbol = args["symbol"] frequency = args["frequency"] last_price_result = self.get_last_price_date(symbol=symbol, frequency=frequency) function = "TIME_SERIES_{}".format(frequency.upper()) key = app.config["ALPHAVANTAGE_KEY"] endpoint = "https://www.alphavantage.co/query" params = { "function":function, "symbol":symbol, "outputsize":"full", "apikey":key } #series key series_key = { "daily":"Time Series (Daily)", "weekly":"Weekly Time Series" } response = requests.get(endpoint, params=params) data = response.json() symbol = data["Meta Data"]["2. Symbol"] series = data[series_key[frequency]] for key, element in series.items(): price_date = datetime.strptime(key, '%Y-%m-%d').date() if price_date > last_price_result["max_price_date"]: stock_data_row = StockData( symbol=symbol, price_date=key, frequency=frequency, open=element["1. open"], high=element["2. high"], low=element["3. low"], close=element["4. close"], volume=element["5. volume"] ) db.session.add(stock_data_row) else: break db.session.commit() msg = "Cargado correctamente hasta: {}".format(data["Meta Data"]["3. Last Refreshed"]) return Response(msg=msg).get()
def close(self, args): symbol = 'CCL' quotes = db.session.query(StockData).filter( StockData.frequency == "weekly", StockData.symbol == symbol, StockData.price_date >= '2020-01-01').order_by( StockData.price_date).all() weekly_data = [] for elem in quotes: close_pct = round(((elem.close - elem.open) / elem.open) * 100, 3) weekly_elem = { "price_date": elem.price_date.strftime('%Y-%m-%d'), "close_pct": float(close_pct) } weekly_data.append(weekly_elem) return Response(input_data=weekly_data).get()
def get_options_chain(self, args={}): symbol=args["symbol"] #symbol is required expiration_date="" strike="" if "expiration_date" in args: expiration_date = args["expiration_date"] if "strike" in args: strike = args["strike"] #strike = args["strike"] calls_query = db.session.query( OptionContract ).filter( OptionContract.side == 'call', OptionContract.expiration_date >= date.today().isoformat(), OptionContract.underlying == symbol ).order_by(OptionContract.expiration_date, OptionContract.strike) if expiration_date != "": calls_query = calls_query.filter(OptionContract.expiration_date == expiration_date) if strike != "": calls_query = calls_query.filter(OptionContract.strike == strike) calls = calls_query.all() puts_query = db.session.query( OptionContract ).filter( OptionContract.side == 'put', OptionContract.expiration_date >= date.today().isoformat(), OptionContract.underlying == symbol ).order_by(OptionContract.expiration_date, OptionContract.strike) if expiration_date != "": puts_query = puts_query.filter(OptionContract.expiration_date == expiration_date) if strike != "": puts_query = puts_query.filter(OptionContract.strike == strike) puts = puts_query.all() calls = Converter.process_list(calls) puts = Converter.process_list(puts) return Response(input_data={"calls":calls,"puts":puts}).get()
def load_contracts(self, args={}): symbol=args["symbol"] #contracts = MarketApi().get_option_contracts(symbol=symbol) with open('tmp/CCLContracts.json') as f: contracts = f.read() contracts = json.loads(contracts) for elem in contracts: contract_symbol = elem["symbol"] sym = self.get_symbol(contract_symbol) if sym is None: ss = StockSymbol( symbol = contract_symbol, name = elem["description"], exchange = elem["exchange"], asset_type = "options" ) db.session.add(ss) db.session.flush() #adding the details oc = OptionContract( symbol_id = ss.id, contract_size = elem["contractSize"], currency = elem["currency"], description = elem["description"], expiration_date = elem["expirationDate"], side = elem["side"], strike = elem["strike"], symbol = elem["symbol"], underlying = elem["underlying"], register_date = date.today() ) db.session.add(oc) db.session.commit() return Response(msg="Se han cargado correctamente los symbol de los contratos para {}".format(symbol)).get()
import sys, json from app import app from common.Response import Response #app.run(debug=False) try: app.run(debug=False) except Exception: rsp = json.dumps( Response(msg="Error no controlado del programa", success=False, code=-1).get()) print(rsp)
def request_handle(request_handler: tornado.web.RequestHandler, query_params: QueryParams): response = Response() result = dict() try: print("") query_params.check() except BadRequest as e: msg = str(e) logger.warn(msg) code = ResponseStatusCode.BAD_REQUEST.value response.__init__(resp_status=code, code=code, msg=msg, result=result) except Unauthorized as e: msg = str(e) logger.warn(msg) code = ResponseStatusCode.UNAUTHORIZED.value response.__init__(resp_status=code, code=code, msg=msg, result=result) except Exception as e: print(str(e)) print(sys.exc_info()[0]) msg = str(e) logger.warn(msg) code = ResponseStatusCode.INTERNAL_SERVER_ERROR.value response.__init__(resp_status=code, code=code, msg=msg, result=result) else: code = ResponseStatusCode.SUCCESS.value response.__init__(resp_status=code, code=code, msg="OK", result=result) response_str = response.generate_response(request_handler) return response_str
def make_response(self): return Response(success=self.success, msg=self.message, extradata=self.data).get()
def get_list(self, args): quotes = StockData.query.filter( StockData.price_date >= '2021-05-25' ).all() return Response(input_data=quotes, formatter=ChangeFormatter()).get()