# Code from http://gouthamanbalaraman.com/blog/calculating-stock-beta.html
# Modified very slightly so that it could be easily reused.

from pandas.io.data import DataReader
from datetime import date, datetime
import numpy as np
import pandas as pd
import datetime

# Grab time series data for 5-year history for the stock (here AAPL)
# and for S&P-500 Index
def calculateTrend(sym, edate):
    DD = datetime.timedelta(days=365*5)
    sdate = (datetime.datetime.now() - DD).strftime("%Y-%m-%d")
    df = DataReader(sym, 'yahoo', sdate, edate)
    dfb = DataReader('^GSPC', 'yahoo', sdate, edate)

    # create a time-series of monthly data points
    rts = df.resample('M',how='last')
    rbts = dfb.resample('M',how='last')
    dfsm = pd.DataFrame({'s_adjclose' : rts['Adj Close'],
                            'b_adjclose' : rbts['Adj Close']},
                            index=rts.index)

    # compute returns
    dfsm[['s_returns', 'b_returns']] = dfsm[['s_adjclose', 'b_adjclose']]/\
        dfsm[['s_adjclose', 'b_adjclose']].shift(1) -1
    dfsm = dfsm.dropna()
    covmat = np.cov(dfsm["s_returns"], dfsm["b_returns"])

    # calculate measures now
    beta = covmat[0,1]/covmat[1,1]
    alpha= np.mean(dfsm["s_returns"])-beta*np.mean(dfsm["b_returns"])

    # r_squared     = 1. - SS_res/SS_tot
    ypred = alpha + beta * dfsm["b_returns"]
    SS_res = np.sum(np.power(ypred-dfsm["s_returns"],2))
    SS_tot = covmat[0,0]*(len(dfsm)-1) # SS_tot is sample_variance*(n-1)
    r_squared = 1. - SS_res/SS_tot
    # 5- year volatiity and 1-year momentum
    volatility = np.sqrt(covmat[0,0])
    momentum = np.prod(1+dfsm["s_returns"].tail(12).values) -1

    # annualize the numbers
    prd = 12. # used monthly returns; 12 periods to annualize
    alpha = alpha*prd
    volatility = volatility*np.sqrt(prd)

    return beta, alpha, r_squared, volatility, momentum
34404b6a29cc2e3d690a4818f0d27a4ca1366704
<mask token>

<mask token>


def calculateTrend(sym, edate):
    DD = datetime.timedelta(days=365 * 5)
    sdate = (datetime.datetime.now() - DD).strftime('%Y-%m-%d')
    df = DataReader(sym, 'yahoo', sdate, edate)
    dfb = DataReader('^GSPC', 'yahoo', sdate, edate)
    rts = df.resample('M', how='last')
    rbts = dfb.resample('M', how='last')
    dfsm = pd.DataFrame({'s_adjclose': rts['Adj Close'], 'b_adjclose': rbts
        ['Adj Close']}, index=rts.index)
    dfsm[['s_returns', 'b_returns']] = dfsm[['s_adjclose', 'b_adjclose']
        ] / dfsm[['s_adjclose', 'b_adjclose']].shift(1) - 1
    dfsm = dfsm.dropna()
    covmat = np.cov(dfsm['s_returns'], dfsm['b_returns'])
    beta = covmat[0, 1] / covmat[1, 1]
    alpha = np.mean(dfsm['s_returns']) - beta * np.mean(dfsm['b_returns'])
    ypred = alpha + beta * dfsm['b_returns']
    SS_res = np.sum(np.power(ypred - dfsm['s_returns'], 2))
    SS_tot = covmat[0, 0] * (len(dfsm) - 1)
    r_squared = 1.0 - SS_res / SS_tot
    volatility = np.sqrt(covmat[0, 0])
    momentum = np.prod(1 + dfsm['s_returns'].tail(12).values) - 1
    prd = 12.0
    alpha = alpha * prd
    volatility = volatility * np.sqrt(prd)
    return beta, alpha, r_squared, volatility, momentum

from pandas.io.data import DataReader
from datetime import date, datetime
import numpy as np
import pandas as pd
import datetime


def calculateTrend(sym, edate):
    DD = datetime.timedelta(days=365 * 5)
    sdate = (datetime.datetime.now() - DD).strftime('%Y-%m-%d')
    df = DataReader(sym, 'yahoo', sdate, edate)
    dfb = DataReader('^GSPC', 'yahoo', sdate, edate)
    rts = df.resample('M', how='last')
    rbts = dfb.resample('M', how='last')
    dfsm = pd.DataFrame({'s_adjclose': rts['Adj Close'], 'b_adjclose': rbts
        ['Adj Close']}, index=rts.index)
    dfsm[['s_returns', 'b_returns']] = dfsm[['s_adjclose', 'b_adjclose']
        ] / dfsm[['s_adjclose', 'b_adjclose']].shift(1) - 1
    dfsm = dfsm.dropna()
    covmat = np.cov(dfsm['s_returns'], dfsm['b_returns'])
    beta = covmat[0, 1] / covmat[1, 1]
    alpha = np.mean(dfsm['s_returns']) - beta * np.mean(dfsm['b_returns'])
    ypred = alpha + beta * dfsm['b_returns']
    SS_res = np.sum(np.power(ypred - dfsm['s_returns'], 2))
    SS_tot = covmat[0, 0] * (len(dfsm) - 1)
    r_squared = 1.0 - SS_res / SS_tot
    volatility = np.sqrt(covmat[0, 0])
    momentum = np.prod(1 + dfsm['s_returns'].tail(12).values) - 1
    prd = 12.0
    alpha = alpha * prd
    volatility = volatility * np.sqrt(prd)
    return beta, alpha, r_squared, volatility, momentum

# Code from http://gouthamanbalaraman.com/blog/calculating-stock-beta.html
# Modified very slightly so that it could be easily reused.

from pandas.io.data import DataReader
from datetime import date, datetime
import numpy as np
import pandas as pd
import datetime

# Grab time series data for 5-year history for the stock (here AAPL)
# and for S&P-500 Index
def calculateTrend(sym, edate):
    DD = datetime.timedelta(days=365*5)
    sdate = (datetime.datetime.now() - DD).strftime("%Y-%m-%d")
    df = DataReader(sym, 'yahoo', sdate, edate)
    dfb = DataReader('^GSPC', 'yahoo', sdate, edate)

    # create a time-series of monthly data points
    rts = df.resample('M',how='last')
    rbts = dfb.resample('M',how='last')
    dfsm = pd.DataFrame({'s_adjclose' : rts['Adj Close'],
                            'b_adjclose' : rbts['Adj Close']},
                            index=rts.index)

    # compute returns
    dfsm[['s_returns', 'b_returns']] = dfsm[['s_adjclose', 'b_adjclose']]/\
        dfsm[['s_adjclose', 'b_adjclose']].shift(1) -1
    dfsm = dfsm.dropna()
    covmat = np.cov(dfsm["s_returns"], dfsm["b_returns"])

    # calculate measures now
    beta = covmat[0,1]/covmat[1,1]
    alpha= np.mean(dfsm["s_returns"])-beta*np.mean(dfsm["b_returns"])

    # r_squared     = 1. - SS_res/SS_tot
    ypred = alpha + beta * dfsm["b_returns"]
    SS_res = np.sum(np.power(ypred-dfsm["s_returns"],2))
    SS_tot = covmat[0,0]*(len(dfsm)-1) # SS_tot is sample_variance*(n-1)
    r_squared = 1. - SS_res/SS_tot
    # 5- year volatiity and 1-year momentum
    volatility = np.sqrt(covmat[0,0])
    momentum = np.prod(1+dfsm["s_returns"].tail(12).values) -1

    # annualize the numbers
    prd = 12. # used monthly returns; 12 periods to annualize
    alpha = alpha*prd
    volatility = volatility*np.sqrt(prd)

    return beta, alpha, r_squared, volatility, momentum