# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/01-mkt-prices.ipynb (unless otherwise specified).

__all__ = ['get_ets_mkt_data', 'plot_long_term_avg', 'plot_ohlc_vol', 'plot_recent_ohlc_vol']

# Cell
import json
import pandas as pd

import matplotlib.pyplot as plt
import mplfinance as mpf
import FEAutils as hlp

import os
import requests

# Cell
def get_ets_mkt_data(
    api_key,
    api_root='https://www.quandl.com/api/v3/datasets',
    quandl_code='CHRIS/ICE_C1'
):
    # Constructing endpoint
    endpoint_url = f'{api_root}/{quandl_code}.json'

    # Making the data request
    params = {'api_key': api_key}
    r = requests.get(endpoint_url, params=params)

    # Converting to a dataframe
    dataset = r.json()['dataset']
    df = pd.DataFrame(dataset['data'], columns=dataset['column_names'])

    # Cleaning the dataframe
    df.columns = df.columns.str.lower().str.replace('.', '').str.replace(' ', '_')
    df = df.rename(columns={'date': 'datetime'}).set_index('datetime')
    df['close'] = df['open'] + df['change']
    df.index = pd.to_datetime(df.index)
    df = df.sort_index()

    return df

# Cell
def plot_long_term_avg(df):
    fig, ax = plt.subplots(dpi=250, figsize=(10, 4))

    df['settle'].plot(ax=ax, color='#AE0019', linewidth=1)

    ax.set_ylim(0)
    ax.set_xlim(df.index.min(), df.index.max())
    ax.set_xlabel('')
    ax.set_ylabel('Price (EUR/tonne CO2)')
    hlp.hide_spines(ax)

    return fig, ax

# Cell
def plot_ohlc_vol(df):
    fig, axs = plt.subplots(dpi=250, nrows=2, figsize=(8, 8))

    mpf.plot(df, type='candle', ax=axs[0], volume=axs[1], show_nontrading=True, style='sas')

    ax = axs[0]
    ax.set_xticks([])
    ax.set_xticklabels([])
    ax.set_ylabel('Price (EUR/tonne CO2)')
    ax.yaxis.set_label_position('left')
    ax.yaxis.tick_left()
    hlp.hide_spines(ax, positions=['top', 'bottom', 'right'])

    ax = axs[1]
    ax.set_ylabel('Volume (tonne CO2)')
    hlp.hide_spines(ax, positions=['top', 'right'])

    return fig, axs

def plot_recent_ohlc_vol(df, weeks=8, latest_date=None):
    if latest_date is None:
        latest_date = df.index.max()

    earliest_date = latest_date - pd.Timedelta(weeks=weeks)

    cols = ['open', 'high', 'low', 'close', 'volume']
    df_recent = df[cols].sort_index().dropna().loc[earliest_date:latest_date]

    fig, axs = plot_ohlc_vol(df_recent)

    return fig, axs