Example #1
0
def maxmin(data, fastk_period):
    close_prices = data[
        "close"].values  #np.nan_to_num(np.array([v['close'] for v in data]))
    max_prices = data[
        "high"].values  #np.nan_to_num(np.array([v['high'] for v in data]))
    min_prices = data[
        "low"].values  #np.nan_to_num(np.array([v['low'] for v in data]))

    max_close = talib.MAX(max_prices, timeperiod=fastk_period)
    min_close = talib.MIN(min_prices, timeperiod=fastk_period)

    try:
        for k in range(len(min_prices)):
            if k < fastk_period and k > 1:
                aaa = talib.MIN(min_prices, timeperiod=k)
                bbb = talib.MAX(max_prices, timeperiod=k)
                min_close[k] = aaa[k]
                max_close[k] = bbb[k]
            elif k == 1 or k == 0:
                min_close[k] = min_prices[k]
                max_close[k] = max_prices[k]
    except Exception as e:
        print(e)

    indicators = {'close': close_prices, 'max': max_close, 'min': min_close}
    return indicators
Example #2
0
def devstop(candles: np.ndarray, period: int = 20, mult: float = 0, direction: str = "long",
            sequential: bool = False) -> Union[
    float, np.ndarray]:
    """
    Kase Dev Stops

    :param candles: np.ndarray
    :param period: int - default=20
    :param mult: float - default=0
    :param direction: str - default=long
    :param sequential: bool - default=False

    :return: float | np.ndarray
    """
    candles = slice_candles(candles, sequential)

    high = candles[:, 3]
    low = candles[:, 4]

    AVTR = talib.SMA(talib.MAX(high, 2) - talib.MIN(low, 2), period)
    SD = talib.STDDEV(talib.MAX(high, 2) - talib.MIN(low, 2), period)

    if direction == "long":
        res = talib.MAX(high - AVTR - mult * SD, period)
    else:
        res = talib.MIN(low + AVTR + mult * SD, period)

    return res if sequential else res[-1]
Example #3
0
    def entrySignal(self, bar, signalPeriod):
        longSignal, shortSignal = 0, 0
        arrayPrepared, amSignal = self.arrayPrepared(signalPeriod)
        # amSignalDatetime = datetime.strptime(amSignal.datetime[-1], "%Y%m%d %H:%M:%S")
        if arrayPrepared:
            longSignal, shortSignal = 0, 0
            if self.calIndicator(bar):
                self.observedLong, self.observedShort, self.reversedLong, self.reversedShort, self.breakLong, self.breakShort = self.algorithm.rBreak(amSignal, self.paraDict)
            # upRevertDn, dnRevertUp, upBreak, dnBreak
            if len(self.observedLong):
                upRevertDn = ta.MAX(amSignal.high, self.sigPeriod)[-1]>ta.MAX(self.observedShort, self.sigPeriod)[-1] and amSignal.close[-1]<self.reversedShort[-1] and amSignal.close[-2]>=self.reversedShort[-1]
                dnRevertUp = ta.MIN(amSignal.low, self.sigPeriod)[-1]<ta.MIN(self.observedLong, self.sigPeriod)[-1] and amSignal.close[-1]>self.reversedLong[-1] and amSignal.close[-2]<=self.reversedLong[-1]
                upBreak = amSignal.close[-1]>self.breakLong[-2] and amSignal.close[-2]<=self.breakLong[-2]
                dnBreak = amSignal.close[-1]<self.breakShort[-2] and amSignal.close[-2]>=self.breakShort[-2]
                
                if dnRevertUp or upBreak:
                    longSignal = 1
                if upRevertDn or dnBreak:
                    shortSignal = 1
                self.globalStatus['longSignal'] = longSignal
                self.globalStatus['shortSignal'] = shortSignal

                self.chartLog['datetime'].append(datetime.strptime(amSignal.datetime[-1], "%Y%m%d %H:%M:%S"))
                self.chartLog['observedLong'].append(self.observedLong[-1])
                self.chartLog['observedShort'].append(self.observedShort[-1])
                self.chartLog['reversedLong'].append(self.reversedLong[-1])
                self.chartLog['reversedShort'].append(self.reversedShort[-1])
                self.chartLog['breakLong'].append(self.breakLong[-1])
                self.chartLog['breakShort'].append(self.breakShort[-1])
        return longSignal, shortSignal
Example #4
0
def get_ymjh_pos_df_all(index_code_lst, name_lst, index_hq_dic, para_dict,
                        hq_last_date):
    pos_df_all = pd.DataFrame(columns=['trade_date'])

    for j in range(len(index_code_lst)):
        index_code = index_code_lst[j]
        pos_df = pd.DataFrame(columns=['trade_date'])
        index_name = name_lst[j]
        index_hq = index_hq_dic[index_code]
        index_hq = index_hq[index_hq['trade_date'] <= hq_last_date]

        para_lst = para_dict[index_name]
        for i in range(len(para_lst)):
            para = para_lst[i]
            N1 = para[0]
            N2 = para[1]
            position = index_hq \
                .assign(HH_s=lambda df: tb.MAX(df.high.values, N1)) \
                .assign(LL_s=lambda df: tb.MIN(df.low.values, N1)) \
                .assign(HH_l=lambda df: tb.MAX(df.high.values, N2)) \
                .assign(LL_l=lambda df: tb.MIN(df.low.values, N2)) \
                .assign(ma_s=lambda df: (df.HH_s + df.LL_s) / 2) \
                .assign(ma_l=lambda df: (df.HH_l + df.LL_l) / 2) \
                .assign(ma_s1=lambda df: df.ma_s.shift(1)) \
                .assign(ma_l1=lambda df: df.ma_l.shift(1)) \
                .assign(ave_p=lambda df: (2 * df.close + df.high + df.low) / 4)
            pos = 0
            pos_lst = []
            for idx, _row in position.iterrows():
                condition_l = ((_row.ma_s1 == _row.ma_l1) and
                               (_row.ma_s > _row.ma_l) and
                               (_row.ave_p >= _row.ma_s)) or (
                                   (_row.ma_s1 < _row.ma_l1) and
                                   (_row.ma_s > _row.ma_l) and
                                   (_row.ave_p >= min(_row.ma_s, _row.ma_l)))
                condition_s = (_row.ma_s1 > _row.ma_l1) and (
                    _row.ma_s < _row.ma_l) and (_row.ave_p <= max(
                        _row.ma_s, _row.ma_l))
                if pos == 0:
                    if condition_l:
                        pos = 1
                elif pos == 1:
                    if condition_s:
                        pos = 0
                pos_lst.append(pos)
            position['pos' + str(i)] = pos_lst
            position = position.reset_index(drop=True)[[
                'trade_date', 'pos' + str(i)
            ]]
            pos_df = pos_df.merge(position, on=['trade_date'], how='outer')
        pos_df = pos_df.dropna().sort_values(['trade_date'
                                              ]).set_index(['trade_date'])

        pos_df[index_name + '_ymjh'] = pos_df.sum(axis=1) / len(para_lst)
        pos_df_all = pos_df_all.merge(pos_df.reset_index(drop=False)[[
            'trade_date', index_name + '_ymjh'
        ]],
                                      on=['trade_date'],
                                      how='outer')
    return pos_df_all
Example #5
0
def cksp(candles: np.ndarray,
         p: int = 10,
         x: float = 1.0,
         q: int = 9,
         sequential: bool = False) -> CKSP:
    """
    Chande Kroll Stop (CKSP)

    :param candles: np.ndarray
    :param p: int - default: 10
    :param x: float - default: 1.0
    :param q: int - default: 9
    :param sequential: bool - default: False

    :return: float | np.ndarray
    """
    candles = slice_candles(candles, sequential)

    candles_close = candles[:, 2]
    candles_high = candles[:, 3]
    candles_low = candles[:, 4]

    atr = talib.ATR(candles_high, candles_low, candles_close, timeperiod=p)

    LS0 = talib.MAX(candles_high, q) - x * atr
    LS = talib.MAX(LS0, q)

    SS0 = talib.MIN(candles_low, q) + x * atr
    SS = talib.MIN(SS0, q)

    if sequential:
        return CKSP(LS, SS)
    else:
        return CKSP(LS[-1], SS[-1])
Example #6
0
def cal_signal(df,strat_time,end_time,cs0,ix_zong=100,all_day=0):

    a = time.process_time()
    # std__len,rooling_count,std_bd_n ,tp_n,zuhe_limit,max_stop_win = cs0
    #  ===指标数据
    df['tp'] = std_zdf_tp(df, int(cs0[0]), float(cs0[2]), int(cs0[0]))
    df['zuheyinzi'] = rsi_cci_atr01(df[['candle_begin_time', 'open', 'high', 'low', 'close', 'volume']],n=int(cs0[0]))
    # df['zuheyinzi'] = (df['zuheyinzi'].diff(1).diff(1)).rolling(int(cs0[0])).mean()
    df['zuheyinzi'] = df['zuheyinzi'] - df['zuheyinzi'].shift(1)
    df['zuheyinzi'] = df['zuheyinzi'] - df['zuheyinzi'].shift(1)
    df['zuheyinzi'] = (talib.MAX(df['zuheyinzi'],int(cs0[0])) +talib.MIN(df['zuheyinzi'],int(cs0[0])))*0.5

    # print(df['zuheyinzi'].tail(20))
    df['xiao'] =talib.MA(df['close'],int(cs0[1]))
    df['stop_line'] =talib.MIN(df['close'],int(cs0[0]))

    df['止损价'] = np.nan
    df['止盈价'] = np.nan
    df['日内最低价'] = np.nan
    df['日内最高价'] = np.nan
    pass
    # ===转化成np.array
    df0cols = ['candle_begin_time', 'open', 'high', 'low', 'close', 'volume','days', 'huors', 'minutes']
    df0 = df[df0cols].values
    df1cols = ['candle_begin_time', 'signal', 'pos', 'opne_price', 'per_lr', 'sl']
    df1 = df[df1cols].values
    df2cols = ['candle_begin_time', 'tp',"zuheyinzi", 'xiao',"stop_line", '止损价', '止盈价', '日内最低价', '日内最高价']

    df2 = df[df2cols].values
    df0, df1, df2, res = cal_signal_(df0, df1, df2, strat_time, end_time, cs0,all_day)
    print('runingtime:', time.process_time() - a, f's ,已经完成 ==:{round(ix_zong,2)}%')
    # print(df0.shape, df1.shape, df2.shape,[df0cols,df1cols,df2cols], res)

    # res=[0]
    return df0, df1, df2,[df0cols,df1cols,df2cols],ix_zong, res
Example #7
0
    def calcRange(self):
        if self.am.count >= self.atrDays + 1:
            self.atrValue = self.am.atr(self.atrDays, False)
            if self.atrValue > 0:
                self.fixedSize = self.calcUnitNo(self.atrValue, self.fixedSize)
            self.rangeHigh = talib.MAX(self.am.high, self.rangeDays)[-1]
            self.rangeLow = talib.MIN(self.am.low, self.rangeDays)[-1]
            self.rangeHighClose = talib.MAX(self.am.close, self.rangeDays)[-1]
            self.rangeLowClose = talib.MIN(self.am.close, self.rangeDays)[-1]
            self.range1 = self.rangeHigh - self.rangeLowClose
            self.range2 = self.rangeHighClose - self.rangeLow
            #self.rsival = self.am.rsi(self.rsilen, array=False)

            tlen = len(self.am.closeArray) - self.rsilen - 2
            rsi1 = talib.RSI(self.am.closeArray[tlen:], timeperiod=self.rsilen)
            self.rsival = rsi1[-1]
            #print("rsi array", rsi1)

            #print("\n\rthe rsi is:", rsi1[-1])

            # print(self.rangeHigh,self.rangeLow)
            if (self.range1 > self.range2):
                calcRange = self.range1
            else:
                calcRange = self.range2
        else:
            calcRange = 0
        return calcRange
Example #8
0
    def soupSignal(self,am, paraDict):
        hlPeriod = paraDict['hlPeriod']
        delayPeriod = paraDict['delayPeriod']

        delayMax = ta.MAX(am.high, hlPeriod)[:-delayPeriod]
        delayMin = ta.MIN(am.low, hlPeriod)[:-delayPeriod]

        newHigh = ta.MAX(am.high, hlPeriod)[delayPeriod:]
        newLow = ta.MIN(am.low, hlPeriod)[delayPeriod:]

        exHighArray = delayMax*(delayMax<newHigh)
        exLowArray = delayMin*(delayMin>newLow)

        delayHigh, delayLow = 0, 0
        for i in range(len(exHighArray)-1, 0, -1):
            if exHighArray[i] != 0:
                delayHigh = exHighArray[i]
                break
        
        for i in range(len(exLowArray)-1, 0, -1):
            if exLowArray[i] != 0:
                delayLow = exLowArray[i]
                break
        
        return delayHigh, delayLow, newHigh, newLow
Example #9
0
def tianbijun_formulation():
    raw_data = ts.get_hist_data('hs300', start='2014-07-01')
    H1 = ta.MA(np.asarray(raw_data['close']), timeperiod=8,
               matype=1)  #8日指数平滑均线
    H2 = ta.MA(H1, timeperiod=20, matype=1)
    LH = ta.MA(np.asarray(raw_data['close']), timeperiod=240,
               matype=1)  #240指数平滑均线
    high_price = ta.MAX(np.asarray(raw_data['high']), timeperiod=36)
    VAR1 = (high_price - np.asarray(raw_data['close'])) / (
        high_price - ta.MIN(np.asarray(raw_data['high']), timeperiod=36)) * 100
    VAR2 = ta.MA(VAR1, timeperiod=5)
    VAR3 = ta.MA(VAR2, timeperiod=8)
    if line_cross(VAR2, VAR3) and VAR3 < 20:
        VAR4 = True
    else:
        VAR4 = False
    if np.asarray(raw_data['close']) > 1.3 * ta.MIN(
            np.asarray(raw_data['high']), timeperiod=60) and VAR4:
        VAR5 = True
    else:
        VAR5 = False
    if np.asarray(raw_data['close']) > 1000:
        VAR6 = VAR4
    else:
        VAR6 = VAR5

    return VAR6
Example #10
0
    def __init__(self,
                 feed,
                 instruments,
                 context,
                 dictOfDataDf,
                 atrPeriod=20,
                 short=20,
                 long=55):
        """
        初始化
        :parm feed pyalgotrade 的feed对象,装了所有csv数据。类似于dict可以用中括号取值。
        :parm instrument 包含所有category的list,用的是简写,如‘rb’,‘ag’
        :param context context 对象,装所有变量
        :parm atrPeriod atr的周期
        :parm short 唐奇安通道的短期
        :parm long 唐奇安通道的长期
        :parm dictOfDataDf 包含所有数据的dict,其中每一个category是一个df
        """
        self.initialCash = 100000
        super(TurtleTrade, self).__init__(feed, self.initialCash)
        self.feed = feed
        if isinstance(instruments, list):  # 对于不是多个品种的情况,进行判断,如果是字符串,用list包裹在存储
            self.instruments = instruments
        else:
            self.instruments = [instruments]
        self.atrPeriod = atrPeriod
        self.short = short  # * 300  # 测试
        self.long = long  # * 300  # 测试
        self.dictOfDateDf = dictOfDataDf
        self.context = context
        self.generalTickInfo = pd.read_csv('../general_ticker_info.csv')
        self.openPriceAndATR = {}  # 用于记录每个品种的开仓价格与当时的atr
        self.equity = 0
        self.tech = {}
        # self.max = 0  # 用来存储最大的历史数据有多长, 以计算此时到了哪一根k线,以方便用 -(self.max - self.i) 来取技术指标
        for instrument in self.instruments:
            atr = talib.ATR(np.array(self.dictOfDateDf[instrument]['High']),
                            np.array(self.dictOfDateDf[instrument]['Low']),
                            np.array(self.dictOfDateDf[instrument]['Close']),
                            self.atrPeriod)  # 返回的ndarray
            long_upper = talib.MAX(
                np.array(self.dictOfDateDf[instrument]['High']), self.long)
            long_lower = talib.MIN(
                np.array(self.dictOfDateDf[instrument]['Low']), self.long)
            short_upper = talib.MAX(
                np.array(self.dictOfDateDf[instrument]['High']), self.short)
            short_lower = talib.MIN(
                np.array(self.dictOfDateDf[instrument]['Low']), self.short)

            self.tech[instrument] = {
                'atr': atr,
                'long upper': long_upper,
                'long lower': long_lower,
                'short upper': short_upper,
                'short lower': short_lower
            }
Example #11
0
	def BarUpdate(self):
		""""""
		if self.CurrentBar < self.Params['fsLength']:
			return
		atr = talib.ATR(self.H, self.L, self.C, 14)

		lots = self.Params['Lots']

		DonchianHi = talib.MAX(self.H, self.Params['boLength'])[-2]
		DonchianLo = talib.MIN(self.L, self.Params['boLength'])[-2]

		fsDonchianHi = talib.MAX(self.H, self.Params['fsLength'])[-2]
		fsDonchianLo = talib.MIN(self.L, self.Params['fsLength'])[-2]

		ExitHighestPrice = talib.MAX(self.H, self.Params['teLength'])[-2]
		ExitLowestPrice = talib.MIN(self.L, self.Params['teLength'])[-2]

		if len(atr) < 2:
			return

		N = atr[-2]

		if self.Position == 0:
			if self.H[-1] > DonchianHi:
				price = max(min(self.H[-1], DonchianHi), self.O[-1])
				self.Buy(price, lots, '上轨')
			elif self.L[-1] < DonchianLo:
				price = min(max(self.L[-1], DonchianLo), self.O[-1])
				self.SellShort(price, lots, '下轨')
			#长期突破
			elif self.H[-1] > fsDonchianHi:
				price = max(min(self.H[-1], fsDonchianHi), self.O[-1])
				self.Buy(price, lots, '上轨-fs')
			elif self.L[-1] < fsDonchianLo:
				price = min(max(self.L[-1], fsDonchianLo), self.O[-1])
				self.SellShort(price, lots, '下轨-fs')

		elif self.Position > 0:
			if self.L[-1] < ExitLowestPrice:
				price = min(self.O[-1], max(self.L[-1], ExitLowestPrice))
				self.Sell(price, self.PositionLong, 'exit-价格需优化')
			else:
				if self.H[-1] >= self.LastEntryPriceLong + 0.5 * N:
					price = max(self.O[-1], self.LastEntryPriceLong + 0.5 * N)
					self.Buy(price, lots, '{0},{1}'.format(N, '加仓-多'))
		elif self.Position < 0:
			if self.H[-1] > ExitHighestPrice:
				price = max(self.O[-1], min(self.H[-1], ExitHighestPrice))
				self.BuyToCover(price, self.PositionShort, 'exit')
			else:
				if self.L[-1] <= self.LastEntryPriceShort - 0.5 * N:
					price = min(self.O[-1], self.LastEntryPriceShort - 0.5 * N)
					self.SellShort(price, lots, '{0},{1}'.format(N, '加仓-空'))
Example #12
0
 def strategy_handle(self):
     position = copy.copy(self.position)
     df = copy.copy(self.data1)
     df["conversion_min"] = talib.MIN(df["low"], self.conversion_periods)
     df["conversion_max"] = talib.MAX(df["high"], self.conversion_periods)
     df["conversion"] = (df["conversion_min"] + df["conversion_max"]) / 2
     df["base_min"] = talib.MIN(df["low"], self.base_periods)
     df["base_max"] = talib.MAX(df["high"], self.base_periods)
     df["base"] = (df["base_min"] + df["base_max"]) / 2
     df["leada"] = (df["conversion"] + df["base"]) / 2
     df["leadb_min"] = talib.MIN(df["low"], self.lagging_span2_periods)
     df["leadb_max"] = talib.MAX(df["high"], self.lagging_span2_periods)
     df["leadb"] = (df["leadb_min"] + df["leadb_max"]) / 2
     df = df[[
         'id', 'open', 'high', 'low', 'close', 'conversion', 'base',
         'leada', 'leadb'
     ]]
     last_bar = df.iloc[-2]
     curr_bar = df.iloc[-1]
     self.last_price = curr_bar["close"]
     last_lead = df.iloc[-self.base_periods - 1]
     curr_lead = df.iloc[-self.base_periods]
     last_delay_lead = df.iloc[-self.lagging_span2_periods - 1]
     curr_delay_lead = df.iloc[-self.lagging_span2_periods]
     cur_lead_dir, charge_lead_dir = ichimoku_util.lead_dir(
         last_bar, curr_bar)
     cur_price_dir, charge_price_dir, price_base = ichimoku_util.price_ichimoku(
         last_bar, curr_bar, last_lead, curr_lead)
     cur_cb_dir, change_cb_dir, cb_dir, cb_change_dir = ichimoku_util.cb_base_ichimoku(
         last_bar, curr_bar, last_lead, curr_lead)
     cur_delay_dir, change_delay_dir = ichimoku_util.delay_ichimoku(
         last_bar, curr_bar, last_delay_lead, curr_delay_lead)
     log = {
         "cur_lead_dir": cur_lead_dir,
         "charge_lead_dir": charge_lead_dir,
         "cur_price_dir": cur_price_dir,
         "charge_price_dir": charge_price_dir,
         "price_base": price_base,
         "cur_cb_dir": cur_cb_dir,
         "change_cb_dir": change_cb_dir,
         "cb_dir": cb_dir,
         "cb_change_dir": cb_change_dir,
         "cur_delay_dir": cur_delay_dir,
         "change_delay_dir": change_delay_dir,
         "close": curr_bar["close"]
     }
     # print(log)
     self.open_position(cur_price_dir, charge_price_dir, cur_cb_dir,
                        change_cb_dir, cb_dir, cb_change_dir, cur_delay_dir,
                        change_delay_dir)
     self.close_position(position, cur_price_dir, price_base, cb_dir,
                         cur_delay_dir)
Example #13
0
def ichimoku_cloud_seq(candles: np.ndarray,
                       conversion_line_period: int = 9,
                       base_line_period: int = 26,
                       lagging_line_period: int = 52,
                       displacement: int = 26,
                       sequential: bool = False) -> IchimokuCloud:
    """
    Ichimoku Cloud

    :param candles: np.ndarray
    :param conversion_line_period: int - default=9
    :param base_line_period: int - default=26
    :param lagging_line_period: int - default=52
    :param displacement: - default=26
    :param sequential: bool - default=False

    :return: IchimokuCloud
    """

    if len(candles) < lagging_line_period + displacement:
        raise ValueError(
            "Too few candles available for lagging_line_period + displacement."
        )

    if not sequential and len(candles) > 240:
        candles = candles[-240:]

    small_ph = talib.MAX(candles[:, 3], conversion_line_period)
    small_pl = talib.MIN(candles[:, 4], conversion_line_period)
    conversion_line = (small_ph + small_pl) / 2

    mid_ph = talib.MAX(candles[:, 3], base_line_period)
    mid_pl = talib.MIN(candles[:, 4], base_line_period)
    base_line = (mid_ph + mid_pl) / 2

    long_ph = talib.MAX(candles[:, 3], lagging_line_period)
    long_pl = talib.MIN(candles[:, 4], lagging_line_period)
    span_b_pre = (long_ph + long_pl) / 2
    span_b = np_shift(span_b_pre, displacement, fill_value=np.nan)
    span_a_pre = (conversion_line + base_line) / 2
    span_a = np_shift(span_a_pre, displacement, fill_value=np.nan)

    lagging_line = np_shift(candles[:, 2], displacement - 1, fill_value=np.nan)

    if sequential:
        return IchimokuCloud(conversion_line, base_line, span_a, span_b,
                             lagging_line, span_a_pre, span_b_pre)
    else:
        return IchimokuCloud(conversion_line[-1], base_line[-1], span_a[-1],
                             span_b[-1], lagging_line[-1], span_a_pre[-1],
                             span_b_pre[-1])
Example #14
0
 def calcPrepare(self):
     #calculate initials of the strategy
     barLength = 0 
     barLength = max(self.longDays,self.shortDays,self.atrDays) 
     if self.am.count < barLength + 1:
         return   
     #self.atrValue = talib.ATR(self.am.high, self.am.low, self.am.close,self.atrDays)[-1] 
     self.atrValue = self.am.atr(self.atrDays,False)
     # = atrLine[-1]
    
     self.upperChannel = talib.MAX(self.am.high,self.longDays)[-1]
     self.lowerChannel = talib.MIN(self.am.low,self.shortDays)[-1]
     self.longChannelExit = talib.MIN(self.am.low,self.longExitDays)[-1]
     self.shortChannelExit = talib.MAX(self.am.high,self.shortExitDays)[-1]
Example #15
0
 def min(self, n, bar_component='close', array=False):
     """
     Simple moving average.
     """
     if bar_component == 'volume':
         result = talib.MIN(self.volume, n)
         if array:
             return result
         return result[-1]
     else:
         result = talib.MIN(self.close, n)
         if array:
             return result
         return result[-1]
 def calcRange(self):
     if self.am.count >= self.rangeDays:
         self.rangeHigh = talib.MAX(self.am.high, self.rangeDays)[-1]
         self.rangeLow = talib.MIN(self.am.low, self.rangeDays)[-1]
         self.rangeHighClose = talib.MAX(self.am.close, self.rangeDays)[-1]
         self.rangeLowClose = talib.MIN(self.am.close, self.rangeDays)[-1]
         self.range1 = self.rangeHigh - self.rangeLowClose
         self.range2 = self.rangeHighClose - self.rangeLow
         if (self.range1 > self.range2):
             calcRange = self.range1
         else:
             calcRange = self.range2
     else:
         calcRange = 0
     return calcRange
    def entrySignal(self, bar, signalPeriod, tradePeriod):
        longSignal, shortSignal = 0, 0
        arrayPrepared1, amSignal = self.arrayPrepared(signalPeriod)
        arrayPrepared2, amTrade = self.arrayPrepared(tradePeriod)

        # amSignalDatetime = datetime.strptime(amSignal.datetime[-1], "%Y%m%d %H:%M:%S")
        if arrayPrepared1 and arrayPrepared2:
            longSignal, shortSignal = 0, 0
            if self.calIndicator(bar):
                self.observedLong, self.observedShort, self.reversedLong, self.reversedShort, self.breakLong, self.breakShort = self.algorithm.rBreak(
                    amSignal, self.paraDict)
            # upRevertDn, dnRevertUp, upBreak, dnBreak
            if len(self.observedLong):
                filterCanTrade = self.algorithm.fliterVol(
                    amSignal, self.paraDict)
                upRevertDn = ta.MAX(amSignal.high, self.sigPeriod)[-1]>ta.MAX(self.observedShort, self.sigPeriod)[-1]\
                 and amTrade.close[-1]<self.reversedShort[-1] and amSignal.close[-1]>=self.reversedShort[-1]
                dnRevertUp = ta.MIN(amSignal.low, self.sigPeriod)[-1]<ta.MIN(self.observedLong, self.sigPeriod)[-1]\
                 and amTrade.close[-1]>self.reversedLong[-1] and amSignal.close[-1]<=self.reversedLong[-1]

                upBreak = amTrade.close[-1] > self.breakLong[
                    -1] and amSignal.close[-1] <= self.breakLong[-1]
                dnBreak = amTrade.close[-1] < self.breakShort[
                    -1] and amSignal.close[-1] >= self.breakShort[-1]

                if not self.isStopControled():
                    if filterCanTrade:
                        if dnRevertUp or upBreak:
                            longSignal = 1
                        if upRevertDn or dnBreak:
                            shortSignal = 1

                self.lotMultiplier = self.algorithm.bigVolWeight(
                    amTrade, self.paraDict)

                self.globalStatus['longSignal'] = longSignal
                self.globalStatus['shortSignal'] = shortSignal

                self.chartLog['datetime'].append(
                    datetime.strptime(amSignal.datetime[-1],
                                      "%Y%m%d %H:%M:%S"))
                self.chartLog['observedLong'].append(self.observedLong[-1])
                self.chartLog['observedShort'].append(self.observedShort[-1])
                self.chartLog['reversedLong'].append(self.reversedLong[-1])
                self.chartLog['reversedShort'].append(self.reversedShort[-1])
                self.chartLog['breakLong'].append(self.breakLong[-1])
                self.chartLog['breakShort'].append(self.breakShort[-1])
        return longSignal, shortSignal
Example #18
0
def donchian(n, df):
    """
    Donchian Channel.
    """
    up = talib.MAX(df.high_price, n)
    down = talib.MIN(df.low_price, n)
    return Decimal(str(up[-2])), Decimal(str(down[-2]))
Example #19
0
    def clfxc(self, n, array=False):
        """缠论分型通道"""
        clfx_high = np.zeros(self.size)
        clfx_low = np.zeros(self.size)
        clfx_high_index = []
        clfx_low_index = []
        
        # 遍历,找到是分型点的index
        for i in range(1,self.size-1):
            if self.high[i]>self.high[i-1] and self.high[i]>self.high[i+1] and self.low[i]>self.low[i-1] and self.low[i]>self.low[i+1]:
                clfx_high_index.append(i)
            elif self.high[i]<self.high[i-1] and self.high[i]<self.high[i+1] and self.low[i]<self.low[i-1] and self.low[i]<self.low[i+1]:
                clfx_low_index.append(i)
        # 填充“当前时点最近一个分型值”数组
        print(clfx_high_index)
        for i in range(len(clfx_high_index)-1):
            clfx_high[clfx_high_index[i]:clfx_high_index[i+1]] = self.high[clfx_high_index[i]]
        if len(clfx_high_index) >= 2:
            clfx_high[clfx_high_index[-1]:] = self.high[clfx_high_index[-1]]

        for i in range(len(clfx_low_index)-1):
            clfx_low[clfx_low_index[i]:clfx_low_index[i+1]] = self.low[clfx_low_index[i]]
        if len(clfx_low_index) >= 2:
            clfx_low[clfx_low_index[-1]:] = self.low[clfx_low_index[-1]]
        # 窗口期内最大分型点的数值构成通道上下轨
        up = talib.MAX(clfx_high, n)
        down = talib.MIN(clfx_low, n)

        if array:
            return up, down
        return up[-1], down[-1]
Example #20
0
def cal_signal(df,strat_time,end_time,cs0,ix_zong=100):
    a = time.process_time()
    #  ===指标数据
    # da,zhong,xiao,stop_n,max_stop_win = cs0

    df['ma_da'] = talib.MA(df['close'],cs0[0])
    df['ma_z'] = talib.MA(df['close'],cs0[1])
    df['ma_xiao'] = talib.MA(df['close'],cs0[2])
    df['ma_xiao_min'] = talib.MIN(df['ma_xiao'],10)

    df['止损价'] = np.nan
    df['止盈价'] = np.nan
    df['日内最低价'] = np.nan
    df['日内最高价'] = np.nan
    pass
    # ===转化成np.array
    df0cols = ['candle_begin_time', 'open', 'high', 'low', 'close', 'volume','days', 'huors', 'minutes']
    df0 = df[df0cols].values
    df1cols = ['candle_begin_time', 'signal', 'pos', 'opne_price', 'per_lr', 'sl']
    df1 = df[df1cols].values
    df2cols = ['candle_begin_time', 'ma_da', 'ma_xiao_min', 'ma_xiao', '止损价', '止盈价', '日内最低价', '日内最高价']
    df2 = df[df2cols].values
    df0, df1, df2, res = cal_signal_(df0, df1, df2, strat_time, end_time, cs0)
    print('runingtime:', time.process_time() - a, f's ,已经完成 ==:{round(ix_zong,2)}%')
    # print(df0.shape, df1.shape, df2.shape,[df0cols,df1cols,df2cols], res)

    # res=[0]
    return df0, df1, df2,[df0cols,df1cols,df2cols], res
Example #21
0
File: stochf.py Project: zx9r/jesse
def stochf(candles: np.ndarray, fastk_period: int = 5, fastd_period: int = 3, fastd_matype: int = 0,
           sequential: bool = False) -> StochasticFast:
    """
    Stochastic Fast

    :param candles: np.ndarray
    :param fastk_period: int - default=5
    :param fastd_period: int - default=3
    :param fastd_matype: int - default=0
    :param sequential: bool - default=False

    :return: StochasticFast(k, d)
    """
    candles = slice_candles(candles, sequential)

    candles_close = candles[:, 2]
    candles_high = candles[:, 3]
    candles_low = candles[:, 4]

    hh = talib.MAX(candles_high, fastk_period)
    ll = talib.MIN(candles_low, fastk_period)

    k = 100 * (candles_close - ll) / (hh - ll)
    d = ma(k, period=fastd_period, matype=fastd_matype, sequential=True)

    if sequential:
        return StochasticFast(k, d)
    else:
        return StochasticFast(k[-1], d[-1])
Example #22
0
    def donchian(self, n, array=False):
        up = talib.MAX(self.high, n)
        down = talib.MIN(self.low, n)

        if array:
            return up, down
        return up[-1], down[-1]
Example #23
0
def handle_data(context):
    MA1 = talib.MA(Close(), timeperiod=p)
    MA2 = talib.MIN(Low(), timeperiod=p)
    MA3 = talib.MAX(High(), timeperiod=p)
    #LogInfo(MA2)
    #LogInfo(MA3)
    MA4 = talib.MA(Close(), timeperiod=N1)
    MA5 = talib.MA(Close(), timeperiod=N2)
    if len(MA2) < 55 or len(MA3) < 67:
        return

    if MarketPosition() == 0:
        if (Close()[-1] > MA1[-1]) and (MA5[-1] > MA4[-1]) and (Close()[-1] >
                                                                MA3[-N0]):
            Buy(1, Close()[-1])
        elif (MA1[-1] > Close()[-1]) and (MA5[-1] < MA4[-1]) and (Close()[-1] <
                                                                  MA4[-1]):
            SellShort(1, Close()[-1])
        else:
            pass

    else:
        if Close()[-1] < MA2[-N]:
            Sell(1, Close()[-1])
        elif Close()[-1] > MA3[-N0]:
            BuyToCover(1, Close()[-1])  #买平仓
        else:
            pass
    def boll_kc_dc_combination(self, high, close, low, boll_kk_dev,kk_atr_length,com_length):

        # 计算组合均线
        ema_com = talib.EMA(close, com_length)

        # 计算布林带
        boll_std = talib.STDDEV(close, com_length)
        boll_up = ema_com + boll_kk_dev * boll_std
        boll_down = ema_com - boll_kk_dev * boll_std

        # 计算肯特通道
        kc_atr = talib.ATR(high, low, close, kk_atr_length)
        kc_up = ema_com + kc_atr * boll_kk_dev
        kc_dowm = ema_com - kc_atr * boll_kk_dev

        # 计算唐安奇通道
        dc_up = talib.MAX(high, com_length)
        dc_down = talib.MIN(low, com_length)

        # 计算轨道 因kc通道是直接,最小值大概率是直接,所以去除
        pass_up_min = min(dc_up[-1], boll_up[-1])
        pass_down_min = max(dc_down[-1], boll_down[-1])

        pass_up_max = max(kc_up[-1], dc_up[-1], boll_up[-1])
        pass_down_max = min(kc_dowm[-1], dc_down[-1], boll_down[-1])
        ema_mid = ema_com[-1]

        com_width = abs(pass_up_max - pass_down_max)

        return ema_mid, com_width, pass_up_min, pass_down_min, pass_up_max, pass_down_max
Example #25
0
def Math_Operators(dataframe):
	#Math Operator Functions
	#ADD - Vector Arithmetic Add
	df[f'{ratio}_ADD'] = talib.ADD(High, Low)
	#c - Vector Arithmetic Div
	df[f'{ratio}_ADD'] = talib.DIV(High, Low)
	#MAX - Highest value over a specified period
	df[f'{ratio}_MAX'] = talib.MAX(Close, timeperiod=30)
	#MAXINDEX - Index of Highest value over a specified period
	#integer = MAXINDEX(Close, timeperiod=30)
	#MIN - Lowest value over a specified period
	df[f'{ratio}_MIN'] = talib.MIN(Close, timeperiod=30)
	#MININDEX - Index of Lowest value over a specified period
	integer = talib.MININDEX(Close, timeperiod=30)
	#MINMAX - Lowest and Highest values over a specified period
	min, max = talib.MINMAX(Close, timeperiod=30)
	#MINMAXINDEX - Indexes of Lowest and Highest values over a specified period
	minidx, maxidx = talib.MINMAXINDEX(Close, timeperiod=30)
	#MULT - Vector Arithmetic Mult
	df[f'{ratio}_MULT'] = talib.MULT(High, Low)
	#SUB - Vector Arithmetic Substraction
	df[f'{ratio}_SUB'] = talib.SUB(High, Low)
	#SUM - Summation
	df[f'{ratio}_SUM'] = talib.SUM(Close, timeperiod=30)

	return
def donchian(data, n, array=False):
    up = talib.MAX(data, n)
    down = talib.MIN(data, n)

    if array:
        return up, down
    return up[-1], down[-1]
Example #27
0
def safezonestop(candles: np.ndarray, period: int = 22, mult: float = 2.5, max_lookback: int = 3,
                 direction: str = "long", sequential: bool = False) -> Union[float, np.ndarray]:
    """
    Safezone Stops

    :param candles: np.ndarray
    :param period: int - default: 22
    :param mult: float - default: 2.5
    :param max_lookback: int - default: 3
    :param direction: str - default: long
    :param sequential: bool - default: False

    :return: float | np.ndarray
    """
    candles = slice_candles(candles, sequential)

    high = candles[:, 3]
    low = candles[:, 4]

    last_high = np_shift(high, 1, fill_value=np.nan)
    last_low = np_shift(low, 1, fill_value=np.nan)

    if direction == "long":
        res = talib.MAX(last_low - mult * talib.MINUS_DM(high, low, timeperiod=period), max_lookback)
    else:
        res = talib.MIN(last_high + mult * talib.PLUS_DM(high, low, timeperiod=period), max_lookback)

    return res if sequential else res[-1]
Example #28
0
def test_MIN():
    i, result = talib.MIN(series, timeperiod=4)
    assert len(series) - len(result) == i
    assert result[1] == 93.780
    assert result[2] == 93.780
    assert result[3] == 92.530
    assert result[4] == 92.530
def cal_signal(df, strat_time, end_time, canshu):
    a = time.process_time()
    # ===转化成np.array
    df0cols = [
        'candle_begin_time', 'open', 'high', 'low', 'close', 'volume', 'days',
        'huors', 'minutes'
    ]
    df1cols = [
        'candle_begin_time', 'signal', 'pos', 'opne_price', 'per_lr', 'sl'
    ]
    df2cols = [
        'candle_begin_time', '止损价', '止盈价', '日内最低价', '日内最高价', '开仓线', 'atr_day',
        '小均线', 'n_atr', '移动止赢', '大均线', 'min_n'
    ]
    # 配置参数:止盈,ma_len(atr),atr_倍数,交易次数
    # stop_win_n, ma_len, atrn, trade_inner_nums = cs0
    df['小均线'] = talib.SMA(df['close'], int(canshu[1]))
    df['大均线'] = talib.SMA(df['close'], int(canshu[2]))
    df['n_atr'] = talib.ATR(df['close'], df['high'], df['low'], int(canshu[1]))
    df['min_n'] = talib.MIN(df['close'], int(canshu[1]))

    df['移动止赢'] = np.nan

    # print(df.tail())
    # exit()
    df0 = df[df0cols].values
    df1 = df[df1cols].values
    df2 = df[df2cols].values
    df0, df1, df2, res = cal_signal_(df0, df1, df2, strat_time, end_time,
                                     canshu)
    print('runingtime:', time.process_time() - a, 's')
    return df0, df1, df2, (df0cols, df1cols, df2cols), res
Example #30
0
    def hlbreak_ls(self, hsmaall, length, nstd):

        hsmatrade = pd.DataFrame()
        for code in hsmaall['code'].unique():
            print(code)
            hsma = hsmaall[hsmaall['code'] == code].copy()
            hsma.index = range(hsma.shape[0])
            hsma['upper'] = talib.MAX(hsma.high.values, timeperiod=length)
            hsma['lower'] = talib.MIN(hsma.low.values, timeperiod=length)

            hsma['LS'] = 'N'
            temp = hsma.close.shift(1) > hsma.upper.shift(2)
            hsma.loc[temp, 'LS'] = 'L'
            temp = hsma.close.shift(1) < hsma.lower.shift(2)
            hsma.loc[temp, 'LS'] = 'S'

            if self.feelist[code] > 1:
                fee = self.feelist[code] / self.handlist[code] / hsma.loc[
                    hsma.shape[0] - 1, 'close']
            else:
                fee = self.feelist[code]
            hsmatradecode = self.LS_turn(hsma, fee)
            hsmatradecode['code'] = code

            hsmatrade = pd.concat([hsmatrade, hsmatradecode])

        return hsmatrade