Python talib.SMA Examples
The following are 30 code examples for showing how to use talib.SMA(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
You may check out the related API usage on the sidebar.
You may also want to check out all available functions/classes of the module
talib
, or try the search function
.
Example 1
Project: jesse Author: jesse-ai File: vwmacd.py License: MIT License | 7 votes |
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])
Example 2
Project: pandas_talib Author: femtotrader File: wrapper.py License: MIT License | 6 votes |
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)
Example 3
Project: technical Author: freqtrade File: indicators.py License: GNU General Public License v3.0 | 6 votes |
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
Example 4
Project: technical Author: freqtrade File: indicators.py License: GNU General Public License v3.0 | 6 votes |
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))
Example 5
Project: jesse Author: jesse-ai File: acosc.py License: MIT License | 6 votes |
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])
Example 6
Project: jesse Author: jesse-ai File: sma.py License: MIT License | 6 votes |
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]
Example 7
Project: jesse Author: jesse-ai File: ao.py License: MIT License | 6 votes |
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])
Example 8
Project: catalyst Author: enigmampc File: talib_simple.py License: Apache License 2.0 | 6 votes |
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
Example 9
Project: catalyst Author: enigmampc File: talib_simple.py License: Apache License 2.0 | 6 votes |
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
Example 10
Project: Rqalpha-myquant-learning Author: DingTobest File: ma20_60.py License: Apache License 2.0 | 6 votes |
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)
Example 11
Project: Rqalpha-myquant-learning Author: DingTobest File: ma20_5.py License: Apache License 2.0 | 6 votes |
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)
Example 12
Project: Rqalpha-myquant-learning Author: DingTobest File: ma20_20.py License: Apache License 2.0 | 6 votes |
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)
Example 13
Project: Rqalpha-myquant-learning Author: DingTobest File: ma20_120.py License: Apache License 2.0 | 6 votes |
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)
Example 14
Project: Rqalpha-myquant-learning Author: DingTobest File: ma20_250.py License: Apache License 2.0 | 6 votes |
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)
Example 15
Project: Rqalpha-myquant-learning Author: DingTobest File: ma20_10.py License: Apache License 2.0 | 6 votes |
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)
Example 16
Project: Rqalpha-myquant-learning Author: DingTobest File: ma20.py License: Apache License 2.0 | 6 votes |
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)
Example 17
Project: Rqalpha-myquant-learning Author: DingTobest File: timming.py License: Apache License 2.0 | 6 votes |
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)
Example 18
Project: Rqalpha-myquant-learning Author: DingTobest File: ma20.py License: Apache License 2.0 | 6 votes |
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)
Example 19
Project: Rqalpha-myquant-learning Author: DingTobest File: indexTimming.py License: Apache License 2.0 | 6 votes |
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)
Example 20
Project: pyfx Author: jmelett File: new_strategy.py License: MIT License | 6 votes |
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
Example 21
Project: OpenTrader Author: OpenTrading File: SMARecipe.py License: GNU Lesser General Public License v3.0 | 5 votes |
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
Example 22
Project: vnpy_crypto Author: birforce File: market_app.py License: MIT License | 5 votes |
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() # 日志初始化
Example 23
Project: vnpy_crypto Author: birforce File: market_app.py License: MIT License | 5 votes |
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) # 市价
Example 24
Project: vnpy_crypto Author: birforce File: wss_app.py License: MIT License | 5 votes |
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.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.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 = None self.SMA = None self._init_log() #日志初始化
Example 25
Project: vnpy_crypto Author: birforce File: wss_app.py License: MIT License | 5 votes |
def candle(self, data): if self.candle_list is None: 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) #市价
Example 26
Project: cbpro-trader Author: mcardillo55 File: IndicatorSubsystem.py License: GNU General Public License v3.0 | 5 votes |
def calculate_sma(self, period_name, closing_prices): sma = talib.SMA(closing_prices, timeperiod=9) self.current_indicators[period_name]['sma'] = sma[-1] self.current_indicators[period_name]['sma_trend'] = sma[-1] - sma[-2]
Example 27
Project: cbpro-trader Author: mcardillo55 File: IndicatorSubsystem.py License: GNU General Public License v3.0 | 5 votes |
def calculate_avg_volume(self, period_name, volumes): avg_vol = talib.SMA(volumes, timeperiod=15) self.current_indicators[period_name]['avg_volume'] = avg_vol[-1]
Example 28
Project: QUANTAXIS Author: QUANTAXIS File: talib_series.py License: MIT License | 5 votes |
def SMA(Series, timeperiod=30): return pd.Series(talib.SMA(Series.values, timeperiod), index=Series.index)
Example 29
Project: strategy Author: myquant File: volume_mixin.py License: Apache License 2.0 | 5 votes |
def volume_up(self, volume): sma = SMA(volume, timeperiod=self.short_timeperiod) lma = SMA(volume, timeperiod=self.long_timeperiod) ## make sure last lma is a number life = SMA(volume, timeperiod=self.life_timeperiod) if len(sma) < 3: return False volume_enforce = sma[-1] > lma[-1] > life[-1] speed_up = (volume[-1] - sma[-1]) > (sma[-1] - lma[-1]) > (lma[-1] - life[-1]) return volume_enforce and speed_up
Example 30
Project: strategy Author: myquant File: ta_indicator_mixin.py License: Apache License 2.0 | 5 votes |
def sma_close(self, sym, frequency, period=30): if not self.kbars_ready(sym, frequency): return [] closes = self.close(sym, frequency) ma = ta.SMA(closes, timeperiod=period) return ma