def generate_game(**kwargs): default_params = { "machine_name": "foo", "human_name": "bar", "full_price": model.Price(**{ "price": 12.00, "currency": "GBP" }), "current_price": model.Price(**{ "price": 12.00, "currency": "GBP" }), "os": ["linux", "windows"], "platform": ["download"] } default_params.update(kwargs) return model.Game(**default_params)
def calc_percent_change_compare(compare_ticker, session): """ This function calculates the percent change since inception for only the comparison ticker and saves that value to the new_change column in the database. All values are being benchmarked against 4/10/2007, which is the latest inception date for all of the funds for apples-to-apples since-inception comparison. EXCEPTION: if the comparison ticker has an inception date after 4/10/2007, I am using the inception date. Comparison validity is no longer applicable, but it at least allows the user to see the data. """ beginning = time.time() compare_ticker = model.session.query( model.Ticker).filter_by(symbol=compare_ticker).first() ticker = compare_ticker.price # This methodology needs improvement- some stocks have an inception # date after 4/10/2007, so I created blank lines of data to be # added to the database for the difference in days between 4/10/2007 # and the stock's inception date. I could not increment through dates, # because the API data does not include weekends. Therefore, I am # modelling the dates after ticker_id 1. standard_date = datetime.strptime("2007-04-10", "%Y-%m-%d").date() old_date = ticker[-1].date find_old_date_id = m_session.query(model.Price).filter_by( date=old_date, ticker_id=1).first().id find_standard_date_id = m_session.query(model.Price).filter_by( date=standard_date, ticker_id=1).first().id number_of_blanks = find_standard_date_id - find_old_date_id incrementing_date = 0 while incrementing_date < number_of_blanks: incrementing_date = incrementing_date + 1 dummy_id = find_old_date_id + incrementing_date find_dummy_date = m_session.query( model.Price).filter_by(id=dummy_id).first().date add_dummy_price = model.Price(ticker_id=compare_ticker.id, date=find_dummy_date, close_price=0) session.add(add_dummy_price) session.commit() new_index = 0 old_close_price = float( m_session.query(model.Price).filter_by( date=ticker[-1].date, ticker_id=compare_ticker.id).first().close_price) old_date = ticker[-1].date while ticker[new_index].date > old_date: new_close_price = float(ticker[new_index].close_price) difference = round( (new_close_price - old_close_price) / old_close_price, 4) ticker[new_index].percent_change = difference new_index = new_index + 1 session.commit()
def add_item(): ''' Adds a new item to the database. Body: {"name", "upc", "price", "user", "store", "lat", "long"[, "image", "image_url"]} Response: - {"success": true or false}, - {"error": error description} ''' data = request.get_json(force=True) required_fields = ['name', 'upc', 'price', 'user', 'store', 'lat', 'long'] if not validation.has_required(data, required_fields): return json.dumps({'success': False, 'error': Error.MISSING_FIELDS.value}) if not validation.validate_unique_upc(data['upc']): return json.dumps({'success': False, 'error': Error.ITEM_EXISTS.value}) new_price = model.Price( user=data['user'], upvotes=[], downvotes=[], price=data['price'], date=datetime.now().timestamp() ) new_store = model.Store( name=data['store'], location={ 'lat': data['lat'], 'long': data['long'] }, prices=[new_price] ) new_item = model.Item( upc=data['upc'], name=data['name'], image_url='', image=None, stores=[new_store] ) if 'image' in data: add_image(data['image'], new_item) elif 'image_url' in data: new_item.image_url = data['image_url'] try: new_item.save() except (validation.ValidationException, mongoengine.errors.ValidationError) as e: return json.dumps({'success': False, 'error': str(e)}) return json.dumps({'success': True, 'error': None})
def generate_wishlist_game(**kwargs): default_params = { "machine_name": "foo", "human_name": "bar", "price": model.Price(**{ "price": 12.00, "currency": "GBP" }), "os": "linux", "platform": "download" } default_params.update(kwargs) return wishlist.WishlistGame(**default_params)
def load_ticker_data(ticker_url_list, session): """ This function loads the tickers table and the daily close prices for the prices table. Both pull data from the Quandl API as a JSON object. """ for ticker_url in ticker_url_list: u = requests.get(ticker_url) data = u.text newdata = json.loads(data) ticker_symbol = (newdata["code"].split("_"))[1] ticker_name = newdata["name"] ticker_description = newdata["description"] stock = "stock" bond = "bond" if stock in ticker_description: ticker_category = "Stocks" elif bond in ticker_description: ticker_category = "Bonds" else: ticker_category = "" # Create new instance of the Ticker class called new_ticker new_ticker = model.Ticker(symbol=ticker_symbol, name=ticker_name, category=ticker_category) # Add each instance to session session.add(new_ticker) session.commit() # Prices pulls a list of lists (consisting of date, open, high, # low, close, volume. adjusted close). prices = newdata["data"] for price in prices: date = price[0] date_format = datetime.strptime(date, "%Y-%m-%d") date_format = date_format.date() close_price = price[4] new_ticker_price = model.Price(ticker_id=new_ticker.id, date=date_format, close_price=close_price) session.add(new_ticker_price) # commit after all instances are added session.commit()
def admin_price_update(price_id=0): if price_id: price_db = model.Price.get_by_id(price_id) else: price_db = model.Price() if not price_db: flask.abort(404) form = PriceUpdateAdminForm(obj=price_db) currency_dbs, currency_cursor = model.Currency.get_dbs(limit=-1) form.currency_from_key.choices = [(c.key.urlsafe(), c.name) for c in currency_dbs] form.currency_to_key.choices = [(c.key.urlsafe(), c.name) for c in currency_dbs] if flask.request.method == 'GET' and not form.errors: form.currency_from_key.data = price_db.currency_from_key.urlsafe( ) if price_db.currency_from_key else None form.currency_to_key.data = price_db.currency_to_key.urlsafe( ) if price_db.currency_to_key else None if form.validate_on_submit(): form.currency_from_key.data = ndb.Key( urlsafe=form.currency_from_key.data ) if form.currency_from_key.data else None form.currency_to_key.data = ndb.Key( urlsafe=form.currency_to_key.data ) if form.currency_to_key.data else None form.populate_obj(price_db) price_db.put() task.update_price_task(price_db) return flask.redirect( flask.url_for('admin_price_list', order='-modified')) return flask.render_template( 'price/admin_price_update.html', title='%s' % '%sPrice' % ('' if price_id else 'New '), html_class='admin-price-update', form=form, price_db=price_db, back_url_for='admin_price_list', api_url=flask.url_for( 'api.admin.price', price_key=price_db.key.urlsafe() if price_db.key else ''), )
def add_price(): ''' Adds a new price to an existing item. Body: {"upc", "price", "user", "store", "lat", "long"} Response: - {"success": true or false}, - {"error": error description} ''' data = request.get_json(force=True) required_fields = ['upc', 'price', 'user', 'store', 'lat', 'long'] if not validation.has_required(data, required_fields): return json.dumps({ 'success': False, 'error': Error.MISSING_FIELDS.value }) item = model.Item.objects(upc=data['upc']).first() if item is None: return json.dumps({'success': False, 'error': Error.ITEM_DNE.value}) new_price = model.Price(user=data['user'], upvotes=[], downvotes=[], price=data['price'], date=datetime.now().timestamp()) loc = {'lat': data['lat'], 'long': data['long']} store = item.stores.filter(name=data['store'], location=loc).first() if store is not None: store.prices.append(new_price) else: new_store = model.Store(name=data['store'], location=loc, prices=[new_price]) item.stores.append(new_store) try: item.save() except (validation.ValidationException, mongoengine.errors.ValidationError) as e: return json.dumps({'success': False, 'error': str(e)}) return json.dumps({'success': True, 'error': None})
from datetime import datetime import base64 def users(num, start=0): ''' Generates a list of usernames for upvote/downvote lists. ''' return ['user' + str(i) for i in range(start, start+num)] # valid price0 = model.Price( user='******', upvotes=users(10), downvotes=users(5, 10), price=1.99, date=datetime(2019, 3, 10, 11, 30, 12).timestamp() ) # valid price1 = model.Price( user='******', upvotes=users(7), downvotes=users(4, 7), price=0.99, date=datetime(2019, 3, 10, 11, 30, 42).timestamp() ) # valid price2 = model.Price(
def from_config(cls, **kwargs): if kwargs.get("price"): kwargs['requested_price'] = model.Price(**kwargs) return cls(**kwargs)