Stack Exchange
quant. code. to calculate trend, momentum, correlation and volatility in Pandas(Python)
I am new to quant. finance and trying to calculate trend, momentum, correlation and volatility. Below are the functions I have created
import pandas as pd


def roll_correlation(first_df, second_df, rolling_period):
    """
    Rolling correlation
    """
    return first_df.rolling(rolling_period).corr(second_df)


def roll_volatility(df, rolling_period):
    """
    Rolling volatility
    """
    return df.pct_change().rolling(rolling_period).std(ddof=0)


# ASK: is rolling momentum calculation is correct
def roll_momentum(df, rolling_period):
    """
    Rolling momentum
    """
    return df.pct_change(rolling_period)


def roll_returns(df, rolling_period):
    """
    Rolling returns
    """
    return df.rolling(rolling_period).apply(lambda x: x.iloc[[0, -1]].pct_change()[-1])


def trend(df, rolling_period):
    """
    Identify trend
    """
    return df.apply(lambda x: x.autocorr(rolling_period))


if __name__ == '__main__':
    df = pd.Dataframe({'A': [1,2,3,4]})
    print (trend(df,2))


