def post(self, name): data = Stock.parser.parse_args() # not getting the name correctly from the url name = data["name"] if StockModel.find_by_name(name): return {'message': f'A stock with name {name} already exists'}, 400 data = Stock.parser.parse_args() date = data['date'] open_price = data["open_price"] close = data["open_price"] volume = data["volume"] stock = StockModel(name=name, date=date, open_price=open_price, close=close, volume=volume) print(f'{name}:{date}:{open_price}:{close}{volume}') try: stock.save_to_db() except: #raise return {'message': 'an error occurred inserting the stock.'}, 500 #return stock.json(), 201 return redirect("/", code=302)
def post(self): data = _data_parser.parse_args() stock = StockModel(**data) try: stock.save_to_db() except: return {"message":"Ocurrio un error al ingresar un dato a la base de datos."}, 500 return stock.json()
def add_stock(inventory_id): if request.method == 'POST': quantity = request.form['quantity'] new_stock = StockModel(inventory_id=inventory_id, quantity=quantity) new_stock.create_record() flash("Stock added successifully", "success") return redirect(url_for('inventories'))
def delete(cls, symbol: str): """ DEL request - no json required """ symbol = symbol.upper() if stock := StockModel.find_by_symbol(symbol): # stock exist in DB return stock_schema.dump(stock) if stock.del_stock() \ else ({MESSAGE: ERROR_DEL_STOCK.format(symbol)}, HTTPStatus.CONFLICT)
def get(cls, symbol: str): """ GET request - no json required """ symbol = symbol.upper() if stock := StockModel.find_by_symbol(symbol): # stock exist in DB result = stock_schema.dump(stock) if positions_list := PositionsModel.find_by_symbol(symbol): positions_list_json = position_list_schema.dump(positions_list) result.update(positions_list_json)
def put(cls, symbol: str): """ PUT request - json required {symbol: symbol name, desc: description} """ symbol = symbol.upper() stock_json = request.get_json() stock_put = stock_schema.load(stock_json) if stock := StockModel.find_by_symbol(symbol): # stock is exist, then need to update symbol and desc return stock_schema.dump(stock) if stock.update_symbol_and_desc(stock_put['symbol'], stock_put['desc']) \ else ({MESSAGE: ERROR_UPDATE_STOCK.format(symbol)}, HTTPStatus.BAD_REQUEST)
def find_by_symbol(cls, symbol: str) -> Union[List["PositionsModel"], None]: """ find all positions for stock according to symbol :return if found, return list of positions for the stock, else None """ if stock := StockModel.find_by_symbol(symbol): # if stock exist, get all positions according to stock id return cls.query.filter_by(stock_id=stock.id).order_by( PositionsModel.position_date ).all( ) # SQLAlchemy -> SELECT * FROM position WHERE stock_id=stock_id
def get(cls): try: return { 'Stock': stock_list_schema.dump(StockModel.find_all()) }, 200 except Exception as e: return {'msg': str(e)}, 500
def post(cls): try: user_id = get_jwt_identity() user = UserModel.find_by_user_id(user_id) cards = CardsModel.find_all() for card in cards: if card.category == 'Refill': current_time = arrow.utcnow().to('Asia/Kolkata') if current_time.timestamp < user.get_date_time( card.data['date_time']): return {'msg': "Still not time to refill"}, 200 else: try: stock_card = StockModel.find_by_item( item=card.data['item']) stock_card.count = stock_card.count + card.data[ 'count'] stock_card.save_to_data() card.delete_from_data() return { 'msg': 'Item {} has been refilled'.format( stock_card.item) }, 200 except: return { 'msg': "Item you want to refill does not exist in your stock" }, 200 except Exception as e: return {'msg': str(e)}, 500
def delete(self, name): stock = StockModel.find_by_name(name) if stock: item.delete_from_db() return {'message': 'Stock deleted'}
def get(cls, item): try: stock = StockModel.find_by_item(item) if stock: return stock_schema.dump(stock), 200 return {'msg': "No such item exists"}, 404 except Exception as e: return {'msg': str(e)}, 500
def save_details(self, symbol: str) -> bool: """ insert position details for a stock """ if stock := StockModel.find_by_symbol(symbol): # stock is in DB, then add position and update stock quantity and cost try: self.stock_id = stock.id db.session.add(self) # calc by adding unit_cost and quantity to existing stock.calc_unit_cost_and_quantity(self.unit_cost, self.quantity, commit_flag=False) db.session.commit() return True except: db.session.rollback() logging.error(f'failed to save details {self=}, {symbol=}') return False
def post(cls, symbol: str): """ POST request - json required {desc: description} """ symbol = symbol.upper() stock_json = request.get_json() new_stock = stock_schema.load(stock_json, partial=(SYMBOL, )) new_stock[SYMBOL] = symbol stock = StockModel(**new_stock) if stock.save_details(): # stock created in DB return stock_schema.dump(stock), HTTPStatus.CREATED else: return { MESSAGE: STOCK_EXIST.format(symbol) }, HTTPStatus.BAD_REQUEST
def delete(cls, item): try: stock = StockModel.find_by_item(item) if stock: stock.delete_from_data() return {'msg': "Item has been deleted"}, 200 return {'msg': "No such item exists"}, 404 except Exception as e: return {'msg': str(e)}, 500
def add_stock(inv_id): if request.method == 'POST': quantity = request.form['quantity'] new_stock = StockModel(inv_id=inv_id, quantity=quantity) db.session.add(new_stock) db.session.commit() print("Stock added to inventory") return redirect(url_for('inventories'))
def patch(self, date): maxDate = datetime.datetime.strptime( StockModel.get_max_date(), '%Y%m%d') response = requests.get( 'http://www.twse.com.tw/zh/exchangeReport' '/STOCK_DAY?response=html&date=' + date + "&stockNo=0050") html = etree.HTML(response.content) stockList = [] for item in html.xpath('/html/body/div/table/tbody/tr'): # item[0].text->日期 # item[3].text->開盤價 # item[4].text->最高價 # item[5].text->最低價 # item[6].text->收盤價 # item[7].text->漲跌價差 # item[1].text->成交股數 # item[2].text->成交金額 # 日期民國轉西元 year = int(item[0].text.split('/')[0]) + 1911 month = int(item[0].text.split('/')[1]) day = int(item[0].text.split('/')[2]) itemDate = datetime.datetime(year, month, day) if (maxDate < itemDate): # print(item[1].text, item[2].text, item[3].text, # item[4].text, item[5].text, item[6].text, item[7].text) stockList.append( StockModel(itemDate.strftime('%Y%m%d'), '0050', float(item[3].text.replace('X', '')), float(item[4].text.replace('X', '')), float(item[5].text.replace('X', '')), float(item[6].text.replace('X', '')), float(item[7].text.replace('X', '')), round(int(item[1].text.replace(',', '')) / 1000), round(int(item[2].text.replace(',', '')) / 1000))) if (len(stockList) > 0): stockList = sorted(stockList, key=lambda s: s.date) StockModel.save_list_to_db(stockList) return {'message': 'patch stock success', 'stocks': list(item.json() for item in stockList)}, 200
def post(cls): try: user_id = get_jwt_identity() body = request.get_json() stock = stock_schema.load(body) stock.added_by = user_id if StockModel.find_by_item(stock.item): return {'msg': "Item already exists"}, 404 stock.save_to_data() return {'msg': "Item was added to stock database"}, 200 except Exception as e: return {'msg': str(e)}, 500
def post(self, name): data = Stock.parser.parse_args() # not getting the name correctly from the url name = data["name"] print(f'Looking for ticker: {name}') if StockModel.find_by_name(name): return {'message': f'A stock with name {name} already exists'}, 400 # data = Stock.parser.parse_args() # date = data['date'] # open_price = data["open_price"] # close = data["open_price"] # volume = data["volume"] outcomes = get_stock_data(name) print(outcomes[0]) for outcome in outcomes: # print(outcome) name = outcome['name'] date = outcome['date'] open_price = outcome['open_price'] close = outcome['close'] volume = outcome['volume'] stock = StockModel(name=name, date=date, open_price=open_price, close=close, volume=volume) try: stock.save_to_db() except: raise return { 'message': 'an error occurred inserting the hand.' }, 500 # print(f'{name}:{date}:{open_price}:{close}{volume}') try: stock.save_to_db() except: #raise return {'message': 'an error occurred inserting the stock.'}, 500 #return stock.json(), 201 return redirect("/", code=302)
def getOneSymbol(symbol, like): symbol = symbol.upper() stock = StockModel.find_by_symbol(symbol) if not stock: stock = StockModel(symbol=symbol) if like and (like == "true" or like == "True" or like == True): stock.addLike() stock.save_to_db() price = getPrice(symbol) return { "stockData": { "stock": symbol, "price": price, "likes": stock.likes } }
def put(self, name): data = Stock.parser.parse_args() # not getting the name correctly from the url name = data["name"] stock = StockModel.find_by_name(name) # StockModel.insert(stock) if stock: # update attributes stock.date = data['date'] stock.open_price = data["open_price"] stock.volume = data["volume"] else: stock = StockModel(name=name, date=date, open_price=open_price, close=close, volume=volume) stock.save_to_db() return stock.json()
def getTwoSymbols(symbols, like): symbolOne, symbolTwo, *other = symbols symbolOne = symbolOne.upper() symbolTwo = symbolTwo.upper() stockOne = StockModel.find_by_symbol(symbolOne) if not stockOne: stockOne = StockModel(symbol=symbolOne) stockTwo = StockModel.find_by_symbol(symbolTwo) if not stockTwo: stockTwo = StockModel(symbol=symbolTwo) if like and (like == "true" or like == "True" or like == True): stockOne.addLike() stockTwo.addLike() stockOne.save_to_db() stockTwo.save_to_db() priceOne = getPrice(symbolOne) priceTwo = getPrice(symbolTwo) return { "stockData": [ { "stock": symbolOne, "price": priceOne, "rel_likes": stockOne.likes - stockTwo.likes, }, { "stock": symbolTwo, "price": priceTwo, "rel_likes": stockTwo.likes - stockOne.likes, }, ] }
def get(self, date): return {'message': 'get stock success', 'stocks': list(item.json() for item in StockModel.get_by_date(date))}, 200
def get(self): stock = [x.json() for x in StockModel.find_all()] return {'stock':stock}
def get(self, name): stock = StockModel.find_by_name(name) if stock: return stock.json() return {'message': 'Stock not found'}, 404
S_INPUT = 23 R_INPUT = 4 L2CONSTANT = 100 EPOCHS = 1000 PRETRAINED = False device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') data = Dataloader() train, val, test, length = data.get_iterator(BATCHSIZE) newsEnc = NewsEncoder(length, EMBEDDING, HIDDEN, DROPOUT) stockEnc = StockEncoder(S_INPUT, HIDDEN) outRegressor = OutputRegressor(R_INPUT, HIDDEN) stockPredictor = StockModel(newsEnc, stockEnc, outRegressor, device).to(device) optimizer = torch.optim.Adam(stockPredictor.parameters(), weight_decay=L2CONSTANT) criterion = nn.MSELoss() train_start = time.time() trainer = learnParamter(stockPredictor, criterion, optimizer, PRETRAINED) train_loss, val_loss = trainer.train(train, val, EPOCHS) train_end = time.time() trainTime = (train_end - train_start) print( f'\n Total training time ==> [{time.strftime("%H:%M:%S",time.gmtime(trainTime))}] \n' )
def put(cls, symbol: str): """ PUT request - json required {symbol: symbol name, desc: description} """ symbol = symbol.upper() stock_json = request.get_json() stock_put = stock_schema.load(stock_json) if stock := StockModel.find_by_symbol(symbol): # stock is exist, then need to update symbol and desc return stock_schema.dump(stock) if stock.update_symbol_and_desc(stock_put['symbol'], stock_put['desc']) \ else ({MESSAGE: ERROR_UPDATE_STOCK.format(symbol)}, HTTPStatus.BAD_REQUEST) else: # stock not found, then create new one new_stock = stock_schema.load(stock_json) stock = StockModel(**new_stock) return stock_schema.dump(stock) if stock.save_details() \ else ({MESSAGE: ERROR_SAVE_STOCK.format(symbol)}, HTTPStatus.BAD_REQUEST) @classmethod def delete(cls, symbol: str): """ DEL request - no json required """ symbol = symbol.upper() if stock := StockModel.find_by_symbol(symbol): # stock exist in DB return stock_schema.dump(stock) if stock.del_stock() \ else ({MESSAGE: ERROR_DEL_STOCK.format(symbol)}, HTTPStatus.CONFLICT) else: return {