问题描述
我正在尝试在Python熊猫中或使用Cython为考夫曼自适应移动平均线(KAMA)创建函数(我已经在R& Rcpp中完成了此操作)。在递归计算时遇到问题,filt1
I am trying to create a function for the Kaufman Adaptive Moving Average (KAMA), in Python Pandas or using Cython (I have already done this in R & Rcpp). Am having problems with the recursive calculation, filt1
filt1[i] = ( filt1[i-1] + SC[i]*(price[i]-filt1[i-1]) )
我期待KAMA系列应该以
(i)NA开头,长度为n = 10
(ii)要启动KAMA,对于2010-01-19,价格的原始均值为1142.393,在这种情况下为收盘价
(iii)之后,递归公式filt1 [i]
I am expecting the KAMA Series should have(i) NA's to begin with, length of n=10(ii) To start KAMA, for 2010-01-19 the raw mean of the price 1142.393, in this case the mean of the close's(iii) Thereafter KAMA values from the recursive formulae filt1[i]
So:
KAMA
2010-01-04 NA
2010-01-05 NA
2010-01-06 NA
2010-01-07 NA
2010-01-08 NA
2010-01-11 NA
2010-01-12 NA
2010-01-13 NA
2010-01-14 NA
2010-01-15 NA
2010-01-19 1142.393
2010-01-20 1142.367
2010-01-21 1142.244
2010-01-22 1140.212
2010-01-25 1138.683
2010-01-26 1136.517
以
2013-12-24 1791.114
2013-12-26 1802.816
2013-12-27 1814.759
2013-12-30 1822.844
2013-12-31 1830.523
我已经开始了,
#%%
# Include this line for NEW WINDOW(S) for figures
%pylab qt4
# start with getting some data to test on
import datetime
import tradingWithPython as twp # main toolkit functions
import tradingWithPython.lib.yahooFinance as yf # yahoo finance module
import tradingWithPython.lib.backtest as backtest
from tradingWithPython.lib.extra import ProgressBar # import progress bar
#The python module (talib) that I will be using to calculate the technical
#indicators is a wrapper around the open source TA-Lib.
import talib
import numpy as np
import pandas.io.data as web
import pandas.stats.moments
import pandas as pd
#pd.set_option('html', False) # how to display data - DEFAULT is True
#pd.set_option('display.height', int(1e7))
pd.set_option('display.max_rows', int(1e7))
#pd.set_option('display.max_columns', int(1e7))
pd.set_option('display.width', 3000)
#%%
#%%
def KAMA(x, n=10, pow1=2, pow2=30):
''' kama indicator '''
''' accepts pandas dataframe of prices '''
d['absDiffx'] = abs(x - x.shift(1) )
d['ER.num'] = ( x - x.shift(n) )
d['ER.den'] = pandas.stats.moments.rolling_sum(d['absDiffx'],n)
d['ER'] = d['ER.num'] / d['ER.den']
d['SC'] = ( d['ER']*(2.0/(pow1+1)-2.0/(pow2+1.0))+2/(pow2+1.0) ) ** 2.0
return d['SC']
#%%
#%%
#Download data from yahoo finance
start = datetime.datetime(2010,1,1)
end = datetime.datetime(2013,12,31)
ticker = "^GSPC"
d=web.DataReader(ticker,'yahoo',start,end)
d.info()
#<class 'pandas.core.frame.DataFrame'>
#DatetimeIndex: 1006 entries, 2010-01-04 00:00:00 to 2013-12-31 00:00:00
#Data columns (total 6 columns):
#Open 1006 non-null float64
#High 1006 non-null float64
#Low 1006 non-null float64
#Close 1006 non-null float64
#Volume 1006 non-null int64
#Adj Close 1006 non-null float64
type(d)
#pandas.core.frame.DataFrame
d.head()
d.tail()
#%%
#%%
#calculate KAMA
#---------------
kama = KAMA(d.Close, n=10, pow1=2, pow2=30)
type(kama)
#pandas.core.frame.DataFrame
kama.head(100)
kama.tail(10)
#%%
#%%
df = pd.DataFrame({'price':d.Close, 'KAMA':KAMA(d.Close, n=10, pow1=2, pow2=30) })
df.plot(subplots=True)
#%%
如何在熊猫内或使用Cython计算filt1 [i],结果作为熊猫数据框?非常感谢。
How to do I calculate filt1[i] within Pandas or using Cython, with result as a pandas dataframe? Many Thanks.
推荐答案
感谢您的答复。
#%%
def KAMA(price, n=10, pow1=2, pow2=30):
''' kama indicator '''
''' accepts pandas dataframe of prices '''
absDiffx = abs(price - price.shift(1) )
ER_num = abs( price - price.shift(n) )
ER_den = pandas.stats.moments.rolling_sum(absDiffx,n)
ER = ER_num / ER_den
sc = ( ER*(2.0/(pow1+1)-2.0/(pow2+1.0))+2/(pow2+1.0) ) ** 2.0
answer = np.zeros(sc.size)
N = len(answer)
first_value = True
for i in range(N):
if sc[i] != sc[i]:
answer[i] = np.nan
else:
if first_value:
answer[i] = price[i]
first_value = False
else:
answer[i] = answer[i-1] + sc[i] * (price[i] - answer[i-1])
return answer
#%%
#%%
#calculate KAMA
#---------------
kama = KAMA(d.Close, n=10, pow1=2, pow2=30)
kama
#%%
这篇关于Python pandas 考夫曼自适应移动平均值(KAMA)--- pandas 或Cython中的递归计算的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!