本文整理匯總了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)
# 市價