Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Efficiency improvements to calculate risk params #32

Open
mikeyrf opened this issue Jan 20, 2022 · 1 comment · May be fixed by #29
Open

Efficiency improvements to calculate risk params #32

mikeyrf opened this issue Jan 20, 2022 · 1 comment · May be fixed by #29
Assignees

Comments

@mikeyrf
Copy link
Contributor

mikeyrf commented Jan 20, 2022

The csv scripts to calculate risk params around funding, market impact, and caps currently run unnecessary for loops over the time TS and possible k values. Removing the time dependence from calls to pystable and using np.array math should allow us to improve the efficiency of these scripts by removing the for loops.

@mikeyrf mikeyrf assigned deepsp94 and mikeyrf and unassigned mikeyrf Jan 20, 2022
@mikeyrf
Copy link
Contributor Author

mikeyrf commented Jan 20, 2022

With a bit of math around CDF and inverse CDF, we can use a numpy array for time in VaR, ES, EV calculations. Basically I'm taking advantage of stable distribution properties: X = mu * t + sigma * (t/a)**(1/a) * Z where Z is a standard stable.

For example, we can change nvalue_at_risk to (my code might be wrong, but math should be correct):

def nvalue_at_risk(a: float, b: float, mu: float, sigma: float,
                   k_n: float, v: float, g_inv: float, alpha: float,
                   t: np.array) -> (np.array, np.array):
    z = pystable.create(alpha=a, beta=b, mu=0, sigma=1, parameterization=1)

    z_ginv_max = (g_inv - mu * t) / (sigma * (t/a) ** (1/a))  # this is an np.array
    cdf_x_ginv = np.array(pystable.cdf(z, list(z_ginv_max), len(z_ginv_max)))  # this is also now a np.array

    # var long
    p_long = cdf_x_ginv - alpha  # np.array
    q_long = mu * t + sigma * (t/a) ** (1/a) * np.array(pystable.q(z, list(p_long), len(p_long)))  # also a np.array
    nvar_long = ((1-2*k_n)**(np.floor(t/v))) * (np.exp(q_long) - 1)  # now also a np.array

    # var short
    p_short = np.array([alpha for i in range(len(t))])  # a np.array
    q_short =  mu * t + sigma * (t/a) ** (1/a) * np.array(pystable.q(z, p_short, len(p_short)))  # a np.array
    nvar_short = ((1-2*k_n)**(np.floor(t/v))) * (1 - np.exp(q_short))  # a np.array

    return nvar_long, nvar_short

Using math

Fx(g_inv) = Fz((g_inv - mu * t)/(sigma * (t/a)**(1/a))

p = Fx(g_inv) - alpha
q = mu * t + sigma * (t/a) ** (1/a) * F^{-1}z (p)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants