本文整理汇总了Python中talib.SMA属性的典型用法代码示例。如果您正苦于以下问题:Python talib.SMA属性的具体用法?Python talib.SMA怎么用?Python talib.SMA使用的例子?那么恭喜您, 这里精选的属性代码示例或许可以为您提供帮助。您也可以进一步了解该属性所在类talib
的用法示例。
在下文中一共展示了talib.SMA属性的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def main():
basepath = os.path.dirname(__file__)
filename = os.path.join(basepath, "..", "data", "AAPL_GOOGL_IBM_20140101_20141201.xls")
d = pd.read_excel(filename, sheetname=None)
panel = pd.Panel.from_dict(d)
#print(panel.loc['Open','2014-02-03','AAPL'])
panel = panel.iloc[:,1:,:]
panel.major_axis.name = "Date"
#print(panel)
df = panel.loc[:,:,'AAPL']
#print(df)
result = SMA(df['Close'].values, timeperiod=4) # Function API
#result = SMA(df, timeperiod=4, price='Close') # Abstract API
print(result)
示例2: ema
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def ema(dataframe, period, field='close'):
import talib.abstract as ta
return ta.EMA(dataframe, timeperiod=period, price=field)
# HT_TRENDLINE Hilbert Transform - Instantaneous Trendline
# KAMA Kaufman Adaptive Moving Average
# MA Moving average
# MAMA MESA Adaptive Moving Average
# MAVP Moving average with variable period
# MIDPOINT MidPoint over period
# MIDPRICE Midpoint Price over period
# SAR Parabolic SAR
# SAREXT Parabolic SAR - Extended
# SMA Simple Moving Average
示例3: osc
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def osc(dataframe, periods=14) -> ndarray:
"""
1. Calculating DM (i).
If HIGH (i) > HIGH (i - 1), DM (i) = HIGH (i) - HIGH (i - 1), otherwise DM (i) = 0.
2. Calculating DMn (i).
If LOW (i) < LOW (i - 1), DMn (i) = LOW (i - 1) - LOW (i), otherwise DMn (i) = 0.
3. Calculating value of OSC:
OSC (i) = SMA (DM, N) / (SMA (DM, N) + SMA (DMn, N)).
:param dataframe:
:param periods:
:return:
"""
df = dataframe
df['DM'] = (df['high'] - df['high'].shift()).apply(lambda x: max(x, 0))
df['DMn'] = (df['low'].shift() - df['low']).apply(lambda x: max(x, 0))
return Series.rolling_mean(df.DM, periods) / (
Series.rolling_mean(df.DM, periods) + Series.rolling_mean(df.DMn, periods))
示例4: vwmacd
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def vwmacd(candles: np.ndarray, fastperiod=12, slowperiod=26, signalperiod=9, sequential=False) -> VWMACD:
"""
VWMACD - Volume Weighted Moving Average Convergence/Divergence
:param candles: np.ndarray
:param fastperiod: int - default: 12
:param slow_period: int - default: 26
:param signal_period: int - default: 9
:param sequential: bool - default: False
:return: VWMACD(macd, signal, hist)
"""
if not sequential and len(candles) > 240:
candles = candles[-240:]
vwma_slow = talib.SMA(candles[:, 2] * candles[:, 5], slowperiod) / talib.SMA(candles[:, 5], slowperiod)
vwma_fast = talib.SMA(candles[:, 2] * candles[:, 5], fastperiod) / talib.SMA(candles[:, 5], fastperiod)
vwmacd = vwma_fast - vwma_slow
signal = talib.EMA(vwmacd, signalperiod)
hist = vwmacd - signal
if sequential:
return VWMACD(vwmacd, signal, hist)
else:
return VWMACD(vwmacd[-1], signal[-1], hist[-1])
示例5: acosc
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def acosc(candles: np.ndarray, sequential=False) -> AC:
"""
Acceleration / Deceleration Oscillator (AC)
:param candles: np.ndarray
:param sequential: bool - default=False
:return: AC(osc, change)
"""
if not sequential and len(candles) > 240:
candles = candles[-240:]
med = talib.MEDPRICE(candles[:, 3], candles[:, 4])
ao = talib.SMA(med, 5) - talib.SMA(med, 34)
res = ao - talib.SMA(ao, 5)
mom = talib.MOM(res, timeperiod=1)
if sequential:
return AC(res, mom)
else:
return AC(res[-1], mom[-1])
示例6: sma
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def sma(candles: np.ndarray, period=5, source_type="close", sequential=False) -> Union[float, np.ndarray]:
"""
SMA - Simple Moving Average
:param candles: np.ndarray
:param period: int - default: 5
:param source_type: str - default: "close"
:param sequential: bool - default=False
:return: float | np.ndarray
"""
if not sequential and len(candles) > 240:
candles = candles[-240:]
source = get_candle_source(candles, source_type=source_type)
res = talib.SMA(source, timeperiod=period)
return res if sequential else res[-1]
示例7: ao
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def ao(candles: np.ndarray, sequential=False) -> AO:
"""
Awesome Oscillator
:param candles: np.ndarray
:param sequential: bool - default=False
:return: AO(osc, change)
"""
if not sequential and len(candles) > 240:
candles = candles[-240:]
med = talib.MEDPRICE(candles[:, 3], candles[:, 4])
res = talib.SMA(med, 5) - talib.SMA(med, 34)
mom = talib.MOM(res, timeperiod=1)
if sequential:
return AO(res, mom)
else:
return AO(res[-1], mom[-1])
示例8: isBuy
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def isBuy(context, analysis):
# Bullish SMA Crossover
if (getLast(analysis, 'sma_test') == 1):
# Bullish MACD
if (getLast(analysis, 'macd_test') == 1):
return True
# # Bullish Stochastics
# if(getLast(analysis, 'stoch_over_sold') == 1):
# return True
# # Bullish RSI
# if(getLast(analysis, 'rsi_over_sold') == 1):
# return True
return False
示例9: isSell
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def isSell(context, analysis):
# Bearish SMA Crossover
if (getLast(analysis, 'sma_test') == 0):
# Bearish MACD
if (getLast(analysis, 'macd_test') == 0):
return True
# # Bearish Stochastics
# if(getLast(analysis, 'stoch_over_bought') == 0):
# return True
# # Bearish RSI
# if(getLast(analysis, 'rsi_over_bought') == 0):
# return True
return False
示例10: handle_bar
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def handle_bar(context, bar_dict):
prices = history_bars(context.algoInfo, context.SHORTPERIOD+1, '1d', 'close')
short_avg = talib.SMA(prices, context.SHORTPERIOD)
plot("short avg", short_avg[-1])
cur_position = context.portfolio.positions[context.algoInfo].quantity
shares = context.portfolio.cash/bar_dict[context.algoInfo].close
if short_avg[-1] > prices[-1] and short_avg[-2] < prices[-2] and cur_position > 0:
order_target_value(context.algoInfo, 0)
if short_avg[-1] < prices[-1] > 0 and short_avg[-2] > prices[-2]:
order_shares(context.algoInfo, shares)
示例11: stoploss
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def stoploss(context, bar_dict):
if context.trend != 'up':
return
if context.positionIndex == 1:
prices = history_bars(context.stocks[1], 21, "1d", "close")
elif context.positionIndex == 2:
prices = history_bars(context.stocks[2], 21, "1d", "close")
else:
return
short_avg = talib.SMA(prices, 20)
if prices[-1] < short_avg[-1] and prices[-2] > short_avg[-2]:
for stock in context.portfolio.positions:
if bar_dict[stock].is_trading:
order_target_percent(stock, 0)
示例12: annotate_data
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def annotate_data(self, feed, timeframe):
# Get SMAs
for k, v in six.iteritems(self.sma_intervals):
feed[k] = talib.SMA(feed['closeMid'].values, v)
# Get MACD
# NOTE: talib.MACD() returns (macd, signal, hist)
feed['macd'], _, feed['macd_hist'] = talib.MACD(
feed['closeMid'].values,
fastperiod=12,
slowperiod=26,
signalperiod=9
)
# Get RSI
feed['rsi'] = talib.RSI(feed['closeMid'].values)
return feed
示例13: dMakeIngredients
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [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
示例14: __init__
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def __init__(self):
self.client = fcoin_client()
#self.client.stream.stream_depth.subscribe(self.depth)
#self.client.stream.stream_klines.subscribe(self.candle)
self.client.stream.stream_ticker.subscribe(self.ticker)
self.client.stream.stream_marketTrades.subscribe(self.trade)
self.fcoin = Fcoin()
self.fcoin.auth(config.key, config.secret)
self.buy_price = None # 买1价
self.buy_amount = None # 买1量
self.sell_price = None # 卖1价
self.sell_amount = None # 卖1量
self.ts = None # 深度更新时间
self.market_price = None # 市价
self.market_trade_list = None
self.total_bids = 0
self.total_asks = 0
self.filled_buy_order_list = []
self.order_list = defaultdict(lambda: None)
self.buy_order_id = None
self.dic_balance = defaultdict(lambda: None)
self.time_order = time.time()
self.price_list = []
self.candle_list = []
self.SMA = None
self._init_log()
# 日志初始化
示例15: candle
# 需要导入模块: import talib [as 别名]
# 或者: from talib import SMA [as 别名]
def candle(self, data):
if len(self.candle_list) == 0:
self.candle_list = [{'timestamp': data['id'],
'open': data['open'],
'high': data['high'],
'low': data['low'],
'close': data['close'],
'volume': data['base_vol']}]
else:
last_candle = self.candle_list[-1]
if last_candle['timestamp'] == data['id']:
self.candle_list[-1] = {'timestamp': data['id'],
'open': data['open'],
'high': data['high'],
'low': data['low'],
'close': data['close'],
'volume': data['base_vol']}
else:
self.candle_list.append({'timestamp': data['id'],
'open': data['open'],
'high': data['high'],
'low': data['low'],
'close': data['close'],
'volume': data['base_vol']})
if len(self.candle_list) > 10:
self.candle_list.pop(0)
if len(self.candle_list) > 7:
close_array = np.array([item['close'] for item in self.candle_list])
self.SMA = talib.SMA(close_array, timeperiod=7)
# 市价