Search code examples
pythonprettytable

Is there anyway to style <td> elements based on a conditional using PrettyTable


Here is the code:

from prettytable import PrettyTable
import requests

def market_table():
    api = "https://api.coinmarketcap.com/v2/ticker/"
    raw_data = requests.get(api).json()
    data = raw_data['data']

    table = PrettyTable()

    for currency in data:
        name = data[currency]['name']
        market_cap = data[currency]['quotes']['USD']['market_cap']
        price = data[currency]['quotes']['USD']['price']
        change_1h = data[currency]['quotes']['USD']['percent_change_1h']
        change_24h = data[currency]['quotes']['USD']['percent_change_24h']
        change_7d = data[currency]['quotes']['USD']['percent_change_7d']

        table.add_row([name,market_cap,price,change_1h,change_24h,change_7d])

    table.field_names = ["Name","Market Cap","Price","Change 1h","Change 24h","Change 7d"]
    table.sortby = "Market Cap"
    table.reversesort = True
    market_table = table.get_html_string()
    return market_table

What I want to do is style the change_1h,change_24h, and change_7d to color red if change<0, and color green if change>0. Is this possible using PrettyTable?


Solution

  • Color modifications are not possible with PrettyPrint but you can apply your own postprocessing:

    import re
    import requests
    from prettytable import PrettyTable
    
    def market_table():
        changes = []
        data = requests.get('https://api.coinmarketcap.com/v2/ticker').json()['data']
        table = PrettyTable(['Name', 'Market Cap', 'Price', 'Change 1h', 'Change 24h', 'Change 7d'], sortby='Market Cap', reversesort=True)
        for currency in data:
            change_1h = data[currency]['quotes']['USD']['percent_change_1h']
            change_24h = data[currency]['quotes']['USD']['percent_change_24h']
            change_7d = data[currency]['quotes']['USD']['percent_change_7d']
            changes.extend([change_1h, change_24h, change_7d])
            table.add_row([data[currency]['name'], data[currency]['quotes']['USD']['market_cap'],
                           data[currency]['quotes']['USD']['price'], change_1h, change_24h, change_7d])
        html = table.get_html_string()
        for change in changes:
            color = '#00FF00' if change > 0 else '#FF0000'
            html = re.sub('<td>{}</td>'.format(change), '<td bgcolor="{}">{}</td>'.format(color, change), html)
        return html
    

    This is what you'll get:

    enter image description here