from __future__ import print_function
import time
import intrinio_sdk
from intrinio_sdk.rest import ApiException
from pprint import pprint

intrinio_sdk.ApiClient().configuration.api_key['api_key'] = 'YOUR_API_KEY'

crypto_api = intrinio_sdk.CryptoApi()
exchange = 'gemini'  # str | Returns stats for Crypto Currencies that trade on the specified Crypto Exchange. (optional)

currency = 'BTC'  # str | Returns stats for the specified Crypto Currency. (optional)

try:
    api_response = crypto_api.get_crypto_stats(exchange=exchange,
                                               currency=currency)
    stats = api_response.stats
    print("%s stats found!" % (len(stats)))

    for stat in stats:
        print("Name:             %s" % (stat.name))
        print("Code:             %s" % (stat.code))
        print("Symbol:           %s" % (stat.symbol))
        print("Market cap(USD):  %s" % (stat.market_cap_usd))
        print("Available supply: %s" % (stat.available_supply))
        print("Total supply:     %s" % (stat.total_supply))
        print("Max supply:       %s" % (stat.max_supply))
        print("Last updated:     %s" % (stat.last_updated))
        print("")
except ApiException as e:
    print("Exception when calling CryptoApi->get_crypto_stats: %s\n" % e)
def crypto(request):

    crypto_api = intrinio_sdk.CryptoApi()

    timeframe = 'd1'  # str | The time interval for the prices. (default to d1)
    # str | Return prices for the given Crypto Currency Pair. (optional)
    pair = 'btcusd'
    # str | Return prices for a Crypto Currency on the given Crypto Exchange. (optional)
    exchange = 'binance'
    # str | Return prices for the given Crypto Currency. (optional)
    currency = 'BTC'
    # str | Return price date/times in this timezone, also interpret start/end date/time parameters in this timezone. (optional) (default to UTC)
    timezone = 'UTC'
    # date | Return Crypto Prices on or after this date. (optional)
    start_date = datetime.today() - timedelta(days=200)
    # str | Return Crypto Prices at or after this time (24-hour). (optional)
    start_time = ''
    # date | Return Crypto Prices on or before this date. (optional)
    end_date = datetime.today() - timedelta(days=1)
    # str | Return Crypto Prices at or before this time (24-hour). (optional)
    end_time = ''
    # int | An integer greater than or equal to 1 for specifying the number of results on each page. (optional) (default to 100)
    page_size = 100
    # str | Gets the next page of data from a previous API call (optional)
    next_page = ''

    try:
        api_response = crypto_api.get_crypto_prices(
            timeframe,
            pair=pair,
            exchange=exchange,
            currency=currency,
            timezone=timezone,
            start_date=start_date,
            start_time=start_time,
            end_date=end_date,
            end_time=end_time,
            page_size=page_size,
            next_page=next_page)

        crypto_dict = api_response.prices_dict

        datos = pd.DataFrame(crypto_dict)
        f = plt.figure()
        ax = f.add_subplot(111)
        # TENGO QUE CAMBIAR LA FORMA EN LA QUE MUESTRA LAS FECHAS EL GRÁFICO
        ax.plot(datos['time'], datos['close'])
        ax.xaxis.set_major_locator(plt.MaxNLocator(8))
        ax.legend(['Value of a Bitcoin in USD'])
        plt.ylabel('Value', fontsize=10)
        plt.xlabel('Date', fontsize=10)
        ax.tick_params(labelsize=7, width=3)
        # plt.tight_layout()

        # Como enviaremos la imagen en bytes la guardaremos en un buffer
        buf = io.BytesIO()
        canvas = FigureCanvasAgg(f)
        canvas.print_png(buf)

        # Creamos la respuesta enviando los bytes en tipo imagen png
        response = HttpResponse(buf.getvalue(), content_type='image/png')

        # Limpiamos la figura para liberar memoria
        f.clear()

        # Añadimos la cabecera de longitud de fichero para más estabilidad
        response['Content-Length'] = str(len(response.content))

        # Devolvemos la response
        return response

        # return render(request, 'stock_tracker/table.html', {'datos': datos.to_html})

    except ApiException as err:
        return HttpResponse('Ha ocurrido un error {}'.format(err))