def portfolio_add_stock(request, portfolio_id, portfolio, symbol, stock): if stock is None: stock = Stock(yahoo_symbol=symbol) stock.save() portfolio.stocks.add(stock) portfolio.save() return HttpResponse('')
def update_symbols(): """ update the symbol list calling myinvestorshub.com """ from finance_game.models import Stock def get_countries(): url = "http://www.myinvestorshub.com/yahoo_stock_list.php" countries_html = urllib2.urlopen(url).read() index_root = lxml.html.fromstring(countries_html) for country in index_root.cssselect("option"): yield country.text symbol_url_base = "http://www.myinvestorshub.com/yahoo_list.php" for country in get_countries(): if country == "United Kingdom": data = urllib.urlencode({"cnt": country}) binary_data = data.encode('utf-8') request = urllib2.Request(symbol_url_base, binary_data) response = urllib2.urlopen(request) index_root = lxml.html.fromstring(response.read().decode('utf-8')) table = index_root.cssselect("table")[3] stock_rows = table.cssselect("tr") for stock_row in stock_rows[1:]: _, company_name, symbol, exchange, country = list(map(lambda s: s.text, stock_row.cssselect("td"))) if company_name and symbol and exchange and country: print(company_name, symbol, exchange, country) stock = Stock(name=company_name, symbol=symbol, exchange=exchange, country=country) # stock.update_values() stock.save()
def _update_stocks(symbols): """ Update models.Stock entities. :param symbols: Iterable of stock symbols to update. :return: dict mapping symbols to new prices, dict mapping symbols to (old price, new price) for changed symbols. """ to_put = [] symbol_price_updated_dict = {} if symbols is None: stocks_ = list(Stock.query()) symbols = [s.key.id() for s in stocks_] else: stocks_ = [Stock.get_by_id(s) for s in symbols] symbol_price_dict = stocks.get_stock_prices(symbols) for stock in stocks_: if stock is None: continue symbol = stock.key.id() price = symbol_price_dict.get(symbol, None) if stock.price != price: symbol_price_updated_dict[symbol] = (stock.price, price) stock.price = price to_put.append(stock) ndb.put_multi(to_put) return symbol_price_dict, symbol_price_updated_dict
def agregar_stock(detalle, almacen): if existe_stock(detalle.producto, almacen): stock = Stock.objects.get(producto = detalle.producto, en_almacen = almacen) stock.unidades = stock.unidades + detalle.cantidad stock.save() else: stock = Stock(producto = detalle.producto, en_almacen = almacen, unidades = detalle.cantidad) stock.save()
def remove(id): try: #user.remove({'stock':ticker}) stock = Stock(id=id) sym = stock['symbol'] stock.delete() return render_template('remove.html', ticker=sym) except: return render_template('uhoh.html')
def BeginToTrade(request): RequestUser = request.user RequestGroup = RequestUser.group context={ "form":SearchForm(), "sear":True } if request.method=="POST": Post = request.POST.dict() if Post.has_key("StockName"): StockName=str(Post["StockName"]) else: StockName="" if Post.has_key("Volume"): Volume=Post["Volume"] else: Volume=0 if Post.has_key("TransactionType"): TransactionType=Post["TransactionType"] else: TransactionType=None print Post context={ "form":OrderForm(), "sear":False } stock = Stock.objects.filter(StockName=StockName) if len(stock)==0: print "123123" stock = Stock(StockName=StockName) stock.save() context["StockData"] = jsonpickle.encode(stock.Get_data()) else: context["StockData"] = jsonpickle.encode(stock[0].Get_data()) if Volume!="" and TransactionType != None: RequestUser.group.UpdateAcount() stockprice = stock[0].Get_Price() if TransactionType=="buy": if RequestUser.group.Cash >= stockprice*float(Volume): RequestGroup.transaction_set.create(TransType = TransactionType,StockOfTrans = stock[0], Volume=Volume, PriceAtTrans=stock[0].Get_Price() ) context["mess"] = "Succesfully making transaction" else: context["mess"] = "You don't have enough money" else: asset = RequestUser.group.AllAsset if asset[StockName] >= float(Volume): RequestGroup.transaction_set.create(TransType = TransactionType,StockOfTrans = stock[0], Volume=Volume, PriceAtTrans=stock[0].Get_Price() ) context["mess"] = "Succesfully making transaction" else: context["mess"] = "You don't have enough this stock to sell" return render(request, "BeginToTrade.html", context)
def get_all_stocks(name=None): search_name = request.args.get('name') if search_name: stock = Stock.find_one({'name': search_name}, test_mode=app.testing) return jsonify(stock=stock) industry = request.args.get('industry') if industry: stocks = Stock.find({'industry': industry}, test_mode=app.testing) return jsonify(stocks=stocks) # Get all stocks stocks = Stock.find_all(test_mode=app.testing) return jsonify(stocks=stocks['stocks'])
def stock(): if not account.user_is_logged_in(): return redirect(url_for("login")) ticker = request.args.get("ticker", "AAPL") # TODO: no ticker is error... # Find the stock. stock = Stock.get_stock_from_db(ticker) # Check for errors. if stock == -1: N_STOCKS = 20 # number of stocks to retrieve tickers = Stock.get_all_tickers() stocks = Stock.get_stocks(N_STOCKS, True) # default: list of stocks by alpha order return render_template("home.html", error="No ticker matching that name could be found.", tickers = tickers, stocks = stocks, metric = "alpha", order = True, has_recs = account.user_has_recommendations()) # Get the prices with corresponding dates. # Produce formatted date strings to paste into HTML. price_time_series = Stock.get_time_series(ticker, 7) price_dates = price_time_series.keys() price_dates.sort() price_dates_str = [] price_values = [] for curr_date in price_dates: price_values.append(price_time_series[curr_date]) price_dates_str.append(curr_date.strftime("%m-%d")) # Compute price change now-- consistent with time series data! price_change = price_values[-1] - price_values[-2] # Put a blurb in the stock page if it is recommended. stock_is_recommended = False if account.user_has_recommendations(): if stock.ticker in Stock.recommended_tickers: stock_is_recommended = True return render_template("stock.html", ticker = stock.ticker, name = stock.name, latest_price = stock.cur_price, pe_ratio = stock.pe, market_cap = stock.cap, dividends = stock.dividends, beta = stock.beta, sustainability = stock.sustainability, socialgood = stock.socialgood, american = stock.american, price_change = price_change, price_series_dates = price_dates_str, price_series_values = price_values, recommended = stock_is_recommended)
def test_create_stock(self): """Make sure it create a stock.""" Category.create(category_id='001', description='Testing Stock') create_stock('001', 'Testing stock', 1, '001', 9.99) s = Stock.select().where(Stock.stock_id == '001') t = Stock.delete().where(Stock.stock_id == '001') t.execute() t = Category.delete().where(Category.category_id == '001') t.execute() self.assertEqual(str(s), ("<class 'models.Stock'> SELECT `t1`.`id`," " `t1`.`stock_id`, `t1`.`description`," " `t1`.`quantity`, `t1`.`category_id`," " `t1`.`price` FROM `stock` AS t1" " WHERE (`t1`.`stock_id` = %s) ['001']"))
def test_create_outgoing(self): """Create an outgoing record.""" Category.create(category_id='001', description='Testing Stock') Project.create(project_id='001', project_description="Testing") Role.create(role_name='Admin') User.create(first_name='Jay', second_name='Palm', phone='9783978223', role='Admin', username='******', password='******', email='*****@*****.**') create_stock('001', 'Testing stock', 1, '001', 9.99) create_outgoing_stock(stock='001', project_id='001', date="2015-07-22", quantity='7', username='******') OutgoingStock.get(OutgoingStock.stock == '001').delete_instance() Stock.get(Stock.category == '001').delete_instance() User.get(User.username == 'JayPalm').delete_instance() Role.get(Role.role_name == 'Admin').delete_instance() Project.get(Project.project_id == '001').delete_instance() Category.get(Category.category_id == '001').delete_instance()
def show_stock(request, symbol): stks = Stock.objects.filter(symbol=symbol) if stks.count() == 0: stk = Stock(symbol=symbol, price=0.0) stk.save() elif stks.count() == 1: stk = stks[0] else: return HttpResponse("%s" % stks.count()) try: ss = stk.history.order_by('date')[0] except: update(stk) ss = stk.history.order_by('date')[0] return render_to_response('stock.html', {'stock': stk, 'status': ss})
def add_existing_stock(pk_id, to_add): """Increase quantity for a specified record by pk_id. pk_id: primary key id """ stock = Stock.get( Stock.id == pk_id ) current_quantity = stock.quantity new_quantity = current_quantity + to_add query = Stock.update( quantity=new_quantity ).where( Stock.id == pk_id ) return query.execute()
def _process_removed_stocks(sheet, ssheet_id, symbols): """ Update database to reflect sheet's new stocks, changed bounds, or changed order. :param sheet: Instance of models.Sheet to modify. :param ssheet_id: Spreadsheet id. :param symbols: Iterable of symbols. :return: list of ndb Entities to put, list of ndb Entities to delete. """ to_put, to_delete = [], [] symbols_old = {k.id() for k in sheet.stock_keys} for symbol in symbols_old - set(symbols): stock = Stock.get_by_id(symbol) sheetstock_key = ndb.Key('SheetStock', '_'.join([ssheet_id, symbol])) to_delete.append(sheetstock_key) if stock and sheet.key in stock.sheet_keys: stock.sheet_keys.remove(sheet.key) if stock.sheet_keys: to_put.append(stock) else: to_delete.append(stock.key) return to_put, to_delete
def test_fuzzy_text_search_industry_name(self): stocks = Stock.find({'industry': 'consumer'}, test_mode=True) stock = stocks[0] self._assert_first_stock(stock) stock_2 = stocks[1] self._assert_second_stock(stock_2)
def show_stock(): stock = request.args.get('ticker') value = request.args.get('value') unit = request.args.get('unit') stock = Stock(stock) if stock.data is not None: stock.calc_all() format_data = stock.data.reset_index() # DateTimeIndex to column format_data = format_data.to_json(date_format='epoch', orient='records') # Markup tells jinja2 that the object is safe for rendering, without # escaping the quotes (caused problems when creating JSON object). format_data = Markup(format_data) # need to redirect instead return render_template('chart.html', stock=stock, data=format_data) else: error = stock.ticker + " is an invalid ticker symbol." return render_template('index.html', error = error)
def test_create_incoming(self): """Create an incoming record.""" Category.create(category_id='001', description='Testing Stock') create_stock('001', 'Testing stock', 1, '001', 9.99) create_incoming_stock(stock="001", date="2015-07-22", quantity=13, price=13.99) p = IncomingStock.select().where(IncomingStock.stock == '001') q = IncomingStock.delete().where(IncomingStock.stock == '001') q.execute() s = Stock.select().where(Stock.stock_id == '001') t = Stock.delete().where(Stock.stock_id == '001') t.execute() t = Category.delete().where(Category.category_id == '001') t.execute() self.assertEqual(str(p), ("<class 'models.IncomingStock'> SELECT `t1`.`id`, `t1`.`stock_id`, " "`t1`.`date`, `t1`.`price`, `t1`.`cost` FROM `incomingstock` AS t1 WHERE " "(`t1`.`stock_id` = %s) ['001']"))
async def create_stock(stock_request: StockRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db)): """ add one or more tickers to the database background task to use yfinance and load key statistics """ stock = Stock() stock.symbol = stock_request.symbol db.add(stock) db.commit() background_tasks.add_task(fetch_stock_data, stock.id) return {"code": "success", "message": "stock was added to the database"}
def test_find_all_stocks(self): stocks = Stock.find_all(test_mode=True) stocks = stocks['stocks'] stock_1 = stocks[0] self._assert_first_stock(stock_1) stock_2 = stocks[1] self._assert_second_stock(stock_2)
def stock_add(request): from app.remote.stocks import StockHistoryClient from app.forms import StockWizardForm from app.models import Company, Stock if request.method == "POST": form = StockWizardForm(request.POST) pprint(form.is_valid()) if form.is_valid(): # save company = Company() company.name = form.cleaned_data['company_name'] company.country = form.cleaned_data['company_country'] company.save() stock = Stock() stock.company = company stock.name = form.cleaned_data['name'] stock.wkn = form.cleaned_data['wkn'] stock.isin = form.cleaned_data['isin'] stock.symbol = form.cleaned_data['symbol'] stock.type = form.cleaned_data['type'] stock.default_stock_exchange = form.cleaned_data['default_stock_exchange'] stock.save() return HttpResponseRedirect(reverse('stock', args=(stock.symbol,))) else: pprint(form.errors) else: data = None if 'wkn_or_isin' in request.GET: shc = StockHistoryClient() data = shc.get_basics_by_wkn_or_isin(wkn_or_isin=request.GET['wkn_or_isin']) data['company_country'] = data['country'] data['company_name'] = data['name'] form = StockWizardForm(initial=data) return render_to_response( 'stock_wizard_add.html', { 'form': form }, context_instance=RequestContext(request) )
def get_user_info(): user_id = request.args.get('user_id', None) user = User.get_by_id(user_id) user_infos = { "funds" : user.funds, "user_stock_infos" : Stock.get_stocks_infos_by_user_id(user_id=user.id), "user_id":user_id } return jsonify(user_infos), 200, DEFAULT_HEADERS
async def create_stock(stock_request: StockRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db)): """ created a stock and stores it in the databse if exist bg_task need async keyword """ # Pydantic, Dependency Injection, and Background Tasks stock = Stock() stock.symbol = stock_request.symbol db.add(stock) db.commit() # background here background_tasks.add_task(fetch_stock_data, stock.id) return {"code": "success", "message": "shit"}
def find_stocks_with_possible_filters(filters, user): query = Stock.queryNotSoftDeleted() if 'offererId' in filters: query = query.filter( Stock.offererId == dehumanize(filters['offererId'])) _check_offerer_user(query.first_or_404().offerer.query, user) if 'hasPrice' in filters and filters['hasPrice'].lower() == 'true': query = query.filter(Stock.price != None) return query
def get_stocks_in_day(stock_name, day): out = [] markets = Market.all(keys_only=False).filter("date =", day).filter("ref =", stock_name.market_ref).order('time').fetch(100) for market in markets: stock = Stock.all().filter("market =", market.key()).filter('name = ', stock_name.key()).get() if not stock is None: dt = datetime.combine(market.date, market.time) out.append((dt, stock, market.exchange_rate)) return out
def add(ticker): print('add XF') try: stock = Stock() stock['name'] = ticker stock['symbol'] = ticker try: stock['last_price'] = float(stocks.get_quote(ticker)) except: print("lookup failed for %s" % ticker) print('presave') try: stock.save() except: print('stock failed to save') print("Created %s Successfully" % stock['name']) return render_template('add.html', ticker=ticker) except: return render_template('uhoh.html')
async def create_stock(stock_request: StockRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db)): """creates a stock and stores it in the database Returns: [type]: [description] """ stock = Stock() stock.symbol = stock_request.symbol db.add(stock) db.commit() background_tasks.add_task(fetch_stock_data, stock.id) return { "code": "success", "message": "stock created", }
def setUp(self): """create test client, add sample data""" s = Stock(stock_symbol="AAPL", stock_name="Apple") p = Peer(lead_stock_symbol=s.stock_symbol, peer_stock_symbol='MSFT') p.id = 9876 db.session.add_all([s, p]) db.session.commit() self.p = p
def get_stocks_days(stock_name, num_days=10): days = last_weekdays(num_days) out = [] for day in days: market = Market.all(keys_only=False).filter("date =", day.date()).filter("ref =", stock_name.market_ref).order('-time').get() if not market is None: stock = Stock.all().filter("market =", market.key()).filter('name = ', stock_name.key()).get() if not stock is None: out.append((day, stock, market.exchange_rate)) return out
def get_market_stocks(client): payload = client.get_market_stocks().payload stocks_usd = [ stock for stock in payload.instruments[:] if stock.currency == 'USD' ] stocks = { s.ticker: Stock(ticker=s.ticker, isin=s.isin) for s in stocks_usd } return stocks
async def create_stock(stock_request: StockRequest, background_tasks: BackgroundTasks, db: SessionLocal = Depends(get_db)): """ Create new stock entry and store it in database. Run background task in queue to update db entry with fetched stock details :return: """ # Instantiate model with input data stock = Stock() stock.symbol = stock_request.symbol # Save to db db.add(stock) db.commit() background_tasks.add_task(fetch_stock_data, stock.id) return {"code": "success", "message": "Stock was added to database"}
def api_save_trade_record(request, *, type, occur_date, occur_amount, balance, **kw): if not type or not type.strip(): raise APIValueError('type', 'type cannot be empty.') if not occur_amount or not occur_amount.strip(): raise APIValueError('occur_amount', 'occur_amount cannot be empty') if 'charge_fee' in kw: charge_fee = kw['charge_fee'] else: charge_fee = 0 if 'stamp_tax' in kw: stamp_tax = kw['stamp_tax'] else: stamp_tax = 0 if 'transfer_fee' in kw: transfer_fee = kw['transfer_fee'] else: transfer_fee = 0 if 'commission' in kw: commission = kw['commission'] else: commission = 0 if 'stock_balance' in kw: stock_balance = kw['stock_balance'] else: stock_balance = 0 if 'stock_code' in kw: stock_code = kw['stock_code'] else: stock_code = '' if 'deal_num' in kw: deal_num = kw['deal_num'] else: deal_num = 0 if 'deal_price' in kw: deal_price = kw['deal_price'] else: deal_price = 0 stock = Stock(type=type.strip(), occur_date=occur_date, occur_amount=occur_amount, balance=balance, stock_balance=stock_balance, stock_code=stock_code, deal_num=deal_num, deal_price=deal_price, stamp_tax=stamp_tax, transfer_fee=transfer_fee, commission=commission, charge_fee=charge_fee) yield from stock.save() return stock
def send_advanced_details(): """returns JSON with advanced company details""" stock_symbol = request.json.get('stock_symbol') # 404 should not be an issue if gotten to this stage returned_stock_details = Stock.query.get_or_404(stock_symbol) # sends request to API & adds to database returned_fin = Stock.add_basic_financial(stock_symbol) returned_rec = Stock.add_rec_trend(stock_symbol) returned_target = Stock.add_target(stock_symbol) returned_peer = Stock.add_peers(stock_symbol) # gets updated stock object returned_stock_details = Stock.query.get_or_404(stock_symbol) # creates a list containing each peers symbol (peers is a realted SQL object) peers = [peer.peer_stock_symbol for peer in returned_stock_details.peers] return jsonify(stock=returned_stock_details.serialize_advanced_stock_details(), peers=peers)
def test_returns_humanized_ids_for_foreign_keys(self, app): # given user = create_user(postal_code=None, idx=12) booking = create_booking(user, Stock(), idx=13) booking.userId = user.id # when dict_result = as_dict(booking, includes=[]) # then assert dict_result['userId'] == 'BQ'
def update_or_add_stock(equity, field, data): equity = equity.upper() existing_stock = db.session.query(Stock).filter( Stock.equity == equity).first() if existing_stock is None: if field == 'info': stock = Stock(equity=equity, info=data) elif field == 'history': stock = Stock(equity=equity, history=data) elif field == 'history_alpha': stock = Stock(equity=equity, history_alpha=data) db.session.add(stock) else: if field == 'info': existing_stock.info = data elif field == 'history': existing_stock.history = data elif field == 'history_alpha': existing_stock.history_alpha = data db.session.commit()
def create_stock(stock_request: StockRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db)): """ Created a stock and store it in the database """ stock = db.query(Stock).filter( Stock.symbol == stock_request.symbol).first() if not stock: stock = Stock() stock.symbol = stock_request.symbol db.add(stock) db.commit() background_tasks.add_task(fetch_stock_data, stock.id) return { "code": "success", "message": "stock created successfully", }
def get_stocks(): stocks = [ { 'id': stock.id, 'brand': stock.brand, 'price': stock.price } for stock in Stock.all() ] return jsonify(stocks), 200, DEFAULT_HEADERS
def test_create_stock_no_duplicate(self): """Makes sure stock don't have the same stock_id when creating.""" Category.create(category_id='001', description='Testing Stock') create_stock('001', 'Testing stock', 1, '001', 9.99) from peewee import IntegrityError with self.assertRaises(IntegrityError): create_stock('001', 'Testing stock', 1, '001', 9.99) q = Stock.delete().where(Stock.stock_id == '001') q.execute() t = Category.delete().where(Category.category_id == '001') t.execute()
def test_raises_resource_gone_error_if_is_used(self): # Given booking = Booking() booking.isUsed = True booking.stock = Stock() # When with pytest.raises(ResourceGoneError) as e: check_booking_is_usable(booking) assert e.value.errors['booking'] == [ 'Cette réservation a déjà été validée']
def test_is_countermak_validated_label_when_booking_is_used(self): # Given booking = Booking() booking.stock = Stock() booking.isUsed = True # When statusLabel = booking.statusLabel # Then assert statusLabel == 'Contremarque validée'
def get_all(): try: df = pd.DataFrame(ts.get_today_all()) j_datas = json.loads(df.to_json(orient='records')) stocks = [] from models import Stock for j_data in j_datas: stocks.append(Stock(j_data)) return stocks except IOError: pass
def add_stock(): body = request.get_json() for ingreTemp in body: stock1 = Stock(id_profile=ingreTemp["id_profile"], id_ingrediente=ingreTemp["id_ingrediente"], quantity=ingreTemp["quantity"]) db.session.add(stock1) db.session.commit() return "ok", 200
def test_validated_label_when_event_is_expired(self): # Given booking = Booking() booking.stock = Stock() booking.stock.beginningDatetime = datetime.utcnow() + timedelta(-1) # When statusLabel = booking.statusLabel # Then assert statusLabel == 'Validé'
def test_is_cancelled_label_when_booking_is_cancelled(self): # Given booking = Booking() booking.stock = Stock() booking.isCancelled = True # When statusLabel = booking.statusLabel # Then assert statusLabel == "Réservation annulée"
def post(self): status = 200; if validationUtil.is_json(request.data): args = self.reqparse.parse_args(strict=True, custom=True) if args['error']: genericError = GenericError(0, list(args['body'].values())) res = genericError.__dict__ else: name = request.json['name'] description = request.json['description'] errors = [] if not name: errors.append('Name is empty') if not description: errors.append('Description is empty') if len(errors) <= 0: session = Session() newStock = Stock(request.json['name'], request.json['description']) session.add(newStock) session.flush() res = newStock._asdict() session.commit() session.close() else: genericError = GenericError(0, errors) res = genericError.__dict__ status = 400 else: errors.append('Not a valid JSON format') res = GenericError(0, errors).__dict__ status = 400 return res, status
async def create_stock( stock_request: StockRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db), ): """ Creates a stock and stores in database. """ # Instantiate our Stock model stock = Stock() # Our database model has 'symbol'. And our request has 'symbol' stock.symbol = stock_request.symbol # Add this object to our database session and commit to database db.add(stock) db.commit() # Kick off a single background task after inserting to database background_tasks.add_task(fetch_stock_data, stock.id) return {"code": "success", "message": "stock was added to the database"}
def test_booking_on_thing_is_cancellable(self): # Given booking = Booking() booking.stock = Stock() booking.stock.offer = Offer() booking.stock.offer.product = create_product_with_thing_type() # When is_cancellable = booking.isUserCancellable # Then assert is_cancellable == True
async def create_stock( stock_request: StockRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db), ): """Creates a stock and saves it in the database""" stock = Stock() stock.symbol = stock_request.symbol db.add(stock) db.commit() background_tasks.add_task(fetch_stock_data, stock.id) return { "code": "success", "message": "Stock added", "stock_id": stock.id, "stock_symbol": stock.symbol, }
def edit_stock(pk_id, stock_id, description, quantity, category, price): """Takes all stock arguments and save it in the selected stock record. (EDIT THE STOCK) pk_id: primary key id, or stock to be edited. The rest of the arguments are going to be the new data to the specified record. """ stock = Stock.update( stock_id=stock_id, description=description, quantity=quantity, category=category, price=price ).where( Stock.id == pk_id ) return stock.execute()
def create_stock_with_event_offer(offerer, venue, price=10, booking_email='*****@*****.**', available=10, is_soft_deleted=False, event_type=EventType.JEUX, name='Mains, sorts et papiers', offer_id=None, beginning_datetime=datetime.utcnow() + timedelta(hours=72), end_datetime=datetime.utcnow() + timedelta(hours=74), thumb_count=0, booking_limit_datetime=datetime.utcnow() + timedelta(hours=71)): stock = Stock() stock.offerer = offerer stock.price = price stock.available = available stock.beginningDatetime = beginning_datetime stock.endDatetime = end_datetime stock.bookingLimitDatetime = booking_limit_datetime stock.offer = create_offer_with_event_product(venue, event_name=name, event_type=event_type, booking_email=booking_email, is_national=False, thumb_count=thumb_count) stock.offer.id = offer_id stock.isSoftDeleted = is_soft_deleted return stock
def add_stock_for_user(db: Session, stock: StockCreate, email: str): stock.ticker = stock.ticker.upper() stock_obj = stockquotes.Stock(stock.ticker) current_price = stock_obj.current_price user_id = get_user_by_email(db, email).id db_stock = Stock(**stock.dict(), user_id=user_id, current_price=current_price) db.add(db_stock) db.commit() db.refresh(db_stock) return db_stock
def get_market(): #util.clean_market(0) url = 'http://pregao-online.bmfbovespa.com.br/Cotacoes.aspx' soup = BeautifulSoup(urlfetch.fetch(url, deadline=50).content, 'lxml') rate = util.get_exchange() #dt = get_datetime() dt = datetime.datetime.now(tz.tzstr('EBST3EBDT')) market = Market(ref=0, date=dt.date(), time=dt.time(), exchange_rate=rate) market.put() table = soup('table', attrs={'id': 'ctl00_DefaultContent_GrdCarteiraIndice'})[0] for tr in table('tr')[1:]: tds = tr('td') code = str(tds[0].string) name = util.clean_string(tds[1].string) value = util.get_float(tds[2].string) diff = util.get_float(tds[3].text.strip()) stock = Stock(name=util.get_or_create_name(0, code, name), value=value, diff=diff, market=market.key()) stock.put()
def buyer(): stocks = Stock.select().where(Stock.bought == False) stocks = [ {"id": json.dumps(str(stock.id)), "stock": stock} for stock in stocks ] # this will be used for adding listings to the homepage tags = [product.name for product in Product.select()] tags += [descriptor.description for descriptor in Descriptor.select()] tags += [brand.name for brand in Brand.select()] tags.sort() return render_template("buyer_dashboard.html", stocks=stocks, Order=Order, Stock=Stock, tags=tags, fn=fn)
def get_market(): #util.clean_market(1) #dt = get_datetime() dt = datetime.datetime.now(tz.tzstr('EST5EDT')) market = Market(ref=1, date=dt.date(), time=dt.time()) market.put() url = 'http://www.barchart.com/stocks/nasdaq100.php?view=main' soup = BeautifulSoup(urlfetch.fetch(url, deadline=30).content, 'lxml') table = soup('table', attrs={'id': 'dt1'})[0] for tr in table('tr')[1:]: tds = tr('td') code = str(tds[0].text) name = str(tds[1].text) value = float(tds[2].text.replace(',', '')) text_replace = tds[4].text.replace(',', '').replace('%', '') diff = float(text_replace) if text_replace != 'unch' else 0.0 stock = Stock(name=util.get_or_create_name(1, code, name), value=value, diff=diff, market=market.key()) stock.put()
def create_booking_for_event( amount=50, quantity=1, user=None, isCancelled=False, type=EventType.CINEMA, date_created=datetime.utcnow() ): product = Product(from_dict={'type': str(type)}) offer = Offer() stock = Stock() booking = Booking(from_dict={'amount': amount}) offer.product = product stock.offer = offer booking.stock = stock booking.quantity = quantity booking.user = user booking.isCancelled = isCancelled booking.token = random_token() booking.dateCreated = date_created return booking
def test_does_not_raise_api_error_when_user_cancellation_and_event_in_more_than_72h(self): # Given booking = Booking() booking.isUsed = False booking.stock = Stock() booking.stock.beginningDatetime = datetime.utcnow() + timedelta(hours=73) # When check_output = check_booking_is_cancellable(booking, is_user_cancellation=False) # Then assert check_output is None
def create_booking_for_thing( url=None, amount=50, quantity=1, user=None, is_cancelled=False, product_type=ThingType.JEUX, date_created=datetime.utcnow() ): product = Product(from_dict={'url': url, 'type': str(product_type)}) offer = Offer(from_dict={'type': str(product_type)}) stock = Stock() booking = Booking(from_dict={'amount': amount}) offer.product = product stock.offer = offer booking.stock = stock booking.quantity = quantity booking.user = user booking.isCancelled = is_cancelled booking.dateCreated = date_created return booking
async def create_stock(stock_request: StockRequest, background_tasks: BackgroundTasks, db: Session = Depends(get_db)): # this function depends on get_db """ Creates a sstock and stores it in the database """ # instantiate Stock class from model stock = Stock() # class stock symbol equals stock_request symbol stock.symbol = stock_request.symbol # db is SessionLocal which is like a cursor db.add(stock) db.commit() # id came from the just inserted stock above background_tasks.add_task(fetch_stock_data, stock.id) return {"code": "success", "message": "stock"}
def home(): N_STOCKS = 20 # number of stocks to retrieve if not account.user_is_logged_in(): return redirect(url_for("login")) # Get all stock tickers tickers = Stock.get_all_tickers() # Get default sorting metric and order order = None metric = request.args.get("metric", "recs") order_arg = request.args.get("order", "lowhigh") if order_arg == "lowhigh": order = True elif order_arg == "highlow": order = False # Get sorted stocks stocks = None if metric == "alpha": stocks = Stock.get_stocks(N_STOCKS, order) elif metric == "price": stocks = Stock.get_stocks_sorted_by_price(N_STOCKS, order) elif metric == "pe": stocks = Stock.get_stocks_sorted_by_pe(N_STOCKS, order) elif metric == "risk": stocks = Stock.get_stocks_sorted_by_risk(N_STOCKS, order) elif metric == "recs": stocks = Stock.get_recommendations() elif metric == "sustainability": stocks = Stock.get_stocks_sorted_by_sustainability(N_STOCKS, order) elif metric == "socialgood": stocks = Stock.get_stocks_sorted_by_socialgood(N_STOCKS, order) elif metric == "american": stocks = Stock.get_stocks_sorted_by_american(N_STOCKS, order) return render_template("home.html", tickers = tickers, stocks = stocks, metric = metric, order = order, has_recs = account.user_has_recommendations())
def _process_new_or_changed_stocks(lbs, ubs, sheet, ssheet_id, symbols): """ Update database to reflect sheet's new stocks, changed bounds, or changed order. :param lbs: Iterable of lower bounds for the stock price. :param ubs: Iterable of upper bounds for the stock price. :param sheet: Instance of models.Sheet to modify. :param ssheet_id: Spreadsheet id. :param symbols: Iterable of symbols. :return: list of stock keys, list of new prices, list of ndb Entities to put. """ to_put = [] stock_keys, prices = [], [] for symbol, lb, ub in zip(symbols, lbs, ubs): stock, put_stock = Stock.get_create_by_id(symbol) if stock.price is None: price = stocks.get_stock_prices(symbol).get(symbol) stock.price = price put_stock = True if sheet.key not in stock.sheet_keys: stock.sheet_keys.append(sheet.key) put_stock = True if put_stock: to_put.append(stock) stock_keys.append(stock.key) prices.append(stock.price) sheetstock, put_sheetstock = SheetStock.get_create_by_id(ssheet_id, symbol, bound_lower=lb, bound_upper=ub) put_sheetstock = _update_sheet_stock_bounds(sheetstock, lb, ub, changed=put_sheetstock) if put_sheetstock: to_put.append(sheetstock) return stock_keys, prices, to_put
def update(logger): db = get_db() user = db.user stocklist = Stock.objects() for stock in stocklist: price = stocks.get_quote(stock.symbol) logger.info("Got latest price for {0}:{1}".format( stock.symbol, price ) ) try: stock.last_price = price stock.update(**{"set__last_price":price}) logger.info("Updated data for {0}:{1}\n".format( stock['name'], stock['last_price'] ) ) except Exception as e: logger.error("Error upating stock {}\n".format(stock['name'])) logger.error(e.message)
def import_data(): snapshot = Snapshot() snapshot.snapshot = datetime.now() snapshot.save() print "Importing data from finviz" r = requests.get('http://finviz.com/export.ashx?v=152', cookies={"screenerUrl": "screener.ashx?v=152&f=cap_smallover&ft=4", "customTable": "0,1,2,6,7,10,11,13,14,45,65"}) data = csv_to_dicts(r.text) tickers = [] for row in data: try: stock = Stock() stock.snapshot = snapshot if row["Ticker"]: stock.Ticker = row["Ticker"] print stock.Ticker tickers.append(stock.Ticker) if "Importing " + row["Company"]: stock.Company = row["Company"] if row["Market Cap"]: stock.MarketCap = row["Market Cap"] if row["P/E"]: stock.PE = row["P/E"] if row["P/S"]: stock.PS = row["P/S"] if row["P/B"]: stock.PB = row["P/B"] if row["P/Free Cash Flow"]: stock.PFreeCashFlow = row["P/Free Cash Flow"] if row["Dividend Yield"]: stock.DividendYield = row["Dividend Yield"][:-1] if row["Performance (Half Year)"]: stock.PerformanceHalfYear = row["Performance (Half Year)"][:-1] if row["Price"]: stock.Price = row["Price"] stock.save() except: pdb.set_trace() import_evebitda(snapshot) import_buyback_yield(snapshot)