def cci( high_vals: pd.Series, low_vals: pd.Series, close_vals: pd.Series, length: int = 14, scalar: float = 0.0015, ) -> pd.DataFrame: """Commodity channel index Parameters ---------- high_vals: pd.Series High values low_values: pd.Series Low values close-values: pd.Series Close values length: int Length of window scalar: float Scalar variable Returns ---------- pd.DataFrame Dataframe of technical indicator """ return pd.DataFrame( ta.cci( high=high_vals, low=low_vals, close=close_vals, length=length, scalar=scalar, ).dropna())
def cci(s_interval: str, df_stock: pd.DataFrame, length: int, scalar: float) -> pd.DataFrame: """Commodity channel index Parameters ---------- s_interval: str Stock time interval df_stock: pd.DataFrame Dataframe of prices length: int Length of window scalar: float Scalar variable Returns ---------- df_ta: pd.DataFrame Dataframe of technical indicator """ # Daily if s_interval == "1440min": df_ta = ta.cci( high=df_stock["High"], low=df_stock["Low"], close=df_stock["Adj Close"], length=length, scalar=scalar, ).dropna() # Intraday else: df_ta = ta.cci( high=df_stock["High"], low=df_stock["Low"], close=df_stock["Close"], length=length, scalar=scalar, ).dropna() return pd.DataFrame(df_ta)
def on_15min_bar(self, bar: BarData): """""" self.cancel_all() am = self.am am.update_bar(bar) if not am.inited: return close = pd.Series(am.close_array) high = pd.Series(am.high_array) low = pd.Series(am.low_array) standard_deviation = ta.stdev(close=close, length=self.boll_window) deviations = self.boll_dev * standard_deviation mid = ta.sma(close=close, length=self.boll_window) self.boll_up, self.boll_down = (mid + deviations).iloc[-1], (mid - deviations).iloc[-1] self.cci_value = ta.cci(high, low, close, self.cci_window).iloc[-1] self.atr_value = ta.atr(high, low, close, self.atr_window).iloc[-1] if self.pos == 0: self.intra_trade_high = bar.high_price self.intra_trade_low = bar.low_price if self.cci_value > 0: self.buy(self.boll_up, self.fixed_size, True) elif self.cci_value < 0: self.short(self.boll_down, self.fixed_size, True) elif self.pos > 0: self.intra_trade_high = max(self.intra_trade_high, bar.high_price) self.intra_trade_low = bar.low_price self.long_stop = self.intra_trade_high - self.atr_value * self.sl_multiplier self.sell(self.long_stop, abs(self.pos), True) elif self.pos < 0: self.intra_trade_high = bar.high_price self.intra_trade_low = min(self.intra_trade_low, bar.low_price) self.short_stop = self.intra_trade_low + self.atr_value * self.sl_multiplier self.cover(self.short_stop, abs(self.pos), True) self.put_event()
def on_bar(self, bar: BarData): """ Callback of new bar data update. """ self.am.update_bar(bar) if not self.am.inited: self.set_signal_pos(0) close = pd.Series(self.am.close_array) high = pd.Series(self.am.high_array) low = pd.Series(self.am.low_array) cci_value = ta.cci(high, low, close, self.cci_window).iloc[-1] if cci_value >= self.cci_long: self.set_signal_pos(1) elif cci_value <= self.cci_short: self.set_signal_pos(-1) else: self.set_signal_pos(0)
def add_plots(df: pd.DataFrame, additional_charts: Dict[str, bool]): """Add additional plots to the candle chart. Parameters ---------- df : pd.DataFrame The source data additional_charts : Dict[str, bool] A dictionary of flags to include additional charts Returns ------- Tuple Tuple of lists containing the plots, legends and subplot legends """ panel_number = 2 plots_to_add = [] legends = [] subplot_legends = [] if additional_charts["ad"]: ad = ta.ad(df["High"], df["Low"], df["Close"], df["Volume"]) ad_plot = mpf.make_addplot(ad, panel=panel_number) plots_to_add.append(ad_plot) subplot_legends.extend([panel_number * 2, ["AD"]]) panel_number += 1 if additional_charts["bbands"]: bbands = ta.bbands(df["Close"]) bbands = bbands.drop("BBB_5_2.0", axis=1) bbands_plot = mpf.make_addplot(bbands, panel=0) plots_to_add.append(bbands_plot) legends.extend(["Lower BBand", "Middle BBand", "Upper BBand"]) if additional_charts["cci"]: cci = ta.cci(df["High"], df["Low"], df["Close"]) cci_plot = mpf.make_addplot(cci, panel=panel_number) plots_to_add.append(cci_plot) subplot_legends.extend([panel_number * 2, ["CCI"]]) panel_number += 1 if additional_charts["ema"]: ema = ta.ema(df["Close"]) ema_plot = mpf.make_addplot(ema, panel=0) plots_to_add.append(ema_plot) legends.append("10 EMA") if additional_charts["rsi"]: rsi = ta.rsi(df["Close"]) rsi_plot = mpf.make_addplot(rsi, panel=panel_number) plots_to_add.append(rsi_plot) subplot_legends.extend([panel_number * 2, ["RSI"]]) panel_number += 1 if additional_charts["obv"]: obv = ta.obv(df["Close"], df["Volume"]) obv_plot = mpf.make_addplot(obv, panel=panel_number) plots_to_add.append(obv_plot) subplot_legends.extend([panel_number * 2, ["OBV"]]) panel_number += 1 if additional_charts["sma"]: sma_length = [20, 50] for length in sma_length: sma = ta.sma(df["Close"], length=length) sma_plot = mpf.make_addplot(sma, panel=0) plots_to_add.append(sma_plot) legends.append(f"{length} SMA") if additional_charts["vwap"]: vwap = ta.vwap(df["High"], df["Low"], df["Close"], df["Volume"]) vwap_plot = mpf.make_addplot(vwap, panel=0) plots_to_add.append(vwap_plot) legends.append("vwap") return plots_to_add, legends, subplot_legends
def main(ticker_name, date_from, param_atr, param_cci_length=28): init_activity_log(ticker_name) df = new_prepare_data_today(ticker_name)[date_from:] df_atr = ta.atr(df['high'], df['low'], df['close'], length=14) df_atr.name = 'atr' df = df.join(df_atr) df_cci = ta.cci(df['high'], df['low'], df['close'], length=param_cci_length) df_cci.name = 'cci' df = df.join(df_cci) print(df.tail(10)) trade_init() indexmax = len(df) for i in range(0, indexmax): close = df.iloc[i]['close'] high = df.iloc[i]['high'] low = df.iloc[i]['low'] env_datetime = df.iloc[i]['datetime'] atr = df.iloc[i]['atr'] cci = df.iloc[i]['cci'] prev_cci = df.iloc[i - 1]['cci'] prev_close = df.iloc[i - 1]['close'] is_trade_closed = False actual_atr = atr * param_atr update_trade(ticker_name, close, high, low, env_datetime, actual_atr, prev_close) #print(str(prev_cci)) #print(str(cci)) if prev_cci < 0 and cci >= 0: if trade_type != '': close_trade(ticker_name, close, env_datetime) is_trade_closed = True new_env_datetime = env_datetime if is_trade_closed == True: new_env_datetime = datetime.strptime( env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z') + timedelta(minutes=1) new_env_datetime = datetime.strftime( new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z') open_trade(ticker_name, 'long', close, new_env_datetime, actual_atr) if prev_cci >= 0 and cci < 0: if trade_type != '': close_trade(ticker_name, close, env_datetime) is_trade_closed = True new_env_datetime = env_datetime if is_trade_closed == True: new_env_datetime = datetime.strptime( env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z') + timedelta(minutes=1) new_env_datetime = datetime.strftime( new_env_datetime, '%Y-%m-%dT%H:%M:%S.%f000Z') open_trade(ticker_name, 'short', close, new_env_datetime, actual_atr) print('---') print('from ' + date_from + ' to ' + datetime.strftime(datetime.now(), '%Y-%m-%d %H:%M:%S')) print('trades sum result: ' + str(trade_sum)) print('trades count: ' + str(trade_count)) persist_activity_log(ticker_name) """
def cci(l_args, s_ticker, s_interval, df_stock): parser = argparse.ArgumentParser( add_help=False, prog="cci", description=""" The CCI is designed to detect beginning and ending market trends. The range of 100 to -100 is the normal trading range. CCI values outside of this range indicate overbought or oversold conditions. You can also look for price divergence in the CCI. If the price is making new highs, and the CCI is not, then a price correction is likely. """, ) parser.add_argument( "-l", "--length", action="store", dest="n_length", type=check_positive, default=14, help="length", ) parser.add_argument( "-s", "--scalar", action="store", dest="n_scalar", type=check_positive, default=0.015, help="scalar", ) parser.add_argument( "-o", "--offset", action="store", dest="n_offset", type=check_positive, default=0, help="offset", ) try: ns_parser = parse_known_args_and_warn(parser, l_args) if not ns_parser: return # Daily if s_interval == "1440min": df_ta = ta.cci( high=df_stock["High"], low=df_stock["Low"], close=df_stock["Adj Close"], length=ns_parser.n_length, scalar=ns_parser.n_scalar, offset=ns_parser.n_offset, ).dropna() # Intraday else: df_ta = ta.cci( high=df_stock["High"], low=df_stock["Low"], close=df_stock["Close"], length=ns_parser.n_length, scalar=ns_parser.n_scalar, offset=ns_parser.n_offset, ).dropna() plt.figure(figsize=plot_autoscale(), dpi=PLOT_DPI) plt.subplot(211) plt.title(f"Commodity Channel Index (CCI) on {s_ticker}") if s_interval == "1440min": plt.plot(df_stock.index, df_stock["Adj Close"].values, "k", lw=2) else: plt.plot(df_stock.index, df_stock["Close"].values, "k", lw=2) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.ylabel("Share Price ($)") plt.grid(b=True, which="major", color="#666666", linestyle="-") plt.minorticks_on() plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) plt.subplot(212) plt.plot(df_ta.index, df_ta.values, "b", lw=2) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.axhspan(100, plt.gca().get_ylim()[1], facecolor="r", alpha=0.2) plt.axhspan(plt.gca().get_ylim()[0], -100, facecolor="g", alpha=0.2) plt.axhline(100, linewidth=3, color="r", ls="--") plt.axhline(-100, linewidth=3, color="g", ls="--") plt.xlabel("Time") plt.grid(b=True, which="major", color="#666666", linestyle="-") plt.minorticks_on() plt.grid(b=True, which="minor", color="#999999", linestyle="-", alpha=0.2) plt.gca().twinx() plt.ylim(plt.gca().get_ylim()) plt.yticks([0.2, 0.8], ("OVERSOLD", "OVERBOUGHT")) if gtff.USE_ION: plt.ion() plt.show() print("") except Exception as e: print(e) print("")
def cci(l_args, s_ticker, s_interval, df_stock): parser = argparse.ArgumentParser( prog='cci', description= """ The CCI is designed to detect beginning and ending market trends. The range of 100 to -100 is the normal trading range. CCI values outside of this range indicate overbought or oversold conditions. You can also look for price divergence in the CCI. If the price is making new highs, and the CCI is not, then a price correction is likely. """) parser.add_argument('-l', "--length", action="store", dest="n_length", type=check_positive, default=14, help='length') parser.add_argument('-s', "--scalar", action="store", dest="n_scalar", type=check_positive, default=0.015, help='scalar') parser.add_argument('-o', "--offset", action="store", dest="n_offset", type=check_positive, default=0, help='offset') try: (ns_parser, l_unknown_args) = parser.parse_known_args(l_args) if l_unknown_args: print( f"The following args couldn't be interpreted: {l_unknown_args}\n" ) return # Daily if s_interval == "1440min": df_ta = ta.cci(high=df_stock['2. high'], low=df_stock['3. low'], close=df_stock['5. adjusted close'], length=ns_parser.n_length, scalar=ns_parser.n_scalar, offset=ns_parser.n_offset).dropna() plt.subplot(211) plt.title(f"Commodity Channel Index (CCI) on {s_ticker}") plt.plot(df_stock.index, df_stock['5. adjusted close'].values, 'k', lw=2) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.ylabel(f'Share Price ($)') plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) plt.subplot(212) plt.plot(df_ta.index, df_ta.values, 'b', lw=2) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.axhspan(100, plt.gca().get_ylim()[1], facecolor='r', alpha=0.2) plt.axhspan(plt.gca().get_ylim()[0], -100, facecolor='g', alpha=0.2) plt.axhline(100, linewidth=3, color='r', ls='--') plt.axhline(-100, linewidth=3, color='g', ls='--') plt.xlabel('Time') plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) plt.gca().twinx() plt.ylim(plt.gca().get_ylim()) plt.yticks([.2, .8], ('OVERSOLD', 'OVERBOUGHT')) plt.show() # Intraday else: df_ta = ta.cci(high=df_stock['2. high'], low=df_stock['3. low'], close=df_stock['4. close'], length=ns_parser.n_length, scalar=ns_parser.n_scalar, offset=ns_parser.n_offset).dropna() plt.subplot(211) plt.title(f"Commodity Channel Index (CCI) on {s_ticker}") plt.plot(df_stock.index, df_stock['4. close'].values, 'k', lw=2) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.ylabel(f'Share Price ($)') plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) plt.subplot(212) plt.plot(df_ta.index, df_ta.values, 'b', lw=2) plt.xlim(df_stock.index[0], df_stock.index[-1]) plt.axhspan(100, plt.gca().get_ylim()[1], facecolor='r', alpha=0.2) plt.axhspan(plt.gca().get_ylim()[0], -100, facecolor='g', alpha=0.2) plt.axhline(100, linewidth=3, color='r', ls='--') plt.axhline(-100, linewidth=3, color='g', ls='--') plt.xlabel('Time') plt.grid(b=True, which='major', color='#666666', linestyle='-') plt.minorticks_on() plt.grid(b=True, which='minor', color='#999999', linestyle='-', alpha=0.2) plt.gca().twinx() plt.ylim(plt.gca().get_ylim()) plt.yticks([.2, .8], ('OVERSOLD', 'OVERBOUGHT')) plt.show() print("") except: print("")
def add_plots(df, ns_parser): panel_number = 2 plots_to_add = [] legends = [] subplot_legends = [] if ns_parser.ad: ad = ta.ad(df["High"], df["Low"], df["Close"], df["Volume"]) ad_plot = mpf.make_addplot(ad, panel=panel_number) plots_to_add.append(ad_plot) subplot_legends.extend([panel_number * 2, ["AD"]]) panel_number += 1 if ns_parser.bbands: bbands = ta.bbands(df["Close"]) bbands = bbands.drop("BBB_5_2.0", axis=1) bbands_plot = mpf.make_addplot(bbands, panel=0) plots_to_add.append(bbands_plot) legends.extend(["Lower BBand", "Middle BBand", "Upper BBand"]) if ns_parser.cci: cci = ta.cci(df["High"], df["Low"], df["Close"]) cci_plot = mpf.make_addplot(cci, panel=panel_number) plots_to_add.append(cci_plot) subplot_legends.extend([panel_number * 2, ["CCI"]]) panel_number += 1 if ns_parser.ema: ema = ta.ema(df["Close"]) ema_plot = mpf.make_addplot(ema, panel=0) plots_to_add.append(ema_plot) legends.append("10 EMA") if ns_parser.rsi: rsi = ta.rsi(df["Close"]) rsi_plot = mpf.make_addplot(rsi, panel=panel_number) plots_to_add.append(rsi_plot) subplot_legends.extend([panel_number * 2, ["RSI"]]) panel_number += 1 if ns_parser.obv: obv = ta.obv(df["Close"], df["Volume"]) obv_plot = mpf.make_addplot(obv, panel=panel_number) plots_to_add.append(obv_plot) subplot_legends.extend([panel_number * 2, ["OBV"]]) panel_number += 1 if ns_parser.sma: sma_length = [20, 50] for length in sma_length: sma = ta.sma(df["Close"], length=length) sma_plot = mpf.make_addplot(sma, panel=0) plots_to_add.append(sma_plot) legends.append(f"{length} SMA") if ns_parser.vwap: vwap = ta.vwap(df["High"], df["Low"], df["Close"], df["Volume"]) vwap_plot = mpf.make_addplot(vwap, panel=0) plots_to_add.append(vwap_plot) legends.append("vwap") return plots_to_add, legends, subplot_legends
def create_env(data, config): features = [] for c in data.columns[1:]: s = Stream.source(list(data[c]), dtype="float").rename(data[c].name) features += [s] cp = Stream.select(features, lambda s: s.name == "close") high_price = data['high'] low_price = data['low'] close_price = data['close'] # print(data['volume']) try: data['date'] except KeyError: data['date'] = data.index features = [ cp.rename('USD/BTC'), cp.log().diff().rename("lr"), rsi(cp, period=14).rename("rsi"), macd(cp, fast=10, slow=50, signal=5).rename("macd"), Stream.source(ta.cci(high_price, low_price, close_price)).rename('cci') # cp.rolling(window=10).mean().rename("fast"), # cp.rolling(window=50).mean().rename("medium"), # cp.rolling(window=100).mean().rename("slow") ] feed = DataFeed(features) feed.compile() # for i in range(5): # print(feed.next()) coinbase = Exchange("coinbase", service=execute_order)(cp) cash = Wallet(coinbase, 100000 * USD) asset = Wallet(coinbase, 10 * BTC) portfolio = Portfolio(USD, [cash, asset]) # reward_scheme = PBR(price=cp) reward_scheme = RiskAdjustedReturns() # action_scheme = BSH(cash=cash, asset=asset).attach(reward_scheme) action_scheme = ManagedRiskOrders() renderer_feed = DataFeed([ Stream.source(list(data["date"])).rename("date"), Stream.source(list(data["open"]), dtype="float").rename("open"), Stream.source(list(data["high"]), dtype="float").rename("high"), Stream.source(list(data["low"]), dtype="float").rename("low"), Stream.source(list(data["close"]), dtype="float").rename("close"), Stream.source(list(data["volume"]), dtype="float").rename("volume"), #Stream.sensor(action_scheme, lambda s: s.action, dtype="float").rename("action") ]) renderer = PlotlyTradingChart() environment = default.create( feed=feed, portfolio=portfolio, action_scheme=action_scheme, # The DQN example uses action_scheme="managed-risk" reward_scheme=reward_scheme, # The DQN uses reward_scheme="risk-adjusted" renderer_feed=renderer_feed, renderer=renderer, window_size=config["window_size"], max_allowed_loss=0.6 ) return environment
# Add Bollinger Bands features df['bbL'] = df2.iloc[:, 0] df['bbM'] = df2.iloc[:, 1] df['bbU'] = df2.iloc[:, 2] # Add Awesome Oscillator df["ao"] = ta.ao(high=df["High"], low=df["Low"]) # Add more stuff df["apo"] = ta.apo(close=df["Close"]) df["bop"] = ta.bop(open_=df["Open"], high=df["High"], low=df["Low"], close=df["Close"]) df["cci"] = ta.cci(high=df["High"], low=df["Low"], close=df["Close"]) df["cg"] = ta.cg(close=df["Close"]) df["cmo"] = ta.cmo(close=df["Close"]) df["cpk"] = ta.coppock(close=df["Close"]) #df["fish"]=ta.fisher(high=df["High"],low=df["Low"]) #df["kst"]=ta.kst(close=df["Close"]) #df["macd"]=ta.macd(close=df["Close"]) df["mom"] = ta.mom(close=df["Close"]) #df["ppo"]=ta.ppo(close=df["Close"]) df["roc"] = ta.roc(close=df["Close"]) df["rsi"] = ta.rsi(close=df["Close"]) #df["rvi"]=ta.rvi(open_=df["Open"],high=df["High"],low=df["Low"],close=df["Close"]) df["slope"] = ta.slope(close=df["Close"]) #df["stoch"]=ta.stoch(high=df["High"],low=df["Low"],close=df["Close"]) df["trix"] = ta.trix(close=df["Close"]) df["tsi"] = ta.tsi(close=df["Close"])