本文整理汇总了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)