Python pandas.rolling_mean() Examples

The following are 30 code examples of pandas.rolling_mean(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pandas , or try the search function .
Example #1
Source File: dataset.py    From PCWG with MIT License 6 votes vote down vote up
def __init__(self, x, y, timeStepInSeconds, df):

        movingAverageWindow = self.calculateMovingAverageWindow(timeStepInSeconds)

        self.xRolling = "xRolling"
        self.yRolling = "yRolling"

        self.xDiffSq = "xDiffSq"
        self.yDiffSq = "yDiffSq"

        df[self.xRolling] = pd.rolling_mean(df[x], window = movingAverageWindow, min_periods = 1)
        df[self.yRolling] = pd.rolling_mean(df[y], window = movingAverageWindow, min_periods = 1)

        df[self.xDiffSq] = ((df[x] - df[self.xRolling])** 2.0)
        df[self.yDiffSq] = ((df[y] - df[self.yRolling])** 2.0) # this needed in uncertainty?

        CalibrationBase.__init__(self, x, y)

        self.requiredColumns += [self.xDiffSq, self.yDiffSq] 
Example #2
Source File: equitycountrymodels.py    From systematictradingexamples with GNU General Public License v2.0 6 votes vote down vote up
def relative_ts_div_predictor(tickers, rawdata):
    all_divs=pd.concat([get_div_yield(tickname, rawdata) for tickname in tickers], axis=1, names=tickers)
    all_divs.columns=tickers
   
    vol_ts=pd.DataFrame([vols]*len(rawdata.index), rawdata.index, columns=tickers)

    divs_SR=all_divs / vol_ts

    divs_SR_ts_avg=pd.rolling_mean(divs_SR, 600, min_periods=1)
    
    norm_SR=divs_SR - divs_SR_ts_avg

    SR_avg=norm_SR.median(axis=1)
    SR_avg=expand_boring(SR_avg, tickers)

    
    rel_SR=norm_SR - SR_avg

    return rel_SR 
Example #3
Source File: c5.py    From abu with GNU General Public License v3.0 6 votes vote down vote up
def sample_532():
    """
    5.3.2 绘制股票的价格与均线
    :return:
    """
    tsla_df.close.plot()
    # ma 30
    # pd_rolling_mean(tsla_df.close, window=30).plot()
    pd_rolling_mean(tsla_df.close, window=30).plot()
    # ma 60
    # pd.rolling_mean(tsla_df.close, window=60).plot()
    pd_rolling_mean(tsla_df.close, window=60).plot()
    # ma 90
    # pd.rolling_mean(tsla_df.close, window=90).plot()
    pd_rolling_mean(tsla_df.close, window=90).plot()
    # loc='best'即自动寻找适合的位置
    plt.legend(['close', '30 mv', '60 mv', '90 mv'], loc='best')
    plt.show() 
Example #4
Source File: ABuPdHelper.py    From abu with GNU General Public License v3.0 6 votes vote down vote up
def _pd_rolling(pd_object, pd_object_cm, how, *args, **kwargs):
    """
    被_pd_object_covert装饰,对pandas中的rolling操作,根据pandas version版本自动选择调用方式
    :param pd_object: 可迭代的序列,pd.Series, pd.DataFrame或者只是Iterable
    :param pd_object_cm: 与pd_object相同,针对需要两个pandas对象或者序列执行的操作,如corr,cov等
    :param how: 代表方法操作名称,eg. mean, std, var
    :return:
    """
    if g_pandas_has_rolling:
        """pandas版本高,使用如pd_object.rolling直接调用"""
        rolling_obj = pd_object.rolling(*args, **kwargs)
        if hasattr(rolling_obj, how):
            if pd_object_cm is None:
                return getattr(rolling_obj, how)()
            # 需要两个pd_object进行的操作, getattr(rolling_obj, how)(pd_object_cm)
            return getattr(rolling_obj, how)(pd_object_cm)
    else:
        """pandas版本低,使用如pd.rolling_mean方法调用"""
        how_func = 'rolling_{}'.format(how)
        if hasattr(pd, how_func):
            if pd_object_cm is None:
                return getattr(pd, how_func)(pd_object, *args, **kwargs)
            # 需要两个pd_object进行的操作,getattr(pd, how_func)(pd_object, pd_object_cm, *args, **kwargs)
            return getattr(pd, how_func)(pd_object, pd_object_cm, *args, **kwargs)
    raise RuntimeError('_pd_rolling {} getattr error'.format(how)) 
Example #5
Source File: ma_strategy.py    From stock with Apache License 2.0 6 votes vote down vote up
def calcute_ma(self, df, avr_short=12, avr_long=40):
        """
        计算ma, ema
        :param df:
        :return:
        """
        if len(df) == 0:
            return

        # print "{} calcute ma".format(df.ix[0,'code'])
        df['ma_' + str(avr_short)] = pd.rolling_mean(df['close'], avr_short)  # 12
        df['ma_' + str(avr_long)] = pd.rolling_mean(df['close'], avr_long)  # 40

        # print "{} calcute ema".format(df.ix[0, 'code'])
        df['ema_' + str(avr_short)] = pd.ewma(df['close'], span=avr_short)  # 12
        df['ema_' + str(avr_long)] = pd.ewma(df['close'], span=avr_long)  # 40

        df = df.replace(np.nan, 0)
        return df 
Example #6
Source File: data_calcute.py    From stock with Apache License 2.0 6 votes vote down vote up
def calcute_ma(df, avr_short=12, avr_long=40):
    """
    计算ma, ema
    :param df:
    :return:
    """
    if len(df) == 0:
        return

    # print "{} calcute ma".format(df.ix[0,'code'])
    df['ma_' + str(avr_short)] = pd.rolling_mean(df['close'], avr_short)  # 12
    df['ma_' + str(avr_long)] = pd.rolling_mean(df['close'], avr_long)  # 40


    # print "{} calcute ema".format(df.ix[0, 'code'])
    df['ema_' + str(avr_short)] = pd.ewma(df['close'], span=avr_short)  # 12
    df['ema_' + str(avr_long)] = pd.ewma(df['close'], span=avr_long)  # 40

    df = df.replace(np.nan, 0)
    return df 
Example #7
Source File: viz2.py    From scipy2015-blaze-bokeh with MIT License 6 votes vote down vote up
def timeseries():
    # Get data
    df = pd.read_csv('data/Land_Ocean_Monthly_Anomaly_Average.csv')
    df['datetime'] = pd.to_datetime(df['datetime'])
    df = df[['anomaly','datetime']]
    df['moving_average'] = pd.rolling_mean(df['anomaly'], 12)
    df = df.fillna(0)
    
    # List all the tools that you want in your plot separated by comas, all in one string.
    TOOLS="crosshair,pan,wheel_zoom,box_zoom,reset,hover,previewsave"

    # New figure
    t = figure(x_axis_type = "datetime", width=1000, height=200,tools=TOOLS)

    # Data processing
    # The hover tools doesn't render datetime appropriately. We'll need a string. 
    # We just want dates, remove time
    f = lambda x: str(x)[:7]
    df["datetime_s"]=df[["datetime"]].applymap(f)
    source = ColumnDataSource(df)

    # Create plot
    t.line('datetime', 'anomaly', color='lightgrey', legend='anom', source=source)
    t.line('datetime', 'moving_average', color='red', legend='avg', source=source, name="mva")

    # Style
    xformatter = DatetimeTickFormatter(formats=dict(months=["%b %Y"], years=["%Y"]))
    t.xaxis[0].formatter = xformatter
    t.xaxis.major_label_orientation = math.pi/4
    t.yaxis.axis_label = 'Anomaly(ºC)'
    t.legend.orientation = "bottom_right"
    t.grid.grid_line_alpha=0.2
    t.toolbar_location=None

    # Style hover tool
    hover = t.select(dict(type=HoverTool))
    hover.tooltips = """
        <div>
            <span style="font-size: 15px;">Anomaly</span>
            <span style="font-size: 17px;  color: red;">@anomaly</span>
        </div>
        <div>
            <span style="font-size: 15px;">Month</span>
            <span style="font-size: 10px; color: grey;">@datetime_s</span>
        </div>
        """
    hover.renderers = t.select("mva")

    # Show plot
    #show(t)
    return t

# Add title 
Example #8
Source File: macd_back_test.py    From stock with Apache License 2.0 5 votes vote down vote up
def processEMA(stockCsvPath, stockCsvNewPath):
    #导入数据,stockCsvPath为在电脑中的路径
    stock_data = pd.read_csv(stockCsvPath)
    
    # 将数据按照交易日期从远到近排序
    stock_data.sort('Date', inplace=True)
    
    #=====================计算移动平均线
    
    # 分别计算5日、20日、60日移动平均线
    ma_list = [5, 20, 60]
    
    # 计算简单算术移动平均线MA - 注意:stock_data['close']为股票每条的收盘价
    for ma in ma_list:
        stock_data['MA_' + str(ma)] = pd.rolling_mean(stock_data['Adj Close'], ma)
        
    # 计算指数平滑移动平均线EMA
    for ma in ma_list:
        stock_data['EMA_' + str(ma)] = pd.ewma(stock_data['Adj Close'], span=ma)
        
    # 将数据按照交易日期从近到远排序
    stock_data.sort('Date', ascending=False, inplace=True)
    
    stock_data['DIF'] = stock_data['EMA_'+str(ma_list[0])] - stock_data['EMA_'+str(ma_list[-1])]
    stock_data['DEA_' + str(10)] = pd.ewma(stock_data['DIF'], span=10)
    
    # =================================== 将算好的数据输出到csv文件,这里请填写输出文件在您电脑的路径
    stock_data.to_csv(stockCsvNewPath, index=False)   
    
# 自适应均线 
Example #9
Source File: analysis.py    From NMT-Coverage with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_timings(path, y="cost2_p_expl", start=0, finish=3000000, window=100, hours=False):
    logging.debug("Loading timings from {}".format(path))
    tm = numpy.load(path)
    num_steps = min(tm['step'], finish)
    df = pandas.DataFrame({k : tm[k] for k in [y, 'time_step']})[start:num_steps]
    one_step = df['time_step'][-window:].median() / 3600.0
    print "Median time for one step is {} hours".format(one_step)
    if hours:
        df.index = (start + numpy.arange(0, df.index.shape[0])) * one_step
    return pandas.rolling_mean(df, window).iloc[window:] 
Example #10
Source File: evaluate.py    From NMT-Coverage with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_timings(path, args, y):
    logging.debug("Loading timings from {}".format(path))
    tm = numpy.load(path)
    num_steps = min(tm['step'], args.finish)
    df = pandas.DataFrame({k : tm[k] for k in [y, 'time_step']})[args.start:num_steps]
    one_step = df['time_step'].median() / 3600.0
    logging.debug("Median time for one step is {} hours".format(one_step))
    if args.hours:
        df.index = (args.start + numpy.arange(0, df.index.shape[0])) * one_step
    return pandas.rolling_mean(df, args.window).iloc[args.window:] 
Example #11
Source File: ta.py    From tia with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sma(arg, n):
    """ If n is 0 then return the ltd mean; else return the n day mean """
    if n == 0:
        return pd.expanding_mean(arg)
    else:
        return pd.rolling_mean(arg, n, min_periods=n) 
Example #12
Source File: ma_strategy.py    From stock with Apache License 2.0 5 votes vote down vote up
def select_Time_DMA(self):

        # DMA
        ma_close_short = self.df_close[self.COL_MA_S].get_values()
        ma_close_long = self.df_close[self.COL_MA_L].get_values()
        
        # #MA
        # ma_list = [self.AVR_SHORT, self.AVR_LONG]
        # ma_dea = 10
        #
        # if ma_list[0] == self.AVR_SHORT and ma_list[1] == self.AVR_LONG:
        #     ma_close_short = self.ma_short
        #     ma_close_long = self.ma_long
        # else:
        #     ma_close_short = pd.rolling_mean(self.close_price, ma_list[0])
        #     ma_close_long = pd.rolling_mean(self.close_price, ma_list[1])
        
        dma_price = ma_close_short - ma_close_long
        ama_price = pd.rolling_mean(dma_price, self.MA_DEA)
        
        signal = SIGNAL_DEFAULT
            
        if dma_price[-1] > dma_price[-2] and dma_price[-1] > ama_price[-1] \
                                            and dma_price[-2] < ama_price[-2]:
            signal = SIGNAL_BUY
        elif dma_price[-1] < dma_price[-2] and dma_price[-1] < ama_price[-1] \
                            and dma_price[-2] > ama_price[-2]:
            signal = SIGNAL_SALE           
        return signal            
        
     
    # TRIX指标择时 (回测) 
Example #13
Source File: ma_strategy.py    From stock with Apache License 2.0 5 votes vote down vote up
def select_Time_TRIX(self):
        
        #EMA
        ema_close_short = self.df_close[self.COL_EMA_S].get_values()
        ema_ema_close_short = pd.ewma(ema_close_short, span=self.AVR_SHORT)
        tr_close = pd.ewma(ema_ema_close_short, span=self.AVR_SHORT)

        # ma_list = [self.AVR_SHORT, self.AVR_SHORT] #N,M
        #
        # if ma_list[0] == self.AVR_SHORT:
        #     ema_close = self.ema_short
        # else:
        #     ema_close = pd.ewma(self.close_price, span=ma_list[0])
        # ema_close = pd.ewma(ema_close, span=ma_list[0])
        # tr_close = pd.ewma(ema_close, span=ma_list[0])
        
        trixsList = [0]
        for i in range(1, len(tr_close)):
            #print tr_close[i], tr_close[i-1]
            trix = (tr_close[i]-tr_close[i-1])/tr_close[i-1]*100
            trixsList.append(trix)
        trixs = np.array(trixsList)    
        maxtrix = pd.rolling_mean(trixs, self.AVR_LONG)
        
        signal = SIGNAL_DEFAULT
            
        if trixs[-1] > trixs[-2] and trixs[-1] > maxtrix[-1] \
                                            and trixs[-2] < maxtrix[-2]:
            signal = SIGNAL_BUY
        elif trixs[-1] < trixs[-2] and trixs[-1] < maxtrix[-1] \
                            and trixs[-2] > maxtrix[-2]:
            signal = SIGNAL_SALE            
        return signal
    
            
       
    
    # AMA指标择时 
Example #14
Source File: strategy_ma.py    From stock with Apache License 2.0 5 votes vote down vote up
def select_time_ma(df_closeprice, ma_short=12, ma_long=40):
    """
    MA指标择时(简单均线SMA)
    :param df_closeprice:  DataFrame, 收盘价
    :param ma_short:
    :param ma_long:
    :return:
    """

    #SMA
    df_closeprice['ma_close_short'] = pd.rolling_mean(df_closeprice['close_price'], ma_short)
    df_closeprice['ma_close_long'] = pd.rolling_mean(df_closeprice['close_price'], ma_long)


    df_closeprice['signal'] = 0

    for ix, row in df_closeprice.iterrows():
        pass


    # if ema_close_short[-1] > ema_close_short[-2] and ema_close_short[-1] > ema_close_long[-1] \
    #                     and ema_close_short[-2] < ema_close_long[-2]:
    #     signal = SIGNAL_BUY
    # elif ema_close_long[-1] < ema_close_long[-2] and ema_close_short[-1] < ema_close_long[-1] \
    #                     and ema_close_short[-2] > ema_close_long[-2]:
    #     signal = SIGNAL_SALE

    # return signal 
Example #15
Source File: macd_live_test.py    From stock with Apache License 2.0 5 votes vote down vote up
def select_Time_TRIX(self):
        
        #EMA
        ema_close_short = self.df_close[self.COL_EMA_S].get_values()
        ema_ema_close_short = pd.ewma(ema_close_short, span=self.AVR_SHORT)
        tr_close = pd.ewma(ema_ema_close_short, span=self.AVR_SHORT)

        # ma_list = [self.AVR_SHORT, self.AVR_SHORT] #N,M
        #
        # if ma_list[0] == self.AVR_SHORT:
        #     ema_close = self.ema_short
        # else:
        #     ema_close = pd.ewma(self.close_price, span=ma_list[0])
        # ema_close = pd.ewma(ema_close, span=ma_list[0])
        # tr_close = pd.ewma(ema_close, span=ma_list[0])
        
        trixsList = [0]
        for i in range(1, len(tr_close)):
            #print tr_close[i], tr_close[i-1]
            trix = (tr_close[i]-tr_close[i-1])/tr_close[i-1]*100
            trixsList.append(trix)
        trixs = np.array(trixsList)    
        maxtrix = pd.rolling_mean(trixs, self.AVR_LONG)
        
        signal = SIGNAL_DEFAULT
            
        if trixs[-1] > trixs[-2] and trixs[-1] > maxtrix[-1] \
                                            and trixs[-2] < maxtrix[-2]:
            signal = SIGNAL_BUY
        elif trixs[-1] < trixs[-2] and trixs[-1] < maxtrix[-1] \
                            and trixs[-2] > maxtrix[-2]:
            signal = SIGNAL_SALE            
        return signal
    
            
       
    
    # AMA指标择时 
Example #16
Source File: randomtestequitycurvetrading.py    From systematictradingexamples with GNU General Public License v2.0 5 votes vote down vote up
def apply_overlay(x, N_length, period_stdev, costs_SR=0):
    """
    apply an equity curve filter overlay
    
    x is a pd time series of returns
    
    N_length is the mav to apply
    
    Returns a new x with 'flat spots'
    
    """
    if N_length==NO_OVERLAY:
        return x

    cum_x=x.cumsum()
    mav_x=pd.rolling_mean(cum_x, N_length)
    filter_x=pd.TimeSeries([isbelow(cum_x, mav_x, idx) for idx in range(len(x))], x.index)
    
    ## can only apply with a lag (!)
    filtered_x=x*filter_x.shift(1)
    
    if costs_SR>0:
        ## apply costs
        ## first work out the turnover
        ## note everything is adjusted for the period we are in

        turnover=filter_x.diff().abs().mean()/2.0
        
        return_degrade=costs_SR*turnover
        filtered_x = filtered_x - return_degrade
    
    return filtered_x 
Example #17
Source File: compat.py    From jqfactor_analyzer with MIT License 5 votes vote down vote up
def rolling_mean(x, window, min_periods=None, center=False):
    if PD_VERSION >= '0.18.0':
        return x.rolling(window, min_periods=min_periods, center=center).mean()
    else:
        return pd.rolling_mean(
            x, window, min_periods=min_periods, center=center
        ) 
Example #18
Source File: technical_indicators.py    From binance-technical-algorithm with MIT License 5 votes vote down vote up
def sma(data, window):
        sma = pd.rolling_mean(data["lastprice"], window)
        return sma
   
#Eponential Moving Average 
Example #19
Source File: technical_indicators.py    From binance-technical-algorithm with MIT License 5 votes vote down vote up
def sma_ind(data, window):
        sma = pd.rolling_mean(data["lastprice"], window)
        sma_ratio = (data["lastprice"]/sma)-1
        sma_mean = pd.stats.moments.rolling_mean(sma_ratio,20)
        sma_std = pd.stats.moments.rolling_std(sma_ratio,20)
        sma_ub2 = sma_mean + (sma_std*2)
        sma_lb2 = sma_mean - (sma_std*2)
    
        if pd.Series(sma_ratio).lt(0) == True:
            sma_ind = (abs(sma_ratio)/abs(sma_lb2))*-100
        else:
            sma_ind = (sma_ratio/sma_ub2)*100
        return sma_ind

#Exponential Moving Average Volitility 
Example #20
Source File: technical_indicators.py    From binance-technical-algorithm with MIT License 5 votes vote down vote up
def ewma_ind(data, window):
        ewma = pd.ewma(data["lastprice"], span = window)
        ewma_ratio = (data["lastprice"]/ewma)-1
        ewma_mean = pd.stats.moments.rolling_mean(ewma_ratio,60)
        ewma_std = pd.stats.moments.rolling_std(ewma_ratio,60)
        ewma_ub2 = ewma_mean + (ewma_std*2)
        ewma_lb2 = ewma_mean - (ewma_std*2)

        if pd.Series(ewma_ratio).any() < 1:
            ewma_ind = (abs(ewma_ratio)/abs(ewma_lb2))*-100
        else:
            ewma_ind = (ewma_ratio/ewma_ub2)*100
        return ewma_ind
    
#MACD Line and Crossover 
Example #21
Source File: bollinger.py    From prophet with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def run(self, data, symbols, lookback, **kwargs):
        prices = data['prices'].copy()

        rolling_std = pd.rolling_std(prices, lookback)
        rolling_mean = pd.rolling_mean(prices, lookback)

        bollinger_values = (prices - rolling_mean) / (rolling_std)

        for s_key in symbols:
            prices[s_key] = prices[s_key].fillna(method='ffill')
            prices[s_key] = prices[s_key].fillna(method='bfill')
            prices[s_key] = prices[s_key].fillna(1.0)

        return bollinger_values 
Example #22
Source File: analysis.py    From deepAPI with MIT License 5 votes vote down vote up
def load_timings(path, y="cost2_p_expl", start=0, finish=3000000, window=100, hours=False):
    logging.debug("Loading timings from {}".format(path))
    tm = numpy.load(path)
    num_steps = min(tm['step'], finish)
    df = pandas.DataFrame({k : tm[k] for k in [y, 'time_step']})[start:num_steps]
    one_step = df['time_step'][-window:].median() / 3600.0
    print ("Median time for one step is {} hours".format(one_step))
    if hours:
        df.index = (start + numpy.arange(0, df.index.shape[0])) * one_step
    return pandas.rolling_mean(df, window).iloc[window:] 
Example #23
Source File: technical_indicator.py    From NowTrade with MIT License 5 votes vote down vote up
def results(self, data_frame):
        data_frame[self.value] = pd.rolling_mean(data_frame[self.data], self.period) 
Example #24
Source File: SMARecipe.py    From OpenTrader with GNU Lesser General Public License v3.0 5 votes vote down vote up
def dMakeIngredients(self, dFeeds):
        """
        dMakeIngredients takes a dictionary of feeds dFeeds
        with at least one key from lRequiredFeeds to work on.
        It returns a dictionary of ingredients with the keys in lRequiredIngredients
        and a copy of the config  that it used as the key dIngredientsConfig.
        """
        oC = self.oEnsureConfigObj()
        assert oC is not None
        iLongMa = oC['rLongMa']['iLongMa']
        iShortMa = oC['rShortMa']['iShortMa']
        bUseTalib = oC['rShortMa']['bUseTalib']

        self.vCheckRequiredFeeds(dFeeds)
        mFeedOhlc = dFeeds['mFeedOhlc']
        
        iBeginValid = max(iLongMa, iShortMa)-1
        iEndOhlc = len(mFeedOhlc)

        if bUseTalib:
            import talib
            aShortMA = talib.SMA(mFeedOhlc.O.values, timeperiod=iShortMa)
            aLongMA = talib.SMA(mFeedOhlc.O.values, timeperiod=iLongMa)
            rShortMa = pandas.Series(aShortMA, name='O',
                                     index=mFeedOhlc.O.index)
            rLongMa = pandas.Series(aLongMA, name='O',
                                    index=mFeedOhlc.O.index)
        else:
            rShortMa = pandas.rolling_mean(mFeedOhlc.O, iShortMa)
            rLongMa = pandas.rolling_mean(mFeedOhlc.O, iLongMa)

        rShortMa = rShortMa[iBeginValid:]
        rLongMa = rLongMa[iBeginValid:]
        mOhlc = mFeedOhlc[iBeginValid:]
        self.oOm.vAppendHdf('recipe/ingredients/rShortMa', rShortMa)
        self.oOm.vAppendHdf('recipe/ingredients/rLongMa', rLongMa)
        self.dIngredients = dict(rShortMa=rShortMa, rLongMa=rLongMa,
                                 mOhlc=mOhlc,
                                 dIngredientsConfig=dict(oC))
        return self.dIngredients 
Example #25
Source File: equitycountrymodels.py    From systematictradingexamples with GNU General Public License v2.0 5 votes vote down vote up
def get_div_yield(tickname, rawdata):
    price_data=rawdata[tickname+"_PRICE"]
    total_returns=rawdata[tickname+"_TR"]

    tr_return = get_monthly_tr(tickname, rawdata)
    price_return = (price_data / price_data.shift(1)) - 1.0
    div = tr_return - price_return
    div_tr = div * total_returns
    last_year_divs = pd.rolling_mean(div_tr, 12, min_periods=1)*12.0
    div_yield = last_year_divs / total_returns
    
    return div_yield 
Example #26
Source File: assetallocationmodel.py    From systematictradingexamples with GNU General Public License v2.0 5 votes vote down vote up
def yield_forecast_ts(data, vols):
    eqyield = data.SP_Yield
    bondyield = data.Bond_Yield
    
    eqreturn = eqyield / vols[0]
    bondreturn = bondyield / vols[1]

    eqreturn = eqreturn - pd.rolling_mean(eqreturn, 240, min_periods=1)
    bondreturn = bondreturn - pd.rolling_mean(bondreturn, 240, min_periods=1)


    diff = eqreturn - bondreturn
    
    return diff*3.0 
Example #27
Source File: yieldsprediction.py    From systematictradingexamples with GNU General Public License v2.0 5 votes vote down vote up
def get_div_yield(tickname, rawdata):
    price_data=rawdata[tickname+"_PRICE"]
    total_returns=rawdata[tickname+"_TR"]

    tr_return = get_monthly_tr(tickname, rawdata)
    price_return = (price_data / price_data.shift(1)) - 1.0
    div = tr_return - price_return
    div_tr = div * total_returns
    last_year_divs = pd.rolling_mean(div_tr, 12, min_periods=1)*12.0
    div_yield = last_year_divs / total_returns
    
    return div_yield 
Example #28
Source File: optimumrebalance3assets.py    From systematictradingexamples with GNU General Public License v2.0 5 votes vote down vote up
def get_div_yield(tickname, rawdata):
    price_data=rawdata[tickname+"_PRICE"]
    total_returns=rawdata[tickname+"_TR"]

    tr_return = get_monthly_tr(tickname, rawdata)
    price_return = (price_data / price_data.shift(1)) - 1.0
    div = tr_return - price_return
    div_tr = div * total_returns
    last_year_divs = pd.rolling_mean(div_tr, 12, min_periods=1)*12.0
    div_yield = last_year_divs / total_returns
    
    return div_yield 
Example #29
Source File: own_tech.py    From MultipleFactorRiskModel with MIT License 5 votes vote down vote up
def getEMA(close):
    '''
    calculate EMA value
    :param DataFrame close: close price
    :return: DataFrame EMA: EMA value
    '''
    print '''*************************************************************************************
    a kind WARNING from the programmer(not the evil interpreter) function getEMA:
    we have different values for n1,n2,n3 in test code and real code,because the sample file
    may not have sufficient rows for real n1,n2,n3,leading to empty matrix.So be careful of
    the value you choose
    **************************************************************************************
          '''
    # real n1,n2,n3
    n1 = 12
    n2 = 26
    n3 = 9
    # n1,n2,n3 for test
    # n1 = 3
    # n2 = 6
    # n3 = 5
    # calculate MA12
    MA12 = pd.rolling_mean(close, n1)
    # drop np.nan in the first (n1-1) rows
    MA12.dropna(inplace=True)
    # set index with 0,1,2...
    MA12.index = range(MA12.shape[0])
    MA26 = pd.rolling_mean(close, n2)
    MA26.dropna(inplace=True)
    MA26.index = range(MA26.shape[0])
    [row, col] = MA26.shape
    DIF = pd.DataFrame(MA12.iloc[(-row):, :].values) - MA26
    tmp = pd.rolling_mean(DIF, n3)
    tmp.dropna(inplace=True)
    tmp.index = range(tmp.shape[0])
    [row, col] = tmp.shape
    DIF = pd.DataFrame(DIF.iloc[(-row):, :].values)
    EMA = DIF - tmp
    return EMA 
Example #30
Source File: analysis.py    From LV_groundhog with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def load_timings(path, y="cost2_p_expl", start=0, finish=3000000, window=100, hours=False):
    logging.debug("Loading timings from {}".format(path))
    tm = numpy.load(path)
    num_steps = min(tm['step'], finish)
    df = pandas.DataFrame({k : tm[k] for k in [y, 'time_step']})[start:num_steps]
    one_step = df['time_step'][-window:].median() / 3600.0
    print "Median time for one step is {} hours".format(one_step)
    if hours:
        df.index = (start + numpy.arange(0, df.index.shape[0])) * one_step
    return pandas.rolling_mean(df, window).iloc[window:]