Ir al contenido
← Todos los ejemplos

Ejemplo 07

Candle volatility

A published dataset's candles, hour by hour: realized volatility from

Categoría
Host: necesita los datos y el motor de la terminal
Permisos
market.read
Lenguaje
>=0.1.1, <0.2.0
Host
>=0.1.1, <0.2.0
Necesita
market >=0.1.1, <0.2.0

Código

// Category: host
// Permissions: market.read
// A published dataset's candles, hour by hour: realized volatility from
// 1-minute log returns, with the hours that lack data said out loud.
//
// Grant in the T0 Lang window: market.read.

lang ">=0.1.1, <0.2.0";
host "ttt" ">=0.1.1, <0.2.0";
requires "market" ">=0.1.1, <0.2.0";
import std.ind;
import std.stats;
import std.math;

fn closes(candles: List<market.Candle>) -> List<Float> {
    let mut out: List<Float> = [];
    for c in candles {
        out.push(to_float(c.close.amount()));
    }
    return out;
}

fn main() -> Result<Unit, Error> {
    let ds = market.datasets("BTCUSDT")?.first().expect("no published BTCUSDT dataset on this machine");
    // The id names the exact data; a result can be reproduced from it.
    let same = market.dataset(ds.id)?;
    print("dataset " + same.id + " (" + same.symbol + ", quote " + to_string(same.quote) + ")");
    let start = ds.first.expect("an empty dataset");
    let mut hour = 0;
    while hour < 6 {
        let from = start + 1h * hour;
        let candles = market.candles(ds, from, from + 1h)?;
        let returns = ind.known(ind.log_returns(closes(candles)));
        match stats.stdev(returns) {
            Some(s) => print("hour " + to_string(hour) + ": " + to_string(candles.len()) + " candles, volatility " + to_string(s * math.sqrt(60.0)) + " per hour"),
            None => print("hour " + to_string(hour) + ": too few candles (" + to_string(candles.len()) + ") for a volatility"),
        }
        hour = hour + 1;
    }
    return Ok(());
}