当前位置: 首页>>代码示例>>Python>>正文


Python pandas.ewma方法代码示例

本文整理汇总了Python中pandas.ewma方法的典型用法代码示例。如果您正苦于以下问题:Python pandas.ewma方法的具体用法?Python pandas.ewma怎么用?Python pandas.ewma使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在pandas的用法示例。


在下文中一共展示了pandas.ewma方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: main

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('files', metavar='filename', type=str, nargs='*')
    args = parser.parse_args()
    args = vars(args)

    files = args['files']

    assert len(files) == 2

    targets_df = pd.read_csv(files[0], header=0, index_col=False)
    predict_df = pd.read_csv(files[1], header=0, index_col=False)

    column = targets_df.columns[1]

    targets = targets_df.as_matrix(columns=[column])

    #predict_df[column] = pd.ewma(predict_df[column], com=1, adjust=False)
    predictions = predict_df.as_matrix(columns=[column])

    rmse, mse = calc_rmse(predictions, targets)
    print("RMSE: %f, MSE: %f" % (rmse, mse)) 
开发者ID:rwightman,项目名称:tensorflow-litterbox,代码行数:24,代码来源:compare_csv.py

示例2: four_losses_draw

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def four_losses_draw(losses, names, title):
    """ Draw two graphs. First - last 100 iterations. Second - all iterations.

    Parameters
    ----------
    losses : list
        loss values

    names : list
        names of loss

    title : str
        title to graph
    """
    _, axis = plt.subplots(1, 2)
    for loss, name in zip(losses, names):
        axis[0].plot(loss[-100:], label='%s'%name)
        axis[0].plot(pd.ewma(np.array(loss[-100:]), span=10, adjust=False), label='%s'%name)
        axis[1].plot(loss, label='%s'%name)
        axis[1].plot(pd.ewma(np.array(loss), span=10, adjust=False), label='%s'%name)

    axis[0].set_title(title)
    axis[0].legend()
    axis[1].legend()
    plt.show() 
开发者ID:analysiscenter,项目名称:batchflow,代码行数:27,代码来源:utils.py

示例3: select_Time_MACD

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def select_Time_MACD(self):
        
        #EMA
        # print self.df_close.tail()
        ema_close_short = self.df_close[self.COL_EMA_S].get_values()
        ema_close_long = self.df_close[self.COL_EMA_L].get_values()

        
        dif_price = ema_close_short - ema_close_long
        dea_price = pd.ewma(dif_price, span=self.MA_DEA)
        macd_price = 2 * (dif_price - dea_price)
        
        signal = SIGNAL_DEFAULT
            
        if dif_price[-1] > dif_price[-2] and dif_price[-1] > dea_price[-2] \
                                            and dif_price[-2] < dea_price[-2] and dea_price[-1] > 0:
            signal = SIGNAL_BUY
        elif dif_price[-1] < dif_price[-2] and dif_price[-1] < dea_price[-1] \
                            and dif_price[-2] > dea_price[-2] and dif_price[-1] < 0:
            signal = SIGNAL_SALE            
        return signal            
    
    # DMA指标择时 (回测) 
开发者ID:cbbing,项目名称:stock,代码行数:25,代码来源:ma_strategy.py

示例4: calcute_ma

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
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 
开发者ID:cbbing,项目名称:stock,代码行数:21,代码来源:ma_strategy.py

示例5: calcute_ma

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
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 
开发者ID:cbbing,项目名称:stock,代码行数:22,代码来源:data_calcute.py

示例6: ewma_ind

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
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 
开发者ID:Jacyle,项目名称:binance-technical-algorithm,代码行数:17,代码来源:technical_indicators.py

示例7: calc_ewmac_forecast

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def calc_ewmac_forecast(price, Lfast, Lslow=None, usescalar=True):
    
    
    """
    Calculate the ewmac trading fule forecast, given a price and EWMA speeds Lfast, Lslow and vol_lookback
    
    Assumes that 'price' is daily data
    """
    ## price: This is the stitched price series
    ## We can't use the price of the contract we're trading, or the volatility will be jumpy
    ## And we'll miss out on the rolldown. See http://qoppac.blogspot.co.uk/2015/05/systems-building-futures-rolling.html

    if Lslow is None:
        Lslow=4*Lfast
    
    ## We don't need to calculate the decay parameter, just use the span directly
    
    fast_ewma=pd.ewma(price, span=Lfast)
    slow_ewma=pd.ewma(price, span=Lslow)
    raw_ewmac=fast_ewma - slow_ewma
    
    ## volatility adjustment
    stdev_returns=volatility(price)    
    vol_adj_ewmac=raw_ewmac/stdev_returns
    
    ## scaling adjustment
    if usescalar:
        f_scalar=ewmac_forecast_scalar(Lfast, Lslow)
        forecast=vol_adj_ewmac*f_scalar
    else:
        forecast=vol_adj_ewmac
    
    cap_forecast=cap_series(forecast, capmin=-20.0,capmax=20.0)
    
    return cap_forecast 
开发者ID:robcarver17,项目名称:systematictradingexamples,代码行数:37,代码来源:tradingrules.py

示例8: draw_avgpooling

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def draw_avgpooling(maps, answers, axis=None, span=350, model=True):
    """ Draw maps from GAP

    Parameters
    ----------
    maps : np.array
        all maps from GAP layers

    answers : np.array
        answers to all maps

    span : float, optional
        Specify decay in terms of span

    axis : list, optional
        sets the min and max of the x and y axes, with ``[xmin, xmax, ymin, ymax]``

    model : bool, optional
        se resnet or simple resnet
    """
    axis = [0, 2060, 0, 1] if axis is None else axis
    col = sns.color_palette("Set2", 8) + sns.color_palette(["#9b59b6", "#3498db"])

    indices = np.array([np.where(answers == i)[0] for i in range(10)])

    filters = np.array([np.mean(maps[indices[i]], axis=0).reshape(-1) for i in range(10)])
    for i in range(10):
        plt.plot(pd.ewma(filters[i], span=span, adjust=False), color=col[i], label=str(i))

    plt.title("Distribution of average pooling in "+("SE ResNet" if model else 'simple ResNet'))
    plt.legend(fontsize=16, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    plt.ylabel('Activation value', fontsize=18)
    plt.xlabel('Future map index', fontsize=18)
    plt.axis(axis)
    plt.show() 
开发者ID:analysiscenter,项目名称:batchflow,代码行数:37,代码来源:utils.py

示例9: rolling_weighted_mean

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def rolling_weighted_mean(series, window=200, min_periods=None):
    min_periods = window if min_periods is None else min_periods
    try:
        return series.ewm(span=window, min_periods=min_periods).mean()
    except Exception as e:  # noqa: F841
        return pd.ewma(series, span=window, min_periods=min_periods)


# --------------------------------------------- 
开发者ID:freqtrade,项目名称:technical,代码行数:11,代码来源:indicators.py

示例10: ema

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def ema(f, c, p = 20):
    r"""Calculate the mean on a rolling basis.

    Parameters
    ----------
    f : pandas.DataFrame
        Dataframe containing the column ``c``.
    c : str
        Name of the column in the dataframe ``f``.
    p : int
        The period over which to calculate the rolling mean.

    Returns
    -------
    new_column : pandas.Series (float)
        The array containing the new feature.

    References
    ----------
    *An exponential moving average (EMA) is a type of moving average
    that is similar to a simple moving average, except that more weight
    is given to the latest data* [IP_EMA]_.

    .. [IP_EMA] http://www.investopedia.com/terms/e/ema.asp

    """
    new_column = pd.ewma(f[c], span=p)
    return new_column


#
# Function extract_bizday
# 
开发者ID:ScottfreeLLC,项目名称:AlphaPy,代码行数:35,代码来源:transforms.py

示例11: ema

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def ema(arg, n):
    if n == 0:
        return pd.ewma(arg, span=len(arg), min_periods=1)
    else:
        return pd.ewma(arg, span=n, min_periods=n) 
开发者ID:bpsmith,项目名称:tia,代码行数:7,代码来源:ta.py

示例12: rolling_weighted_mean

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def rolling_weighted_mean(series, window=200, min_periods=None):
    min_periods = window if min_periods is None else min_periods
    try:
        return series.ewm(span=window, min_periods=min_periods).mean()
    except Exception as e:
        return pd.ewma(series, span=window, min_periods=min_periods)


# --------------------------------------------- 
开发者ID:ranaroussi,项目名称:qtpylib,代码行数:11,代码来源:indicators.py

示例13: select_Time_TRIX

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
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指标择时 
开发者ID:cbbing,项目名称:stock,代码行数:40,代码来源:ma_strategy.py

示例14: processEMA

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
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)   
    
# 自适应均线 
开发者ID:cbbing,项目名称:stock,代码行数:32,代码来源:macd_back_test.py

示例15: stats_MA_only

# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import ewma [as 别名]
def stats_MA_only(self, market, exch_use, period = '1h', maperiod = 10, nentries = 100000, tail = 10, short_flag = False,
        b_test = None, ma_calc = 'simple'):

        nentries = self.get_nentries(period)

        if not self.using_data_source:
            # Added for cases when we have a different reference exchange / market for calculating the TD
            filename = self.filename_define(market, exch_use)
            transactions = self.read_transactions(filename, nentries, b_test)
            if transactions is None:
                return None
        # if bars are provided, e.g. for traditional markets
        else:
            transactions = self.source_snapshot(b_test.time()).tail(nentries).copy()

        # Base for starting time
        self.price_base = self.get_period(period, b_test)
        bars = self.transaction_resample(transactions, b_test, period, remove_nans = self.is_traditional(exch_use))
        del transactions

        # Calculate the MA values
        ma_df = bars['close']   # why not working for simple ma for oanda?

        if ma_calc == 'simple':
            ma_rolling = ma_df.rolling(window=maperiod, min_periods=maperiod).mean()
        else:
            ma_rolling = pd.ewma(ma_df, span=maperiod)

        # Memory cleaning
        del bars
        gc.collect()
        ### ended cleanup

        return ma_rolling
        
    ### Returning the max or min of last N candles for specific period 
开发者ID:illi4,项目名称:Crypto_trading_robot,代码行数:38,代码来源:tdlib.py


注:本文中的pandas.ewma方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。