Python talib.SMA Examples
The following are 30
code examples of talib.SMA().
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 also want to check out all available functions/classes of the module
talib
, or try the search function
.
Example #1
Source File: ao.py From jesse with MIT License | 7 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 #2
Source File: sma.py From jesse with MIT License | 7 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 #3
Source File: ma20_5.py From Rqalpha-myquant-learning with 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 #4
Source File: talib_simple.py From catalyst with 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 #5
Source File: acosc.py From jesse with 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
Source File: vwmacd.py From jesse with MIT License | 6 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 #7
Source File: indicators.py From technical with 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 #8
Source File: ma20_60.py From Rqalpha-myquant-learning with 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 #9
Source File: wrapper.py From pandas_talib with 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 #10
Source File: ma20_20.py From Rqalpha-myquant-learning with 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
Source File: ma20_120.py From Rqalpha-myquant-learning with 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
Source File: ma20_250.py From Rqalpha-myquant-learning with 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
Source File: ma20.py From Rqalpha-myquant-learning with 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
Source File: ma20_10.py From Rqalpha-myquant-learning with 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
Source File: timming.py From Rqalpha-myquant-learning with 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
Source File: ma20.py From Rqalpha-myquant-learning with 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
Source File: new_strategy.py From pyfx with 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 #18
Source File: indexTimming.py From Rqalpha-myquant-learning with 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 #19
Source File: TestSMA.py From equant with GNU General Public License v2.0 | 5 votes |
def handle_data(context): global ue_sma ta_sma = talib.SMA(Close(), timeperiod=5) es_sma = SMA(Close(), 5, 5) ue_sma[-1] = EsTalib.U_SMA(ue_sma, Close(), 5, 5) ue_sma2[-1] = EsTalib2.U_SMA(Close(), 5, 5) LogInfo("SMA", ta_sma[-1], es_sma[-1], ue_sma[-1], ue_sma2[-1]) PlotNumeric('ta_sma', ta_sma[-1], color=RGB_Red()) PlotNumeric('es_sma', es_sma[-1], color=RGB_Blue()) PlotNumeric('ue_sma', ue_sma[-1], color=RGB_Green()) PlotNumeric('ue_sma2', ue_sma2[-1], color=RGB_Purple())
Example #20
Source File: ta_lib.py From ctpbee with MIT License | 5 votes |
def sma(self, n, array=False): """ Simple moving average. """ result = talib.SMA(self.close, n) if array: return result return result[-1]
Example #21
Source File: golden_cross.py From InplusTrader_Linux with MIT License | 5 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! # 因为策略需要用到均线,所以需要读取历史数据 prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close') # 使用talib计算长短两根均线,均线以array的格式表达 short_avg = talib.SMA(prices, context.SHORTPERIOD) long_avg = talib.SMA(prices, context.LONGPERIOD) plot("short avg", short_avg[-1]) plot("long avg", long_avg[-1]) # 计算现在portfolio中股票的仓位 cur_position = context.portfolio.positions[context.s1].quantity # 计算现在portfolio中的现金可以购买多少股票 shares = context.portfolio.cash/bar_dict[context.s1].close # 如果短均线从上往下跌破长均线,也就是在目前的bar短线平均值低于长线平均值,而上一个bar的短线平均值高于长线平均值 if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0: # 进行清仓 order_target_value(context.s1, 0) # 如果短均线从下往上突破长均线,为入场信号 if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0: # 满仓入股 order_shares(context.s1, shares)
Example #22
Source File: golden_cross.py From InplusTrader_Linux with MIT License | 5 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! # 因为策略需要用到均线,所以需要读取历史数据 prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close') # 使用talib计算长短两根均线,均线以array的格式表达 short_avg = talib.SMA(prices, context.SHORTPERIOD) long_avg = talib.SMA(prices, context.LONGPERIOD) plot("short avg", short_avg[-1]) plot("long avg", long_avg[-1]) # 计算现在portfolio中股票的仓位 cur_position = context.portfolio.positions[context.s1].quantity # 计算现在portfolio中的现金可以购买多少股票 shares = context.portfolio.cash/bar_dict[context.s1].close # 如果短均线从上往下跌破长均线,也就是在目前的bar短线平均值低于长线平均值,而上一个bar的短线平均值高于长线平均值 if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0: # 进行清仓 order_target_value(context.s1, 0) # 如果短均线从下往上突破长均线,为入场信号 if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0: # 满仓入股 order_shares(context.s1, shares)
Example #23
Source File: talib_indicators.py From qtpylib with Apache License 2.0 | 5 votes |
def SMA(data, **kwargs): _check_talib_presence() _, phigh, plow, _, _ = _extract_ohlc(data) return talib.SMA(phigh, plow, **kwargs)
Example #24
Source File: test_indicator_overlap.py From pandas-ta with MIT License | 5 votes |
def test_sma(self): result = pandas_ta.sma(self.close) self.assertIsInstance(result, Series) self.assertEqual(result.name, 'SMA_10') try: expected = tal.SMA(self.close, 10) pdt.assert_series_equal(result, expected, check_names=False) except AssertionError as ae: try: corr = pandas_ta.utils.df_error_analysis(result, expected, col=CORRELATION) self.assertGreater(corr, CORRELATION_THRESHOLD) except Exception as ex: error_analysis(result, CORRELATION, ex)
Example #25
Source File: indexTimming.py From Rqalpha-myquant-learning with Apache License 2.0 | 5 votes |
def timming(prices): short_avg = talib.SMA(prices, 20) long_avg = talib.SMA(prices, 120) timmingData = (short_avg[-1] / long_avg[-1]) - 1 if timmingData > 0.01: return 'up' elif timmingData < -0.01: return 'down' else: return 'Shock'
Example #26
Source File: golden_cross.py From InplusTrader_Linux with MIT License | 5 votes |
def handle_bar(context, bar_dict): # 开始编写你的主要的算法逻辑 # bar_dict[order_book_id] 可以拿到某个证券的bar信息 # context.portfolio 可以拿到现在的投资组合状态信息 # 使用order_shares(id_or_ins, amount)方法进行落单 # TODO: 开始编写你的算法吧! # 因为策略需要用到均线,所以需要读取历史数据 prices = history_bars(context.s1, context.LONGPERIOD+1, '1d', 'close') # 使用talib计算长短两根均线,均线以array的格式表达 short_avg = talib.SMA(prices, context.SHORTPERIOD) long_avg = talib.SMA(prices, context.LONGPERIOD) plot("short avg", short_avg[-1]) plot("long avg", long_avg[-1]) # 计算现在portfolio中股票的仓位 cur_position = context.portfolio.positions[context.s1].quantity # 计算现在portfolio中的现金可以购买多少股票 shares = context.portfolio.cash / bar_dict[context.s1].close # 如果短均线从上往下跌破长均线,也就是在目前的bar短线平均值低于长线平均值,而上一个bar的短线平均值高于长线平均值 if short_avg[-1] - long_avg[-1] < 0 and short_avg[-2] - long_avg[-2] > 0 and cur_position > 0: # 进行清仓 order_target_value(context.s1, 0) # 如果短均线从下往上突破长均线,为入场信号 if short_avg[-1] - long_avg[-1] > 0 and short_avg[-2] - long_avg[-2] < 0: # 满仓入股 order_shares(context.s1, shares)
Example #27
Source File: test_reg.py From finta with GNU Lesser General Public License v3.0 | 5 votes |
def test_sma(): '''test TA.SMA''' ma = TA.SMA(ohlc, 14) talib_ma = talib.SMA(ohlc['close'], timeperiod=14) assert round(talib_ma[-1], 5) == round(ma.values[-1], 5)
Example #28
Source File: TinyStrateSample.py From futuquant with Apache License 2.0 | 5 votes |
def sma(self, np_array, n, array=False): """简单均线""" if n < 2: result = np_array else: result = talib.SMA(np_array, n) if array: return result return result[-1]
Example #29
Source File: TinyStrateSample.py From futuquant with Apache License 2.0 | 5 votes |
def sma(self, np_array, n, array=False): """简单均线""" if n < 2: result = np_array else: result = talib.SMA(np_array, n) if array: return result return result[-1]
Example #30
Source File: TinyQuantBase.py From futuquant with Apache License 2.0 | 5 votes |
def sma(self, n, array=False): """简单均线""" result = talib.SMA(self.close, n) if array: return result return result[-1] # ----------------------------------------------------------------------