Esempio n. 1
0
def assets(pairs):
    fig, ax = plt.subplots()
    fig.set_tight_layout(True)

    for pair in pairs:
        df = priceof(pair).iloc[::60].iloc[-10000:]
        df.open = df.open / df.open[0]  # normalize to be comparable
        dates = df.index.strftime('%Y-%m-%d')

        ax.plot(
            dates,
            df.open,
            # marker='.', markersize=1,
            ls='-',
            lw=1,
            label=pair,
        )

    ax.set_title('Normalized evolution of assets compared to bitcoin')

    ax.tick_params(axis='x', labelrotation=40)
    ax.xaxis.set_major_locator(ticker.AutoLocator())
    ax.spines['top'].set_visible(False)
    ax.spines['right'].set_visible(False)
    ax.legend()

    return fig
Esempio n. 2
0
def corrmap():
    curves = [key for key in REGISTRY if key.endswith('usdt')]

    dfs = []
    for curve in curves:
        df = priceof(curve)[['open']].rename(columns={'open': curve})
        print(curve, df.index[0])
        if df.index[0] < datetime(2019, 6, 1):
            dfs.append(df)

    df = dfs.pop().join(dfs)
    corr = df.corr()
    sns.heatmap(
        corr,
        cmap=sns.diverging_palette(20, 220, n=200),
        square=True,
    )

    plt.show()
Esempio n. 3
0
def _():
    from read import priceof
    from arsim import AR

    past = 200
    pos = np.random.randint(400)

    btcc = priceof('btcusdt').open.iloc[::60 * 24]
    btc = btcc.pct_change().to_numpy()[-past - pos:-pos]
    btc_p = btc  #btcc.pct_change().to_numpy()[-pos:-pos+past]

    p, q = 10, 10
    pp, qq = 10, 10
    par, A, y = fitarma(btc, p=p, q=q)
    # _, Ap, yp = fitarma(btc_p, p=p, q=q)
    Ap, yp = A, y
    pred = A @ par
    predp = Ap @ par
    res = y - pred
    resp = yp - predp

    pgarch, B, u = mom2_garch(res, p=pp, q=qq)
    # _, Bp, up = mom2_garch(resp, p=pp, q=qq)
    Bp, up = B, u
    vol = np.sqrt(B @ pgarch)
    volp = np.sqrt(Bp @ pgarch)

    plt.plot(np.arange(len(btc_p)), btc_p, label='btc')
    plt.plot(np.arange(p + max(p, q), len(btc_p)), predp, label='predictions')
    plt.plot(np.arange(p + max(p, q) + pp + qq, len(btc_p)),
             volp,
             label='volatility')

    rvol = pd.Series(resp).rolling(20).std()
    plt.plot(np.arange(len(btc_p) - len(rvol), len(btc_p)),
             rvol,
             label='rolling standard deviation')
    plt.legend()

    plt.show()
Esempio n. 4
0
import numpy as np
from read import priceof


def mat(seq, p):
    shifts = [seq[p-i-1:-i-1] for i in range(p)]
    return np.vstack((*shifts, np.ones(len(seq) - p))).T

def ar(seq, p=1):
    return np.linalg.lstsq(mat(seq, p), seq[p:], rcond=None)[0]


returns = priceof('btcusdt').open.iloc[::60*24].pct_change()
params = ar(returns.to_numpy()[-300:], p=2)
residuals = returns[2:] - mat(returns, 2) @ params[:, np.newaxis]

plt.plot(residuals)
plt.show()
Esempio n. 5
0
    plots = [
        returns, autocorrelation, autocorrelation_squared, leverage, fat_tailed
    ]

    for pair in [
            'btcusdt',
            'xrpusdt',
            '^TCFA',
            '^TCDPIA',
            '^DJI',
            '^FCHI',
            'bnbusdt',
            'zrxusdt',
    ]:

        df = priceof(pair)
        print(df.columns)

        for plot in plots:
            for interval in ('minute', 'hourly', 'daily'):
                try:
                    fig = plot(df, interval=interval)
                except ValueError:
                    continue

                fig.savefig(
                    os.path.join(PLOTDIR,
                                 f'{pair}-{plot.__name__}-{interval}.png'))

                plt.close(fig)
Esempio n. 6
0
from read import priceof
import numpy as np


ccs = (
    '^TCFA', '^FCHI', '^DJI',
    'btcusdt', 'xrpusdt', 'ethusdt',
)

toks = (
    '^TCDPIA', 'repbtc', 'batbtc', 'enjbtc', 'omgbtc',
)

for pair in toks:
    asset = priceof(pair)

    scales = (1,)
    if pair not in ('^FCHI', '^DJI'):
        scales = np.cumprod((1, 60, 24))

    for scale in scales:
        returns = asset.open.iloc[::scale].pct_change()
        kurt = returns.kurtosis()

        print(f'{pair} fisher kurtosis, returns interval {scale}: {kurt}')