本文整理匯總了Python中talib.ATR屬性的典型用法代碼示例。如果您正苦於以下問題:Python talib.ATR屬性的具體用法?Python talib.ATR怎麽用?Python talib.ATR使用的例子?那麽, 這裏精選的屬性代碼示例或許可以為您提供幫助。您也可以進一步了解該屬性所在類talib
的用法示例。
在下文中一共展示了talib.ATR屬性的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _getAtrExtreme
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def _getAtrExtreme(cls, highs, lows, closes, atrPeriod=14, slowPeriod=30, fastPeriod=3):
"""
獲取TTI ATR Exterme通道, which is based on 《Volatility-Based Technical Analysis》
TTI is 'Trading The Invisible'
@return: fasts, slows
"""
# talib 的源碼,它的 ATR 不是 N 日簡單平均,而是類似 EMA 的方法計算的指數平均
atr = talib.ATR(highs, lows, closes, timeperiod=atrPeriod)
highsMean = talib.EMA(highs, 5)
lowsMean = talib.EMA(lows, 5)
closesMean = talib.EMA(closes, 5)
atrExtremes = np.where(closes > closesMean,
((highs - highsMean)/closes * 100) * (atr/closes * 100),
((lows - lowsMean)/closes * 100) * (atr/closes * 100)
)
fasts = talib.MA(atrExtremes, fastPeriod)
slows = talib.EMA(atrExtremes, slowPeriod)
return fasts, slows, np.std(atrExtremes[-slowPeriod:])
示例2: getAtrRatio
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def getAtrRatio(df, period=14):
"""
平均波動率:ATR(14)/MA(14)
"""
highs = df['high']
lows = df['low']
closes = df['close']
atr = talib.ATR(highs, lows, closes, timeperiod=period)
ma = talib.MA(closes, timeperiod=period)
volatility = atr/ma
s = pd.Series(volatility, index=df.index, name='volatility').dropna()
return s
示例3: atr
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def atr(candles: np.ndarray, period=14, sequential=False) -> Union[float, np.ndarray]:
"""
ATR - Average True Range
:param candles: np.ndarray
:param period: int - default=14
:param sequential: bool - default=False
:return: float | np.ndarray
"""
if not sequential and len(candles) > 240:
candles = candles[-240:]
res = talib.ATR(candles[:, 3], candles[:, 4], candles[:, 2], timeperiod=period)
if sequential:
return res
else:
return None if np.isnan(res[-1]) else res[-1]
示例4: compute_average_true_ranges
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def compute_average_true_ranges(context):
"""
Compute average true ranges, or N.
"""
if context.is_debug:
start_time = time()
rolling_window = 21
moving_average = 20
for market in context.prices.items:
context.average_true_range[market] = ATR(
context.prices[market].high[-rolling_window:],
context.prices[market].low[-rolling_window:],
context.prices[market].close[-rolling_window:],
timeperiod=moving_average
)[-1]
if context.is_test:
assert(len(context.average_true_range) > 0)
if context.is_debug:
time_taken = (time() - start_time) * 1000
log.debug('Executed in %f ms.' % time_taken)
assert(time_taken < 1024)
示例5: GetPrice
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def GetPrice(self, position_type = MarketTrend.ENTER_LONG):
if (not self.SeenEnoughData()):
return 0.0
high = numpy.array(self._high, dtype=float)
low = numpy.array(self._low, dtype=float)
close = numpy.array(self._close, dtype=float)
ATR = talib.ATR(high, low, close, timeperiod=self.period-1)[-1]
stop_price = self._close[-1]
if ( position_type == MarketTrend.ENTER_LONG ):
stop_price -= 2.0*ATR
elif ( position_type == MarketTrend.ENTER_SHORT ):
stop_price += 2.0*ATR
else:
stop_price = 0.0
return stop_price
示例6: GetPrice
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def GetPrice(self, position_type = MarketTrend.ENTER_LONG):
if (not self.SeenEnoughData()):
return 0.0
high = numpy.array(self._high, dtype=float)
low = numpy.array(self._low, dtype=float)
close = numpy.array(self._close, dtype=float)
ATR = talib.ATR(high, low, close, timeperiod=self.period-1)[-1]
takeprofit_price = self._close[-1]
if ( position_type == MarketTrend.ENTER_LONG ):
takeprofit_price += 1.0*ATR
elif ( position_type == MarketTrend.ENTER_SHORT ):
takeprofit_price -= 1.0*ATR
else:
takeprofit_price = 0.0
return takeprofit_price
示例7: GetPrice
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def GetPrice(self, position_type = MarketTrend.ENTER_LONG):
if (not self.SeenEnoughData()):
return 0.0
high = numpy.array(self._high, dtype=float)
low = numpy.array(self._low, dtype=float)
close = numpy.array(self._close, dtype=float)
ATR = talib.ATR(high, low, close, timeperiod=self.period-1)[-1]
if ( position_type == MarketTrend.ENTER_LONG ):
stop_price = self.peak_price - 1.1 * ATR
elif ( position_type == MarketTrend.ENTER_SHORT ):
stop_price = self.peak_price + 1.1 * ATR
else:
stop_price = 0.0
return stop_price
示例8: _calc_atr_from_ta
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def _calc_atr_from_ta(high, low, close, time_period=14):
"""
使用talib計算atr,即透傳talib.ATR計算結果
:param high: 最高價格序列,pd.Series或者np.array
:param low: 最低價格序列,pd.Series或者np.array
:param close: 收盤價格序列,pd.Series或者np.array
:param time_period: atr的N值默認值14,int
:return: atr值序列,np.array對象
"""
import talib
if isinstance(high, pd.Series):
high = high.values
if isinstance(low, pd.Series):
low = low.values
if isinstance(close, pd.Series):
close = close.values
atr = talib.ATR(high, low, close, timeperiod=time_period)
return atr
示例9: getAtrExtreme
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def getAtrExtreme(df, atrPeriod=14, emaPeriod=30, stdPeriod=30, atrExtremeFastPeriod=3, dropna=True):
"""
獲取TTI ATR Exterme通道, which is based on 《Volatility-Based Technical Analysis》
TTI is 'Trading The Invisible'
@atrPeriod: ATR N日平均
@emaPeriod: 移動指數均線周期
@stdPeriod: ATR Extermes的標準差周期
@atrExtremeFastPeriod: ATR Extermes快速簡單均線周期
@return: DF
"""
highs = df['high'].values
lows = df['low'].values
closes = df['close'].values
# talib 的源碼,它的 ATR 不是 N 日簡單平均,而是類似 EMA 的方法計算的指數平均
atr = talib.ATR(highs, lows, closes, timeperiod=atrPeriod)
emaDf = df.ewm(span=emaPeriod).mean()
atrExtremes = np.where(closes > emaDf['close'].values,
((highs - emaDf['high'].values)/closes * 100) * (atr/closes * 100),
((lows - emaDf['low'].values)/closes * 100) * (atr/closes * 100)
)
atrExtremeSeries = pd.Series(atrExtremes)
emaAtrExtremes = atrExtremeSeries.ewm(span=emaPeriod).mean().values
stdAtrExtremes = atrExtremeSeries.rolling(center=False, window=stdPeriod).std().values
maAtrExtremes = atrExtremeSeries.rolling(center=False, window=atrExtremeFastPeriod).mean().values
atrExtremeDf = pd.DataFrame(data={'ema': emaAtrExtremes, 'std': stdAtrExtremes, 'ma': maAtrExtremes},
index=df.index
)
return atrExtremeDf.dropna() if dropna else atrExtremeDf
示例10: __init__
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def __init__(self, ctaEngine, info, state, strategyParam=None):
super().__init__(ctaEngine, info, state, strategyParam)
if strategyParam is None: # 實盤參數
pass
else: # 回測參數
self._atrPeriod = self._strategyParam['ATR周期']
self._fastPeriod = self._strategyParam['快速周期']
self._slowPeriod = self._strategyParam['慢速周期']
self._stdCoef = self._strategyParam['標準差係數']
self._curInit()
示例11: prepare
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def prepare(cls, date, dataEngine, info, codes=None, errorDataEngine=None, backTestingContext=None):
code = DyST_IntraDayT.targetCode
if backTestingContext is not None:
atrPeriod = backTestingContext.strategyParam['ATR周期']
fastPeriod = backTestingContext.strategyParam['快速周期']
slowPeriod = backTestingContext.strategyParam['慢速周期']
else:
atrPeriod = cls.atrPeriod
fastPeriod = cls.fastPeriod
slowPeriod = cls.slowPeriod
barSize = int(DyST_IntraDayT.barMode[3:-1])
oneDayBarLen = math.ceil(4*60/barSize)
dayNbr = math.ceil(DyST_IntraDayT.bufSize/oneDayBarLen)
ticksEngine = dataEngine.ticksEngine
if not ticksEngine.loadCodeN(code, [date, -dayNbr]):
return None
daysDf = ticksEngine.getDaysDataFrame(code)
tickDf = ticksEngine.getDataFrame(code, adj=True, continuous=True)
barDf = DyStockDataUtility.getIntraDayBars(tickDf, str(barSize) + 'min')
highs = barDf['high'].values[-DyST_IntraDayT.bufSize:]
lows = barDf['low'].values[-DyST_IntraDayT.bufSize:]
closes = barDf['close'].values[-DyST_IntraDayT.bufSize:]
fasts, slows, std = DyST_IntraDayT._getAtrExtreme(highs, lows, closes, atrPeriod=atrPeriod, slowPeriod=slowPeriod, fastPeriod=fastPeriod)
return {'highs': {code: highs}, 'lows': {code: lows}, 'closes': {code: closes}, 'preFast': {code: fasts[-1]}, 'preSlow': {code: slows[-1]}, 'preClose': {code: daysDf.ix[-1, 'close']}}
示例12: ATR
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def ATR(DataFrame, N=14):
res = talib.ATR(DataFrame.high.values, DataFrame.low.values, DataFrame.close.values, N)
return pd.DataFrame({'ATR': res}, index=DataFrame.index)
示例13: atr
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def atr(self, sym, frequency, period=14):
if not self.kbars_ready(sym, frequency):
return []
highs = self.high(sym, frequency)
lows = self.low(sym, frequency)
closes = self.close(sym, frequency)
atr_index = ta.ATR(highs, lows, closes, timeperiod=period)
return atr_index
示例14: test_indicator_ATR
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def test_indicator_ATR(self):
n = 5
result = ATR(df, n)
isinstance(result, pd.DataFrame)
expected = talib.ATR(df['High'].values, df['Low'].values, df['Close'].values, timeperiod=n)
np.testing.assert_almost_equal(result, expected[1::])
示例15: __str__
# 需要導入模塊: import talib [as 別名]
# 或者: from talib import ATR [as 別名]
def __str__(self):
return 'ATR(symbol=%s, period=%s)' %(self.symbol, self.period)