示例#1
0
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
示例#2
0
    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)
示例#3
0
    def test_with_function_and_dates(self):
        qc = QuickChart()
        qc.config = {
            "type": "bar",
            "data": {
                "labels": [datetime(2020, 1, 15),
                           datetime(2021, 1, 15)],
                "datasets": [{
                    "label": "Foo",
                    "data": [1, 2]
                }]
            },
            "options": {
                "scales": {
                    "yAxes": [{
                        "ticks": {
                            "callback":
                            QuickChartFunction('(val) => val + "k"')
                        }
                    }],
                    "xAxes": [{
                        "ticks": {
                            "callback":
                            QuickChartFunction('(val) => "$" + val')
                        }
                    }]
                }
            }
        }

        url = qc.get_url()
        self.assertIn(
            '7B%22ticks%22%3A%7B%22callback%22%3A%28val%29+%3D%3E+%22%24%22+%2B+val%7D%7D%5D%7D%7D%7D',
            url)
        self.assertIn('2020-01-15T00%3A00%3A00', url)
示例#4
0
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
示例#5
0
 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()
示例#6
0
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()
示例#7
0
def get_doughnut_chart_url(user_w: User, user_t: TrackingUser, whole_day: bool = False) -> str:
    """
    This function generates a chart, representing users online vs offline,
    using quickchart.io API with configuration, based on
    template `/bot/utils/assets/doughnut_chart_config` based on user_t online timeline
    for last ``user_w.notification_timeout`` if ``whole_day`` is ``False`` or last 24hrs if it is ``True``.

    Parameters
    ----------
    user_w : user.User
        User, which properties i.e. notification timeout and user_t online timeline are considered as factors
        for the chart data. user_t must be a part of user.get_tracking_users() list.
    user_t : user.TrackingUser
        Tracking user, whose online timeline list is being monitored and transposed to chart data.
    whole_day : bool
        if True, chart will contain data, based on user_t last 24hrs activity, otherwise, it'll be defaulted
        to `user_w.notification_timeout`.

    Returns
    -------
    str:
        URL for doughnut chart image which can be downloaded or embedded anywhere.
    """
    logger.info("Generating doughnut chart for {}(id:{}) about {}(id:{}), whole_day={}".format(user_w.first_name,
                                                                                               user_w.user_id,
                                                                                               user_t.first_name,
                                                                                               user_t.user_id,
                                                                                               whole_day))
    chart_config_template = Template(open("./bot/utils/assets/doughnut_chart_config.jinja2").read())

    # [online seconds, offline seconds]
    data = [*get_online_offline(user_w, user_t, whole_day)]
    total_string = get_labeled_time(sum(data))

    qc = QuickChart()
    qc.config = chart_config_template.render(data_string=json.dumps(data), total_string=json.dumps(total_string))

    return qc.get_url()
示例#8
0
def get_radar_chart_url(user_t: TrackingUser) -> str:
    """
    Creates a radar chart based on whole day user_t activity, having values from 0 to 1 for each of 24 rays.

    Parameters
    ----------
    user_t: user.TrackingUser
        Tracking user, whose data is being displayed on the resulting graph.

    Returns
    -------
    URL for radar chart image which can be downloaded or embedded anywhere.
    """
    logger.info("Generating radar chart about {}(id:{})".format(user_t.first_name, user_t.user_id))
    chart_config_template = Template(open("./bot/utils/assets/radar_chart_config.jinja2").read())

    # creating labels from 00:00:00 to 23:00:00 with 1 hour step
    start_of_day = get_start_of_day()
    labels = [(start_of_day + timedelta(hours=i)).strftime(TIME_FORMAT) for i in range(0, 24)]

    # getting array of records since start of the day
    records = get_whole_day_records(user_t)
    # number of records per hour
    chunk = int(HOUR // DEFAULT_TIMEOUT)

    # now, transferring boolean data to integer data, so it can be summed
    int_records = [int(rec) for rec in records]
    # and managing percentage of online time for each hour (for example having 3 records for hour
    # stored in list [1, 1, 0] would lead to 0.66 as online part of the whole hour (40 minutes))
    data = [sum(int_records[chunk * i:chunk * (i + 1)]) / chunk for i in range(24)]

    qc = QuickChart()
    qc.config = chart_config_template.render(labels=json.dumps(labels), data_string=json.dumps(data))

    url = qc.get_url()
    return url
    def get_quick_chart(json_data, output_file):
        qc = QuickChart()
        qc.width = 500
        qc.width = 500

        labels = []  #Declare to hold the x-axis tick labels
        weather_readings = []  #get the data labels

        for index in range(1, 8):
            local_time = datetime.datetime.fromtimestamp(
                json_data['daily'][index]['dt'],
                tz=pytz.timezone('Asia/Singapore'))
            labels.append(local_time.strftime('%a %d/%m '))

            weather_readings.append(
                round(json_data['daily'][index]['temp']['day'], 1))

        qc.config = """{ 
						  type: 'line', 
						  data: { 
						    labels: """ + str(labels) + """,
						datasets: [
		 				      { 
						        backgroundColor: 'rgb(255, 99, 132)', 
						        data: """ + str(weather_readings) + """,
						        lineTension: 0.4,
						        fill: false,
						      }
						    ],
						  },
						  options: { 
						  				title: { display: true,  text: '7-Day Weather Forecast' }, 
						  				legend: { display: false}, 
						  				scales: { yAxes: [ { scaleLabel: 
						  									 { display: true, labelString: 'Temperature Degrees Celcius' } } ]},
						  				plugins: {
												      datalabels: {
												        display: true,
												        align: 'bottom',
												        backgroundColor: '#ccc',
												        borderRadius: 3
												      },
												  }
						  			},
						}"""
        print(qc.get_short_url())  #Print out the chart URL
        qc.to_file(output_file)  #Save to a file
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")
示例#11
0
 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)
示例#12
0
    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)
示例#13
0
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
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()
示例#16
0
from quickchart import QuickChart, QuickChartFunction

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],
            "backgroundColor":
            QuickChartFunction(
                "getGradientFillHelper('vertical', ['rgba(63, 100, 249, 0.2)', 'rgba(255, 255, 255, 0.2)'])"
            ),
        }]
    }
}

print(qc.get_url())
from quickchart import QuickChart

qc = QuickChart()
qc.config = {
    "type": "bar",
    "data": {
        "labels": ["Hello world", "Test"],
        "datasets": [{
            "label": "Foo",
            # Count from 0 to 100
            "data": list(range(0, 100)),
        }]
    }
}

print(qc.get_short_url())
#
# Example output (note that this shortened URL is now expired and will not display a chart):
#
# https://quickchart.io/chart/render/f-b4bf9221-0499-4bc6-b1ae-6f7c78be9d93
#
示例#18
0
async def get_profile_embed(bot, ctx, member, alt=False):
    if alt:
        tag = await tag_convertor(bot, ctx, member, alt=True)
        if tag is None:
            return badEmbed(
                "This user has no alt saved! Use [prefix]savealt <tag>")
    else:
        tag = await tag_convertor(bot, ctx, member)
        if tag is None:
            return badEmbed(
                "This user has no tag saved! Use [prefix]save <tag>")
        if tag == "":
            desc = "/p\n/profile @user\n/p discord_name\n/p discord_id\n/p #BSTAG"
            return discord.Embed(title="Invalid argument!",
                                 colour=discord.Colour.red(),
                                 description=desc)

    bs_cog = bot.get_cog("BrawlStarsCog")
    try:
        player = await bs_cog.ofcbsapi.get_player(tag)

    except brawlstats.errors.NotFoundError:
        return badEmbed("No player with this tag found, try again!")

    except brawlstats.errors.RequestError as e:
        return badEmbed("BS API ERROR: " + str(e))

    except brawlstats.errors.RequestError as e:
        return badEmbed("BS API ERROR: " + str(e))

    colour = player.name_color if player.name_color is not None else "0xffffffff"
    embed = discord.Embed(color=discord.Colour.from_rgb(
        int(colour[4:6], 16), int(colour[6:8], 16), int(colour[8:10], 16)))
    player_icon_id = player.raw_data["icon"]["id"]
    if bs_cog.icons is None:
        bs_cog.icons = await bs_cog.starlist_request(
            "https://api.brawlapi.com/v1/icons")
    try:
        player_icon = bs_cog.icons['player'][str(player_icon_id)]['imageUrl2']
    except:
        if type(member) is discord.Member:
            player_icon = member.avatar_url
        else:
            player_icon = None
    if player_icon == "none":
        player_icon = None
    embed.set_author(name=f"{player.name} {player.raw_data['tag']}",
                     icon_url=player_icon)
    embed.add_field(
        name="Trophies",
        value=f"{get_league_emoji(player.trophies)} {player.trophies}")
    embed.add_field(
        name="Highest Trophies",
        value=
        f"{get_league_emoji(player.highest_trophies)} {player.highest_trophies}"
    )
    embed.add_field(name="Level",
                    value=f"<:exp:614517287809974405> {player.exp_level}")
    star_powers = sum([len(x.star_powers) for x in player.brawlers])
    gadgets = sum([len(x['gadgets']) for x in player.raw_data['brawlers']])
    embed.add_field(
        name="Unlocked Brawlers",
        value=
        f"<:brawlers:614518101983232020> {len(player.brawlers)} <:star_power:729732781638156348> {star_powers} <:gadget:716341776608133130> {gadgets}"
    )
    if "tag" in player.raw_data["club"]:
        try:
            club = await bs_cog.ofcbsapi.get_club(player.club.tag)
            embed.add_field(
                name="Club",
                value=
                f"{bs_cog.get_badge(club.raw_data['badgeId'])} {player.club.name}"
            )
            for m in club.members:
                if m.tag == player.raw_data['tag']:
                    embed.add_field(
                        name="Role",
                        value=
                        f"<:role:614520101621989435> {m.role.capitalize()}")
                    break
        except brawlstats.errors.RequestError:
            embed.add_field(
                name="Club",
                value=f"<:bsband:600741378497970177> {player.club.name}")
            embed.add_field(
                name="Role",
                value=
                f"<:offline:642094554019004416> Error while retrieving role")
    else:
        embed.add_field(name="Club",
                        value=f"<:noclub:661285120287834122> Not in a club")
    embed.add_field(
        name="3v3 Wins",
        value=
        f"{get_gamemode_emoji(get_gamemode_id('gemgrab'))} {player.raw_data['3vs3Victories']}"
    )
    embed.add_field(
        name="Showdown Wins",
        value=
        f"{get_gamemode_emoji(get_gamemode_id('showdown'))} {player.solo_victories} {get_gamemode_emoji(get_gamemode_id('duoshowdown'))} {player.duo_victories}"
    )
    rr_levels = ["-", "Normal", "Hard", "Expert", "Master", "Insane"]
    if player.best_robo_rumble_time > 5:
        rr_level = f"Insane {player.best_robo_rumble_time - 5}"
    else:
        rr_level = rr_levels[player.best_robo_rumble_time]
    embed.add_field(
        name="Best RR Level",
        value=f"{get_gamemode_emoji(get_gamemode_id('roborumble'))} {rr_level}"
    )
    #embed.add_field(
    #    name="Best Time as Big Brawler",
    #    value=f"<:biggame:614517022323245056> {player.best_time_as_big_brawler//60}:{str(player.best_time_as_big_brawler%60).rjust(2, '0')}")
    if "highestPowerPlayPoints" in player.raw_data:
        value = f"{player.raw_data['highestPowerPlayPoints']}"
        embed.add_field(name="Highest PP Points",
                        value=f"<:powertrophies:661266876235513867> {value}")
    reset = reset_trophies(player) - player.trophies
    embed.add_field(
        name="Season Reset",
        value=
        f"<:bstrophy:552558722770141204> {reset} <:starpoint:661265872891150346> {calculate_starpoints(player)}"
    )
    emo = "<:good:450013422717763609> Qualified" if player.raw_data[
        'isQualifiedFromChampionshipChallenge'] else "<:bad:450013438756782081> Not qualified"
    embed.add_field(name="Championship", value=f"{emo}")

    # try:
    #     log = (await bs_cog.ofcbsapi.get_battle_logs(player.raw_data['tag'])).raw_data
    #     plsolo = None
    #     plteam = None
    #     for battle in log:
    #         if "type" in battle['battle']:
    #             if battle['battle']['type'] == "soloRanked" and plsolo is None:
    #                 for play in (battle['battle']['teams'][0]+battle['battle']['teams'][1]):
    #                     if play['tag'] == player.raw_data['tag']:
    #                         plsolo = play['brawler']['trophies']
    #                         break
    #             if battle['battle']['type'] == "teamRanked" and plteam is None:
    #                 for play in (battle['battle']['teams'][0]+battle['battle']['teams'][1]):
    #                     if play['tag'] == player.raw_data['tag']:
    #                         plteam = play['brawler']['trophies']
    #                         break
    #         if plsolo is not None and plteam is not None:
    #             break

    #     lastsolo = 0
    #     lastteam = 0

    #     if plsolo is not None:
    #         await bs_cog.config.user(member).plsolo.set(plsolo)
    #         await bs_cog.config.user(member).lastsolo.set(int(datetime.datetime.timestamp(datetime.datetime.now())))
    #     elif isinstance(member, discord.Member):
    #         lastsolo = await bs_cog.config.user(member).lastsolo()
    #         if (datetime.datetime.now() - datetime.datetime.fromtimestamp(lastsolo)).days > 0:
    #             plsolo = await bs_cog.config.user(member).plsolo()

    #     if plteam is not None:
    #         await bs_cog.config.user(member).plteam.set(plteam)
    #         await bs_cog.config.user(member).lastteam.set(int(datetime.datetime.timestamp(datetime.datetime.now())))
    #     elif isinstance(member, discord.Member):
    #         lastteam = await bs_cog.config.user(member).lastteam()
    #         if (datetime.datetime.now() - datetime.datetime.fromtimestamp(lastteam)).days > 0:
    #             plteam = await bs_cog.config.user(member).plteam()

    #     if plsolo is not None:
    #         embed.add_field(name="Current Solo League", value=get_power_league(plsolo))
    #     if plteam is not None:
    #         embed.add_field(name="Current Team League", value=get_power_league(plteam))
    # except:
    #     pass

    texts = [
        "Check out all your brawlers using /brawlers!",
        "Want to see your club stats? Try /club!",
        "Have you seen all our clubs? No? Do /clubs!",
        "You can see stats of other players by typing /p @user.",
        "You can display player's stats by using his tag! /p #TAG",
        "Did you know LA Bot can display CR stats as well? /crp",
        "Check www.laclubs.net to see all our clubs!"
    ]

    if "name" in player.raw_data["club"] and player.raw_data["club"][
            "name"].startswith("LA "):
        try:
            history_url = "https://laclubs.net/api/history/player?tag=" + player.raw_data[
                'tag'].strip("#")
            data = None
            chart_data = []
            async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(
                    ssl=True)) as session:
                async with session.get(history_url) as resp:
                    data = await resp.json()
            if data is not None and data['status'] == "ok":
                one_day = int(
                    datetime.datetime.timestamp(datetime.datetime.now() -
                                                datetime.timedelta(hours=24)))
                one_week = int(
                    datetime.datetime.timestamp(datetime.datetime.now() -
                                                datetime.timedelta(days=7)))
                stats = ""
                for time in data['times']:
                    if time > one_day:
                        day_diff = player.trophies - data['trophies'][
                            data['times'].index(time)]
                        if day_diff >= 0:
                            stats += f"<:stonks:841606734066090015> **1 day** +{day_diff}\n"
                        else:
                            stats += f"<:stinks:841606733997670430> **1 day** {day_diff}\n"
                        break
                for time in data['times']:
                    if time > one_week:
                        week_diff = player.trophies - data['trophies'][
                            data['times'].index(time)]
                        if week_diff >= 0:
                            stats += f"<:stonks:841606734066090015> **1 week** +{week_diff}\n"
                        else:
                            stats += f"<:stinks:841606733997670430> **1 week** {week_diff}\n"
                        break
                if stats != "":
                    embed.add_field(name="Trophy Progression",
                                    value=stats,
                                    inline=False)

                for time, trophies in zip(
                        data['times'][:-20:4] + data['times'][-20::2],
                        data['trophies'][:-20:4] + data['trophies'][-20::2]):
                    chart_data.append("{t:new Date(" + str(time * 1000) +
                                      "),y:" + str(trophies) + "}")
                chart_data.append("{t:new Date(" + str(
                    int(
                        datetime.datetime.timestamp(datetime.datetime.now()) *
                        1000)) + "),y:" + str(player.trophies) + "}")
                qc = QuickChart()
                qc.config = """
                {
                    type: 'line',
                    data: {
                        datasets: [{
                            data : """ + str(chart_data).replace("\'",
                                                                 "") + """,
                            label: "trophies",
                            fill: true,
                            cubicInterpolationMode: 'monotone',
                            borderColor: 'rgba(10, 180, 20, 1)',
                            backgroundColor: 'rgba(10, 180, 20, 0.3)'
                        }]
                    },
                    options: {
                        scales: {
                            xAxes: [{
                                type: 'time',
                                time: {
                                    unit: 'day'
                                },
                                distribution: 'linear'
                            }]
                        },
                        responsive: false,
                        legend: {
                            display: false
                        },
                        tooltips: {
                            mode: 'index',
                            intersect: false
                        },
                        title: {
                            display: false,
                            text: 'TROPHY PROGRESSION',
                            fontStyle: 'bold'
                        },
                        layout: {
                            padding: {
                                left: 5,
                                right: 10,
                                top: 0,
                                bottom: 5
                            }
                        }
                    }
                }
                """
                embed.set_image(url=qc.get_short_url())
        except (aiohttp.client_exceptions.ContentTypeError):
            pass
    embed.set_footer(text=random.choice(texts))
    return embed
示例#19
0
    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.')
示例#20
0
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]
        }]
    }
}

qc.to_file('/tmp/mychart.png')

print('Done.')
示例#21
0
from quickchart import QuickChart

qc = QuickChart()
qc.width = 600
qc.height = 300
qc.device_pixel_ratio = 2.0
qc.config = '''{
  type: 'bar',
  data: {
    labels: ['Q1', 'Q2', 'Q3', 'Q4'],
    datasets: [{
      label: 'Users',
      data: [50, 60, 70, 180]
    }, {
      label: 'Revenue',
      data: [100, 200, 300, 400]
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          callback: (val) => {
            return val + 'k';
          }
        }
      }]
    }
  }
}'''
示例#22
0
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()
示例#23
0
from datetime import datetime

from quickchart import QuickChart, QuickChartFunction

qc = QuickChart()
qc.width = 600
qc.height = 300
qc.device_pixel_ratio = 2.0
qc.config = {
    "type": "bar",
    "data": {
        "labels": [datetime(2020, 1, 15), datetime(2021, 1, 15)],
        "datasets": [{
            "label": "Foo",
            "data": [1, 2]
        }]
    },
    "options": {
        "scales": {
            "yAxes": [{
                "ticks": {
                    "callback": QuickChartFunction('(val) => val + "k"')
                }
            }, {
                "ticks": {
                    "callback": QuickChartFunction('''function(val) {
                      return val + '???';
                    }''')
                }
            }],
            "xAxes": [{
示例#24
0
from quickchart import QuickChart

qc = QuickChart()
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": [1, 79, 100]
        }]
    },
    "options": {
        "plugins": {
            "datalabels": {
                "display": True,
                "backgroundColor": '#ccc',
                "borderRadius": 3,
                "font": {
                    "size": 18,
                }
            },
        }
    }
}

print(qc.get_short_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
示例#26
0
from quickchart import QuickChart

qc = QuickChart()
qc.config = '''{
  type: 'bar',
  data: {
    labels: ['Q1', 'Q2', 'Q3', 'Q4'],
    datasets: [{
      label: 'Users',
      data: [50, 60, 70, 180]
    }, {
      label: 'Revenue',
      data: [100, 200, 300, 400]
    }]
  },
  options: {
    scales: {
      yAxes: [{
        ticks: {
          callback: (val) => {
            return val + 'k';
          }
        }
      }]
    }
  }
}'''

print(qc.get_short_url())
#
# Example output (note that this shortened URL is now expired and will not display a chart):