def _generate_graph(date_strings): chart = QuickChart() chart.width = 800 chart.height = 400 chart.config = { "data": { "labels": date_strings }, "options": { "scales": { "yAxes": [{ "ticks": { "beginAtZero": True, "suggestedMax": 1 } }] }, "legend": { "position": "bottom" }, "title": { "display": True, "fontSize": 22 } } } return chart
def generate_chart_one_data_set(dates, data_set): url = None LOGGER = logging.getLogger() LOGGER.setLevel(logging.INFO) try: qc = QuickChart() qc.width = 500 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { "type": "line", "data": { "labels": dates, "datasets": [{ "label": "Daily Deaths", "data": data_set }] }, "pointRadius": "0", "fill": "False" } url = qc.get_short_url() except Exception as ex: LOGGER.INFO(ex) finally: return url
def test_no_chart(self): qc = QuickChart() qc.width = 600 qc.height = 300 qc.device_pixel_ratio = 2.0 self.assertRaises(RuntimeError, qc.get_url)
def get_chart(self, high, low): qc = QuickChart() qc.width = 500 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { "type": 'bar', "data": { "labels": ['movies get a low score', 'movies get a high score'], "datasets": [{ "label": "movies have the feature mentioned above", "data": [low, high, 100] }] }, "options": { "plugins": { "datalabels": { "display": True, "backgroundColor": '#ccc', "borderRadius": 3, "font": { "size": 18, } }, } } } return qc.get_url()
def create_chart(width, height, type, data): chart = QuickChart() chart.width = width chart.height = height chart.device_pixel_ration = 2.0 chart.config = data return chart.get_url()
def test_get_bytes(self): qc = QuickChart() qc.width = 600 qc.height = 300 qc.config = { "type": "bar", "data": { "labels": ["Hello world", "Test"], "datasets": [{ "label": "Foo", "data": [1, 2] }] } } self.assertTrue(len(qc.get_bytes()) > 8000)
def covid_info(): """Get Covid-19 informations about a country.""" # User reached route via POST (as by submitting a form via POST) if request.method == "POST": # Call the function lookup to get the newest data about the Covid-19 from the API covid_info = lookup(request.form.get("country")) # If invalid input if covid_info == None: flash("Invalid country. Try again.") return redirect("/information") # Create a Bar Chart with the information returned from the API qc = QuickChart() qc.width = 500 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { "type": "bar", "data": { "labels": covid_info["date"][22::2], "datasets": [ {"label": "Infected Persons", "data": covid_info["active"][22::2]}, {"label": "Total Deaths", "data": covid_info["deaths"][22::2]}, ], }, } image_url = qc.get_url() # return information return render_template( "information_result.html", country=covid_info["country"], active_cases=covid_info["active"][-1], total_deaths=covid_info["deaths"][-1], new_deaths=covid_info["new_deaths"], total_recovered=covid_info["recovered"][-1], date=covid_info["date"][-1], image_url=image_url, ) # Request method = GET else: return render_template("information.html")
def sparkline(data): # generate image for badge qc = QuickChart() qc.width = 75 qc.height = 25 #qc.device_pixel_ratio = 2.0 qc.config = {"type": "sparkline", "data": {"datasets": [{"data": data}]}} url = qc.get_short_url() badge = requests.get(url).content # serve image with suitable cache control headers res = make_response(badge) res.headers.set('Content-Type', 'image/png') res.headers.set('Cache-Control', 'no-cache, no-store, must-revalidate, max-age=0') res.headers.set('Pragma', 'no-cache') res.headers.set('Expires', '0') return res
def test_simple(self): qc = QuickChart() qc.width = 600 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { "type": "bar", "data": { "labels": ["Hello world", "Test"], "datasets": [{ "label": "Foo", "data": [1, 2] }] } } url = qc.get_url() self.assertIn('w=600', url) self.assertIn('h=300', url) self.assertIn('devicePixelRatio=2', url) self.assertIn('Hello+world', url)
async def graph(ctx): qc = QuickChart() qc.width = 600 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { "type": "bar", "data": { "labels": ["Hello world", "Test"], "datasets": [{ "label": "Foo", "data": [1, 2] }] } } with Image.open(BytesIO(qc.get_bytes())) as chat_sample: output_buffer = BytesIO( ) # By using BytesIO we don't have to save the file in our system. chat_sample.save(output_buffer, "png") output_buffer.seek(0) await ctx.send(file=discord.File(fp=output_buffer, filename="chat_sample.png") ) # Change the file name accordingly.
def get_chart(results): from quickchart import QuickChart qc = QuickChart() qc.width = 900 qc.height = 500 qc.device_pixel_ratio = 2.0 qc.config = { "type": "line", "data": { "labels": list(range(len(results))), "datasets": [ { "label": "ms", "backgroundColor": "rgb(255, 99, 132)", "borderColor": "rgb(255, 99, 132)", "data": results, "fill": False, }, ], }, } return qc.get_url()
from quickchart import QuickChart qc = QuickChart() qc.width = 600 qc.height = 300 qc.device_pixel_ratio = 2.0 qc.config = { "type": "bar", "data": { "labels": ["Hello world", "Test"], "datasets": [{ "label": "Foo", "data": [1, 2] }] } } print(qc.get_url()) # https://quickchart.io/chart?c=%7B%22type%22%3A+%22bar%22%2C+%22data%22%3A+%7B%22labels%22%3A+%5B%22Hello+world%22%2C+%22Test%22%5D%2C+%22datasets%22%3A+%5B%7B%22label%22%3A+%22Foo%22%2C+%22data%22%3A+%5B1%2C+2%5D%7D%5D%7D%7D&w=600&h=300&bkg=%23ffffff&devicePixelRatio=2.0&f=png
def get_chart(symbol, duration): """Fetches Finnhub candle data and creates a chart using QuickChart.io API""" start = math.trunc(time.time()) stop = 0.0 resoultion = '' res_long = '' step = 60 if duration.lower().strip( ) == 'd': # sets some variables to be used later based on chart duration stop = math.trunc(time.time() - (86400 * 1)) resolution = '1' res_long = 'Day' step = 60 * 1 elif duration.lower().strip() == 'w': stop = math.trunc(time.time() - (86400 * 7)) resolution = '5' res_long = 'Week' step = 60 * 5 elif duration.lower().strip() == 'm': stop = math.trunc(time.time() - (86400 * 30)) resolution = '30' res_long = 'Month' step = 60 * 30 elif duration.lower().strip() == 'y': stop = math.trunc(time.time() - (86400 * 365)) resolution = 'D' res_long = 'Year' step = 60 * 1440 else: return 'invalid_duration' r = requests.get( f'https://finnhub.io/api/v1/stock/candle?symbol={symbol.upper()}&resolution={resolution}&from={stop-86400}&to={start-86400}&token={API_KEY}' ) json = r.json() # print(json) FIX THIS # print(datetime.datetime.today().weekday()) #Test this over a weekend if json == {'s': 'no_data'} or json['s'] == 'no_data': if datetime.datetime.today().weekday() >= 5: return 'invalid_weekend' else: return 'invalid_symbol' r2 = requests.get( f'https://finnhub.io/api/v1/stock/profile2?symbol={symbol.upper()}&token={API_KEY}' ) # Gets company name. Makes two API calls, could be removed if needed json2 = r2.json() name = json2['name'] data = json['c'] # stock price (close) data lables = [ time.strftime('%b %d %H:%M', datetime.fromtimestamp(i).timetuple()) for i in json['t'] ] # lables for x axis qc = QuickChart() qc.width = 700 qc.height = 500 qc.device_pixel_ratio = 1.0 qc.background_color = '#ffffff' qc.config = { # configuration data for chart formatting. See https://www.chartjs.org/. "type": "line", "data": { "labels": lables, "datasets": [{ "data": data, "fill": "false", "spanGaps": True, "pointRadius": 0, "showLine": True, "borderWidth": 2.5, "borderColor": "#000000" }] }, "options": { "title": { "display": True, "text": f"{symbol.upper()} ({name}) {res_long} Price Chart", "fontSize": 18, "fontFamily": "Helvetica", "fontColor": "#000000" }, "legend": { "display": False, }, "scales": { "xAxes": [{ "scaleLabel": { "display": True, "labelString": "Date" }, }], "yAxes": [{ "scaleLabel": { "display": True, "labelString": "US Dollars" }, "ticks": { "suggestedMin": .95 * min(data), "suggestedMax": 1.05 * max(data) }, }] } } } return qc.get_short_url()
async def bitcoin(self, ctx, mode=None, amount=None): if stocks_up: await open_account(ctx.author) user = ctx.author users = await get_bank_data() bal = await update_bank(ctx.author) if mode == None: await ctx.send( f'{ctx.author.mention}: You must specify if you want to view or sell' ) elif mode == 'view': if amount == None: amount = '14' amount = int(amount) if amount < 0: await ctx.send( f'{ctx.author.mention}: Only positive numbers allowed') elif amount > 100: await ctx.send( f'{ctx.author.mention}: You cannot go past 100 days') else: btc_prices = [] label_count = [] for i in range(amount, 0, -1): label_count.append(str(btc.index.date[i])) btc_prices.append(btc['1a. open (CAD)'][i]) qc = QuickChart() qc.width = 500 qc.height = 300 qc.background_color = 'white' qc.device_pixel_ratio = 2.0 qc.config = { "type": "line", "data": { "labels": label_count, "datasets": [{ "label": "BTC", "data": btc_prices, "fill": False, "borderColor": 'orange' }] } } bitcoin_chart = qc.get_short_url() em = discord.Embed(title=f"Price of Bitcoin", color=discord.Color.orange()) em.set_image(url=bitcoin_chart) em.add_field(name='BTC', value=f'Prices for the last {amount} days', inline=False) em.add_field(name='Current Price', value='```%sMM```' % bitcoin_price, inline=False) await ctx.send(embed=em) elif mode == 'sell': await open_account(ctx.author) if amount == None: await ctx.send( f"{ctx.author.mention}: Please enter the amount") return bal = await update_bank(ctx.author) if amount == 'all': amount = bal[6] amount = float(amount) earnings = int(amount * bitcoin_price) if amount > bal[6]: await ctx.send( f"{ctx.author.mention}: You don't have that much bitcoin" ) return if amount < 0: await ctx.send( f"{ctx.author.mention}: You must enter a positive number" ) return await ctx.send( f"{ctx.author.mention}: You sold {amount} bitcoin and earned {earnings}MM" ) await update_bank(ctx.author, -1 * amount, 'bitcoin') await update_bank(ctx.author, earnings, 'bank') else: await ctx.send( f'{ctx.author.mention}: That option doesn\'t exist') else: await ctx.send( 'Stock API is down for now. Reload in a minute and try again.')