import numpy as np
from microconventions import sign_changes, is_process


# --------------------------------------------------------------------------
#           Miscellaneous utilities
# --------------------------------------------------------------------------

def inv_cdf_walk(inv_cdf, k: int, x0: float) -> float:
    """ Generate sample from sum of independent increments generated by inverse cdf function
         inv_cdf  get_iex_realtime_price   taking (0,1) --> R
         k        int    Number of steps
         x0       float  Starting value
    """
    # See crawler_examples/decastyle_cat for usage example
    x = x0
    for _ in range(k):
        u = np.random.rand()
        dx = inv_cdf(u)
        x = x + dx
    return x


def k_differences(lagged_values,k=1):
    chrono_values = [0.]*k + list(reversed(lagged_values))
    k_diff = list()
    for j in range(k):
        k_diff.extend(np.diff(chrono_values[j:-1:k]))
    return k_diff


def k_diff_std(lagged_values,k=1):
    return np.nanstd(k_differences(lagged_values=lagged_values,k=k))


def k_std(lagged_values,k=1):
    if is_process(lagged_values):
        return k_diff_std(lagged_values,k=k)
    else:
        return np.nanstd(lagged_values)