In this demo, we are going to play with the API of CoinMarketCap using reobject.
Install the packages used in this notebook by doing: pip install reobject requests
Example response of GET https://api.coinmarketcap.com/v1/ticker/
[
{
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "11109.3",
"24h_volume_usd": "7389880000.0",
"market_cap_usd": "187461794302",
"available_supply": "16874312.0",
"total_supply": "16874312.0",
"max_supply": "21000000.0",
"percent_change_24h": "2.57",
"percent_change_7d": "26.87",
...
},
]
from reobject.models import Model
from reobject.models.fields import Field
class Coin(Model):
rank = Field()
name = Field()
symbol = Field()
percent_change_24h = Field()
# Create some instances of our Coin class. Notice how we aren't storing
# references to our objects!
Coin(rank=1, name='Bitcoin', symbol='BTC', percent_change_24h=-10.0)
Coin(rank=2, name='Ethereum', symbol='ETH', percent_change_24h=-70.0)
Coin.objects.all()
# Add a model property, and some automatic type converters to fields
class Coin(Model):
rank = Field(converter=int)
name = Field()
symbol = Field()
percent_change_24h = Field(converter=float)
@property
def is_green(self) -> bool:
return self.percent_change_24h > 0
# Populate real data from CoinMarketCap
import requests
Coin.objects.all().delete()
for coin in requests.get('https://api.coinmarketcap.com/v1/ticker/?limit=200').json():
Coin(rank=coin['rank'], name=coin['name'],
symbol=coin['symbol'], percent_change_24h=coin['percent_change_24h'])
Coin.objects.count()
# Get all coins that made a loss in the last 24 hours
Coin.objects.filter(percent_change_24h__lt=0.0).order_by('percent_change_24h')
# Get 24h change of your favorite coins
my_coins = {'BTC', 'ETH', 'LTC', 'BCH', 'XLM'}
Coin.objects.filter(symbol__in=my_coins).values('percent_change_24h', 'name')
# Get coins that have either "network" or "shares" in their names.
from reobject.query import Q
Coin.objects.filter(Q(name__icontains='network') | Q(name__icontains='shares'))
# You can even use properties as lookup params in the query.
Coin.objects.filter(is_green=True, symbol__in=my_coins)