本文整理汇总了Python中pandas.rolling_mean方法的典型用法代码示例。如果您正苦于以下问题:Python pandas.rolling_mean方法的具体用法?Python pandas.rolling_mean怎么用?Python pandas.rolling_mean使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类pandas
的用法示例。
在下文中一共展示了pandas.rolling_mean方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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]
示例2: relative_ts_div_predictor
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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
示例3: calcute_ma
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [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
示例4: calcute_ma
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [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
示例5: _pd_rolling
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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))
示例6: sample_532
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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()
示例7: dMakeIngredients
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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
示例8: apply_overlay
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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
示例9: get_div_yield
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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
示例10: yield_forecast_ts
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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
示例11: getEMA
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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
示例12: load_timings
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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:]
示例13: load_timings
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
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:]
示例14: results
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
def results(self, data_frame):
y_value = data_frame[self.y_data]
x_value = data_frame[self.x_data]
if self.lookback >= len(x_value):
return ([self.value, self.hedge_ratio, self.spread, self.zscore], \
[pd.Series(np.nan), pd.Series(np.nan), pd.Series(np.nan), pd.Series(np.nan)])
ols_result = pd.ols(y=y_value, x=x_value, window=self.lookback)
hedge_ratio = ols_result.beta['x']
spread = y_value - hedge_ratio * x_value
data_frame[self.value] = ols_result.resid
data_frame[self.hedge_ratio] = hedge_ratio
data_frame[self.spread] = spread
data_frame[self.zscore] = (spread - \
pd.rolling_mean(spread, self.lookback)) / \
pd.rolling_std(spread, self.lookback)
示例15: test_multiple_talib_with_args
# 需要导入模块: import pandas [as 别名]
# 或者: from pandas import rolling_mean [as 别名]
def test_multiple_talib_with_args(self):
zipline_transforms = [ta.MA(timeperiod=10),
ta.MA(timeperiod=25)]
talib_fn = talib.abstract.MA
algo = TALIBAlgorithm(talib=zipline_transforms, identifiers=[0])
algo.run(self.source)
# Test if computed values match those computed by pandas rolling mean.
sid = 0
talib_values = np.array([x[sid] for x in
algo.talib_results[zipline_transforms[0]]])
np.testing.assert_array_equal(talib_values,
pd.rolling_mean(self.panel[0]['price'],
10).values)
talib_values = np.array([x[sid] for x in
algo.talib_results[zipline_transforms[1]]])
np.testing.assert_array_equal(talib_values,
pd.rolling_mean(self.panel[0]['price'],
25).values)
for t in zipline_transforms:
talib_result = np.array(algo.talib_results[t][-1])
talib_data = dict()
data = t.window
# TODO: Figure out if we are clobbering the tests by this
# protection against empty windows
if not data:
continue
for key in ['open', 'high', 'low', 'volume']:
if key in data:
talib_data[key] = data[key][0].values
talib_data['close'] = data['price'][0].values
expected_result = talib_fn(talib_data, **t.call_kwargs)[-1]
np.testing.assert_allclose(talib_result, expected_result)