Пример #1
0
 def get_df(symbol='BTCUSDT', tf='1h') -> pd.DataFrame:
     interval_dict = {
         '1m': Client.KLINE_INTERVAL_1MINUTE,
         '5m': Client.KLINE_INTERVAL_5MINUTE,
         '15m': Client.KLINE_INTERVAL_15MINUTE,
         '1h': Client.KLINE_INTERVAL_1HOUR,
         '4h': Client.KLINE_INTERVAL_4HOUR,
         '1d': Client.KLINE_INTERVAL_1DAY,
         '1w': Client.KLINE_INTERVAL_1WEEK,
         '1M': Client.KLINE_INTERVAL_1MONTH,
     }
     klines = client.futures_klines(symbol=symbol, interval=interval_dict[tf])
     rows_list = []
     for kline in klines:
         row_dict = {
             'date': datetime.fromtimestamp(int(str(kline[0])[0:10])),
             'open': float(kline[1]),
             'high': float(kline[2]),
             'low': float(kline[3]),
             'close': float(kline[4]),
             'volume': float(kline[5]),
         }
         rows_list.append(row_dict)
     df = pd.DataFrame(rows_list)
     df['rsi'] = ta.rsi(df.close, 14)
     df = pd.concat((df, ta.macd(df.close, 12, 26, 9)), axis=1)
     df['ema_20'], df['ema_50'] = ta.ema(df.close, 20), ta.ema(df.close, 50)
     if len(df) >= 288:
         df['ema_200'] = ta.ema(df.close, 200)
     else:
         df['ema_200'] = ta.ema(df.close, len(df.close)-3)
     df.set_index('date', inplace=True)
     df.rename_axis('date', inplace=True)
     df = df.tail(88)
     return df
Пример #2
0
def ema(s_interval: str, df_stock: pd.DataFrame, length: int,
        offset: int) -> pd.DataFrame:
    """Gets exponential moving average (EMA) for stock

    Parameters
    ----------
    s_interval: str
        Data interval
    df_stock: pd.DataFrame
        Dataframe of dates and prices
    length: int
        Length of EMA window
    offset: int
        Length of offset

    Returns
    ----------
    df_ta: pd.DataFrame
        Dataframe containing prices and EMA
    """
    # Daily
    if s_interval == "1440min":
        df_ta = ta.ema(df_stock["Adj Close"], length=length,
                       offset=offset).dropna()

    # Intraday
    else:
        df_ta = ta.ema(df_stock["Close"], length=length,
                       offset=offset).dropna()

    return pd.DataFrame(df_ta)
Пример #3
0
def ema(l_args, s_ticker, s_interval, df_stock):
    parser = argparse.ArgumentParser(
        prog='ema',
        description="""The Exponential Moving Average is a staple of technical 
                                     analysis and is used in countless technical indicators. In a Simple Moving 
                                     Average, each value in the time period carries equal weight, and values outside 
                                     of the time period are not included in the average. However, the Exponential 
                                     Moving Average is a cumulative calculation, including all data. Past values have 
                                     a diminishing contribution to the average, while more recent values have a greater 
                                     contribution. This method allows the moving average to be more responsive to changes 
                                     in the data.""")

    parser.add_argument('-l',
                        "--length",
                        action="store",
                        dest="n_length",
                        type=check_positive,
                        default=20,
                        help='length')
    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.ema(df_stock['5. adjusted close'],
                           length=ns_parser.n_length,
                           offset=ns_parser.n_offset).dropna()
            plot_stock_ta(df_stock['5. adjusted close'], s_ticker, df_ta,
                          f"{ns_parser.n_length} EMA")

        # Intraday
        else:
            df_ta = ta.ema(df_stock['4. close'],
                           length=ns_parser.n_length,
                           offset=ns_parser.n_offset).dropna()
            plot_stock_ta(df_stock['4. close'], s_ticker, df_ta,
                          f"{ns_parser.n_length} EMA")

    except:
        print("")
def bbands(df, n=20):
    #data = df.copy()
    high = df['high']*df['volume']
    low = df['low']*df['volume']
    #close = data['close']
    data = pd.DataFrame()
    upper_band = ta.ema(high, length=n)
    lower_band = ta.ema(low, length=n)
    upper_sdev = np.std(upper_band)
    lower_sdev = np.std(upper_band)
    data['bbands_upper'] = upper_band + upper_sdev * sdev_constant
    data['bbands_lower'] = lower_band - lower_sdev * sdev_constant
    return data
Пример #5
0
def todf(symbols=None, range=200):
    if symbols is None:
        raise ValueError("Require at least 1 Symbol")

    tick = hist_price(symbols, start=dateRange(range)[0])
    df = pd.DataFrame(columns=[
        "symbol", "dip50", "dip100", "pinBar50", "pinBar150", "tweezers50",
        "tweezers150", "oneSolCrow50", "oneSolCrow150", "morEveStar50",
        "morEveStar150", "engulfing50", "engulfing150", "Trend"
    ])
    for i in symbols:
        hist = tick.xs(i, level=0)
        sma50 = ta.sma(hist['close'], length=50)
        sma100 = ta.sma(hist['close'], length=100)
        sma150 = ta.sma(hist['close'], length=150)
        ema20 = ta.ema(hist['close'], length=20)
        ema40 = ta.ema(hist['close'], length=40)
        trnd = trend(sma50, sma150)
        prev2 = candle_dict(hist['open'][len(hist) - 2 - 1],
                            hist['high'][len(hist) - 2 - 1],
                            hist['low'][len(hist) - 2 - 1],
                            hist['close'][len(hist) - 2 - 1])
        prev1 = candle_dict(hist['open'][len(hist) - 1 - 1],
                            hist['high'][len(hist) - 1 - 1],
                            hist['low'][len(hist) - 1 - 1],
                            hist['close'][len(hist) - 1 - 1])
        current = candle_dict(hist['open'][len(hist) - 1],
                              hist['high'][len(hist) - 1],
                              hist['low'][len(hist) - 1],
                              hist['close'][len(hist) - 1])
        datadict = {
            "symbol": i,
            "dip50": dip50(hist, sma50, sma150, ema20, ema40),
            "dip100": dip100(hist, sma50, sma150, sma100, ema20, ema40),
            "pinBar50": PinBar(current, sma50[-1], trnd),
            "pinBar150": PinBar(current, sma150[-1], trnd),
            "tweezers50": tweezers(current, prev1, sma50[-1], trnd),
            "tweezers150": tweezers(current, prev1, sma150[-1], trnd),
            "oneSolCrow50": oneSolCrow(current, prev1, sma50[-1], trnd),
            "oneSolCrow150": oneSolCrow(current, prev1, sma150[-1], trnd),
            "morEveStar50": morEveStar(current, prev1, prev2, sma50[-1], trnd),
            "morEveStar150": morEveStar(current, prev1, prev2, sma150[-1],
                                        trnd),
            "engulfing50": engulfing(current, prev1, sma50[-1], trnd),
            "engulfing150": engulfing(current, prev1, sma150[-1], trnd),
            "Trend": trnd
        }
        df = df.append(datadict, ignore_index=True)
    df = df.set_index('symbol')
    return df
Пример #6
0
    def calculate(self, look_back, wallet):
        """
        Main strategy logic (the meat of the strategy)
        """
        (dataset_cnt, _) = common.get_dataset_count(look_back,
                                                    self.group_by_field)

        # Wait until we have enough data
        if dataset_cnt < self.min_history_ticks:
            print('dataset_cnt:', dataset_cnt)
            return self.actions

        self.actions.clear()
        new_action = TradeState.none

        # Calculate indicators
        df = look_back.tail(self.min_history_ticks)
        close = df['close']

        # ************** Calc EMA
        ema5 = ta.ema(close, length=5).values[-1]
        ema10 = ta.ema(close, length=10).values[-1]
        ema20 = ta.ema(close, length=20).values[-1]

        close_price = self.get_price(TradeState.none, df.tail(), self.pair)

        print('close_price:', close_price, 'ema:', ema20)
        if close_price < ema10 or close_price < ema20:
            new_action = TradeState.sell
        elif close_price > ema5 and close_price > ema10:
            new_action = TradeState.buy

        trade_price = self.get_price(new_action, df.tail(), self.pair)

        # Get stop-loss
        if new_action == TradeState.buy and self.stop_loss.calculate(
                close.values):
            print('stop-loss detected,..selling')
            new_action = TradeState.sell

        action = TradeAction(self.pair,
                             new_action,
                             amount=None,
                             rate=trade_price,
                             buy_sell_mode=self.buy_sell_mode)

        self.actions.append(action)
        return self.actions
Пример #7
0
def get_data():
    database = sqliteDb()
    currency = request.args.get('currency')
    timeframe = request.args.get('timeframe')
    indicator_name = request.args.get('indicator_name')
    indicator_period = request.args.get('indicator_period')
    candle = request.args.get('candle')
    response = database.getData(currency, timeframe)
    database.close()
    df = pd.DataFrame.from_records(
        response,
        columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
    if indicator_name == 'EMA':
        indicator = ta.ema(df['close'], length=int(indicator_period))
    elif indicator_name == 'RSI':
        indicator = ta.rsi(df['close'], length=int(indicator_period))
    indicator = indicator.fillna('undefined')
    dict = indicator.to_dict()
    result = {
        'open value': response[99 - int(candle)][1],
        'high value': response[99 - int(candle)][2],
        'low value': response[99 - int(candle)][3],
        'close value': response[99 - int(candle)][4],
        'timestamp': response[99 - int(candle)][0],
        indicator_name: dict[99 - int(candle)]
    }
    return json.dumps(result)
Пример #8
0
def initialize_vol_ema_one(data_center, ts_code):
    """
    单只股票的计算ema的值
    :param data_center:
    :param ts_code:
    :return:
    """
    # 查看一下表里面有没有数据,如果有的话,就不自动生成了
    exists = data_center.common_query(
        "select 1 from ema_value where ts_code='" + ts_code + "'")
    if len(exists) > 0:
        return
    # 对每个指标做计算
    query_close_sql = "select ts_code, trade_date, vol from stock_base_info where ts_code='"
    query_close_sql = query_close_sql + ts_code + "'"
    base_info_data = data_center.common_query_to_pandas(query_close_sql)
    vol_series = base_info_data['vol']
    if vol_series is None or len(vol_series) < 7:
        return
    # 对每个ema长度做计算
    write_data_frame = pandas.DataFrame(columns=())
    for i in range(3, 8):
        write_data_frame['ts_code'] = base_info_data['ts_code']
        write_data_frame['trade_date'] = base_info_data['trade_date']
        temp_ema = ta.ema(vol_series, length=i)
        write_data_frame['ema_' + str(i)] = temp_ema
    data_center.common_write_data_frame(write_data_frame, 'vol_ema')
Пример #9
0
def analysis(df, ma_f, ma_s, period):
    df["ema_f"] = ta.ema(high=df.high, low=df.low, close=df.close, length=ma_f)
    df["ema_s"] = ta.ema(high=df.high, low=df.low, close=df.close, length=ma_s)

    df.fillna(0, inplace=True)

    df['s'] = (df['ema_s'] - df['ema_s'].shift(1)) >= 0
    df['f'] = (df['ema_f'] - df['ema_f'].shift(1)) >= 0

    df['buy_ema'] = df['ema_f'] > df['ema_s']
    df['sell_ema'] = df['ema_f'] <= df['ema_s']

    df['buy_change'] = (df['buy_ema'] != df['buy_ema'].shift(1)) & df['buy_ema']
    df['sell_change'] = (df['sell_ema'] != df['sell_ema'].shift(1)) & df['sell_ema']

    # df["RSI"] = ta.rsi(high=df.high, low=df.low, close=df.close, length=period)
    # df['RSIs'] = (df['RSI'] - df['RSI'].shift(1)) >= 0
    # df['RSI_ups'] = df.groupby(
    #     (df['RSIs'] != df['RSIs'].shift(1)).cumsum()).cumcount() + 1
    # df['adx'] = ta.adx(high=df.high, low=df.low, close=df.close, length=period)['ADX_%s' % period]
    # df['adx_s'] = (df['adx'] - df['adx'].shift(1)) >= 0
    # df['adx_ups'] = df.groupby(
    #     (df['adx_s'] != df['adx_s'].shift(1)).cumsum()).cumcount() + 1
    # df['ATR'] = df.ta.atr()

    indicator_bb = BollingerBands(close=df.close, window=10, window_dev=1.8)
    df['bb_bbm'] = indicator_bb.bollinger_mavg()
    df['b_m'] = (df['bb_bbm'] - df['bb_bbm'].shift(1)) >= 0
    df['bb_bbh'] = indicator_bb.bollinger_hband()
    df['bb_bbl'] = indicator_bb.bollinger_lband()
    df['bb_bbhi'] = indicator_bb.bollinger_hband_indicator()
    df['bb_bbli'] = indicator_bb.bollinger_lband_indicator()

    df['pvt'] = ta.pvt(close=df.close, volume=df.volume)
    df['pvt_t'] = (df['pvt'] - df['pvt'].shift(1)) >= 0

    df['close_variation'] = df['close'] - df['close'].shift(1)
    #
    # df = ema(df, ma_f, ma_s)
    df = rsi(df, period)
    df = momentum(df)

    df['trend'] = df['momentum_s'] & df['RSIs']

    return df
Пример #10
0
def ema_strategy(
    ticker: str,
    df_stock: pd.DataFrame,
    ema_length: int,
    spy_bt: bool = True,
    no_bench: bool = False,
) -> bt.backtest.Result:
    """Perform backtest for simple EMA strategy.  Buys when price>EMA(l)

    Parameters
    ----------
    ticker : str
        Stock ticker
    df_stock : pd.DataFrame
        Dataframe of prices
    ema_length : int
        Length of ema window
    spy_bt : bool
        Boolean to add spy comparison
    no_bench : bool
        Boolean to not show buy and hold comparison

    Returns
    -------
    bt.backtest.Result
        Backtest results
    """
    ticker = ticker.lower()
    ema = pd.DataFrame()
    start_date = df_stock.index[0]
    prices = pd.DataFrame(df_stock["Adj Close"])
    prices.columns = [ticker]
    ema[ticker] = ta.ema(prices[ticker], ema_length)
    bt_strategy = bt.Strategy(
        "AboveEMA",
        [
            bt.algos.SelectWhere(prices >= ema),
            bt.algos.WeighEqually(),
            bt.algos.Rebalance(),
        ],
    )
    bt_backtest = bt.Backtest(bt_strategy, prices)
    backtests = [bt_backtest]
    if spy_bt:
        spy_bt = buy_and_hold("spy", start_date, "SPY Hold")
        backtests.append(spy_bt)
    if not no_bench:
        stock_bt = buy_and_hold(ticker, start_date, ticker.upper() + " Hold")
        backtests.append(stock_bt)

    res = bt.run(*backtests)
    return res
Пример #11
0
    def checkLongSignal(self, i = None):
        if self.holding:
            return False

        df = self.dataframe
        if i == None:
            i = len(df) - 1

        close = self.df_15min["close"].iloc[-1]
        close_24h = self.df_15min["close"].iloc[len(self.df_15min) - 96]
        change24h = close/close_24h

        ema25 = ta.ema(self.df_15min['close'], 25)
        ema50 = ta.ema(self.df_15min['close'], 50)
        rsi = ta.rsi(self.df_15min['close'], self.rsi_len)
        entry_signal = close <= ema25.iloc[-1]*self.ema_trigger and rsi.iloc[-1] <= self.rsi_threshold and ema50.iloc[-1] > ema25.iloc[-1]

        if entry_signal:
            self.bot_controller.disable_entry = True
            self.holding = True

        return entry_signal
Пример #12
0
def indicator_adder(df):
    '''
    this adds the most common indicators to a dataframe
    with lower case close open high low volume
    takes: dataframe
    returns : dataframe
    '''
    df['rsi'] = pta.rsi(df.close)
    df['riz'] = pta.rsi(df.close,length=2)
    df['vwap'] = pta.vwap(df.high,df.low,df.close,df.volume)
    df[['stoch_k','stoch_d']] = pta.stoch(df.high,df.low,df.close)
    if len(df)>20:
        df['ema'] = pta.ema(df.close,length=20)
    
    #if len(df)>6:
        #df        = super_trend(df)
    return df
Пример #13
0
def ema(values: pd.DataFrame, length: int, offset: int) -> pd.DataFrame:
    """Gets exponential moving average (EMA) for stock

    Parameters
    ----------
    values: pd.DataFrame
        Dataframe of dates and prices
    length: int
        Length of EMA window
    offset: int
        Length of offset

    Returns
    ----------
    pd.DataFrame
        Dataframe containing prices and EMA
    """
    return pd.DataFrame(ta.ema(values, length=length, offset=offset)).dropna()
Пример #14
0
def ema_judge(base_data, ema_length=5, buy_up_count=3, win_pct=0.07, lost_pct=0.03):
    """
    通过EMA指标来短期判定买入卖出,机械性的
    :param buy_up_count: 当EMA连续上涨多少天之后就买入
    :param lost_pct: 损失百分比,当损失达到这种程度的时候就卖出
    :param win_pct: 盈利百分比,当盈利达到这个程度的时候就卖出
    :param ema_length: EMA的长度
    :param base_data: 基础数据
    :return:
    """
    if base_data.empty or len(base_data) == 0:
        return None
    ret_data = pandas.DataFrame(columns=('flag', 'percent'))
    close = base_data['close']
    ema_value = ta.ema(close, length=5)
    if len(ema_value) <= ema_length:
        return None

    temp_dict = {
        "flag": Simulate.DO_NOTHING,
        'percent': 0
    }
    ret_data = ret_data.append(temp_dict, ignore_index=True)

    up_count = 0
    already_buy = False
    buy_price = 0
    for i in range(1, len(ema_value)):
        temp_dict = {
            "flag": Simulate.DO_NOTHING,
            'percent': 0
        }
        if ema_value.iat[i] > ema_value.iat[i - 1]:
            if up_count > buy_up_count and not already_buy:
                temp_dict['flag'] = Simulate.BUY_FLAG
                temp_dict['percent'] = 0.5
                buy_price = base_data.at[i, 'close']
                already_buy = True
                ret_data = ret_data.append(temp_dict, ignore_index=True)
                continue
            up_count = up_count + 1
        else:
            up_count = 0

        # 分析下盈利情况,然后决定是否卖出或者继续持有
        if not already_buy:
            ret_data = ret_data.append(temp_dict, ignore_index=True)
            continue

        curr_price = base_data.at[i, 'close']
        curr_win_pct = (curr_price - buy_price) / buy_price
        if curr_win_pct > win_pct:
            temp_dict['flag'] = Simulate.SOLD_FLAG
            temp_dict['percent'] = 1
            already_buy = False
        elif curr_win_pct <= -lost_pct:
            temp_dict['flag'] = Simulate.SOLD_FLAG
            temp_dict['percent'] = 1
            already_buy = False
        ret_data = ret_data.append(temp_dict, ignore_index=True)
    return ret_data
Пример #15
0
    return quotes


# only take most frequent stocks
symbols = Counter(df["Ticker"]).most_common(400)
symbols = [s[0] for s in symbols]
quotes = prefetch_agg(symbols)
bad_tickers = []

# calc TA
for ticker in tqdm(symbols, total=len(symbols), desc="Calculating TA"):
    try:
        quotes_df = pd.DataFrame(quotes[ticker]).transpose()
        quotes_df["rsi10"] = ta.rsi(quotes_df["c"], length=10)
        quotes_df["volumeEMA"] = ta.ema(quotes_df["v"], length=10)
        quotes[ticker] = quotes_df.to_dict(orient="index")
    except:
        bad_tickers.append(ticker)

# keep track of counts and reset each day
day = arrow.get(df["Time"].iloc[0].format("YYYY-MM-DD"))
counter = Counter()

data, rows = [], []
for idx, row in tqdm(df.iterrows(), total=len(df)):
    # new day - reset counter
    current_day = arrow.get(row["Time"].format("YYYY-MM-DD"))
    if current_day > day:
        counter = Counter()
        day = current_day
Пример #16
0
def get_EMA(data_series_of_target_feature, lookback_value):
    return panda.ema(data_series_of_target_feature, length=lookback_value)
Пример #17
0
    def __call__(self, df):

        df = df.iloc[-self.window:]
        high, low, closes = df["High"], df["Low"], df["Close"]
        EMA_20 = ta.ema(closes, 12)
        EMA_10 = ta.ema(closes, 6)
        ema20 = float(EMA_20.to_list()[-1])
        ema10 = float(EMA_10.to_list()[-1])
        close = closes.to_list()[-1]

        # 1) Wait for an uptrend (10 EMA (Orange) crosses ABOVE 20 EMA (Blue))
        if ema10 > ema20:
            self.uptrend = 1
            self.downtrend = 0
            self.ref = close

        if ema10 < ema20:
            self.downtrend = 1
            self.uptrend = 0
            self.ref = close

        # 2) Wait for price to breakout then retest the EMA's (either one(based on the trend type)) need to retest either 20 or 10.
        # only use 10 if there is a high trend, mening rapid changes
        if close > ema10:
            self.bull_confirmed = 1

        # 3) Wait for bullish confirmation candle after the retest
        if self.bull_confirmed and not self.inposition:
            # 4) Enter after the confirmation candle
            if close <= (ema10 or ema20):
                self.inposition = 1
                return 2

        # 5) Set a stop loss underneath the previous swing low (previous Zigzag point)
        if abs((close - self.ref) / self.ref) > 0.1:
            self.uptrend = 0
            self.bull_confirmed = 0
            self.downtrend = 0
            self.retest = 0
            self.uptrend = 0
            self.last_zigzag = 0
            self.inposition = 0
            print(abs((close - self.ref) / self.ref))
            return 0

        # 6) Take profit one the EMA's cross the other direction (10 EMA crosses BELOW 20 EMA)
        if self.downtrend:
            if self.inposition:
                self.uptrend = 0
                self.bull_confirmed = 0
                self.downtrend = 0
                self.retest = 0
                self.uptrend = 0
                self.last_zigzag = 0
                self.inposition = 0
                return 0
        return 1

        def render(self, df_res):
            df_res = df_res.dropna().copy()

            df_ind_s = df_res[df_res["action"] == 0]
            df_ind_b = df_res[df_res["action"] == 2]

            plt.figure(figsize=(20, 8))
            plt.plot(df_res["Date"], df_res["Close"], c="b")
            plt.scatter(df_ind_b["Date"],
                        df_res.loc[df_ind_b.index]["Close"],
                        c="green")
            plt.scatter(df_ind_s["Date"],
                        df_res.loc[df_ind_s.index]["Close"],
                        c="red")

            plt.show()
Пример #18
0
    new_dict = {}
    indic_dict = {}
    open1, high, low, close = get_close()
    new_dict['open'] = float(open1)
    new_dict['high'] = float(high)
    new_dict['low'] = float(low)
    new_dict['close'] = float(close)
    X_test = X_test.append(new_dict, ignore_index=True)
    if i < 51:
        print(X_test.tail())

    if i >= 51:
        bbands_close = ta.bbands(X_test['close'], length=50, std=2) #calculating indicators
        macd_close = ta.macd(X_test['close'], 5, 35, 5)
        rsi_close = np.array(ta.rsi(X_test['close'], 14))[-1]
        ema_5_close = np.array(ta.ema(X_test['close'], 5))[-1]
        ema_20_close = np.array(ta.ema(X_test['close'], 20))[-1]
        ema_50_close = np.array(ta.ema(X_test['close'], 50))[-1]
        indic_dict['open'] = float(open1)
        indic_dict['high'] = float(high)
        indic_dict['low'] = float(low)
        indic_dict['close'] = float(close)
        indic_dict['useless'] = bbands_close['BBM_50'].iloc[-1]
        indic_dict['bband1'] = bbands_close['BBL_50'].iloc[-1]
        indic_dict['bband2'] = bbands_close['BBU_50'].iloc[-1] #BUYS BUYS BUYS
        indic_dict['macd'] = macd_close['MACD_5_35_5'].iloc[-1]
        indic_dict['macdh'] = macd_close['MACDH_5_35_5'].iloc[-1]
        indic_dict['macds'] = macd_close['MACDS_5_35_5'].iloc[-1]
        indic_dict['rsi'] = rsi_close
        indic_dict['ema1'] = ema_5_close
        indic_dict['ema2'] = ema_20_close
def processSets(symbol):

    subset = symbols_data[symbols_data["Symbol"] == symbol]
    subset = subset.set_index('Date')
    subset['Forward Close'] = subset['Close'].shift(-n_forward)
    subset['Forward Return'] = (subset['Forward Close'] -
                                subset['Close']) / subset['Close']
    subset['VWP'] = subset['Close'] * subset['Volume']

    Short_EVWMA = pd.DataFrame(TA.EVWMA(subset, 12))
    Long_EVWMA = pd.DataFrame(TA.EVWMA(subset, 26))
    Short_EVWMA.columns = ['EVWMA_12']
    Long_EVWMA.columns = ['EVWMA_26']

    #p 209 of ttr doc
    MACD_EVWMA = pd.DataFrame(
        (Short_EVWMA['EVWMA_12'] - Long_EVWMA['EVWMA_26']) /
        Long_EVWMA['EVWMA_26'])
    MACD_EVWMA.columns = ['MACD-line']

    Signal_EVWMA = pd.DataFrame(ta.ema(MACD_EVWMA["MACD-line"], length=9))
    Signal_EVWMA.columns = ['Signal_EMA_9_MACD']
    subset['MACD_Signal'] = Signal_EVWMA

    prices = subset.loc[~subset.index.duplicated(keep='last')]
    prices = subset.reset_index()

    idx1 = subset.index

    merged = idx1.union(idx2)
    s = subset.reindex(merged)
    df = s.interpolate().dropna(axis=0, how='any')

    subset = df

    trades = []
    expectedReturns = []

    sdevs = []

    #conditions_ = []

    #rolling windows
    for i in range(0, width1):
        temp = subset.loc[frequency[i].strftime('%Y-%m-%d'):frequency[i +
                                                                      width2].
                          strftime('%Y-%m-%d')].copy()
        #temp = subset.loc[dateindex[i].strftime('%Y-%m-%d'):dateindex[i+width2].strftime('%Y-%m-%d')].copy()
        #adf_results = ts.adfuller(temp['Close'], 1)
        #H, c, val = compute_Hc(temp['Close'], kind='price', simplified=True)

        #data.loc[dateindex[i]:dateindex[i+width2]]

        result = []

        for ma_length in range(20, limit):

            if strategy == "EMA":

                temp[strategy] = ta.ema(temp[indicator], length=ma_length)
                temp['input'] = [
                    int(x) for x in temp[indicator] > temp[strategy]
                ]

            elif strategy == "SMA":

                temp[strategy] = temp[indicator].rolling(ma_length).mean()
                temp['input'] = [
                    int(x) for x in temp[indicator] > temp[strategy]
                ]

            df = temp.dropna()

            training = df.head(int(train_size * df.shape[0]))
            test = df.tail(int((1 - train_size) * df.shape[0]))

            tr_returns = training[training['input'] == 1]['Forward Return']
            test_returns = test[test['input'] == 1]['Forward Return']

            mean_forward_return_training = tr_returns.mean()
            mean_forward_return_test = test_returns.mean()
            pvalue = ttest_ind(tr_returns, test_returns, equal_var=False)[1]

            result.append({
                'ma_length': ma_length,
                'training_forward_return': mean_forward_return_training,
                'test_forward_return': mean_forward_return_test,
                'p-value': pvalue
            })

        result.sort(key=lambda x: -x['training_forward_return'])

        if strategy == "EMA":
            temp[strategy] = ta.ema(temp[indicator],
                                    length=result[0]['ma_length'])

        elif strategy == "SMA":
            temp[strategy] = temp[indicator].rolling(
                result[0]['ma_length']).mean()

        conditions = 0

        if (result[0]['p-value'] > .05
                and temp.iloc[-1][indicator] > temp.iloc[-1][strategy]):

            if (result[0]['training_forward_return'] > minExpectedReturn
                    and result[0]['test_forward_return'] > minExpectedReturn):
                conditions = conditions + 1

        if conditions >= 1:
            trades.append(temp.index[-1])
            expectedReturns.append((result[0]['training_forward_return'] +
                                    result[0]['test_forward_return']) / 2)
            sdevs.append(np.std(temp['Forward Return']))
            #print(predRet)
            #print(temp.iloc[-1]['MACD_Signal'])

    #print("starting set")
    set = pd.DataFrame()
    for i in range(0, len(trades)):

        value = pd.DataFrame(subset.loc[trades[i]]).transpose()
        value['ExpectedReturn'] = expectedReturns[i]
        value['sdev'] = sdevs[i]
        #value['conditions'] = conditions_[i]
        set = pd.concat([set, value])

    #display(set)

    return set
Пример #20
0
import numpy as np

from attr import define
from dotenv import load_dotenv
from ta.volatility import BollingerBands

from modules.crypto.processing import get_volume_analisys, get_volume_profile

load_dotenv()
bot = os.environ["telegram_token_bot"]

df = pd.read_csv('datasets/ETHUSDT-1m-sma-15.csv')

print(df)

df["EMA12"] = ta.ema(high=df.high, low=df.low, close=df.close, length=12)
df["RSI2"] = ta.rsi(high=df.high, low=df.low, close=df.close, length=14)
df['ATR2'] = df.ta.atr()
df['Momentum'] = df.ta.mom()
df['adx'] = ta.adx(high=df.high, low=df.low, close=df.close, length=14)['ADX_14']

print('---------------------')
df['pvt'] = ta.pvt(close=df.close, volume=df.volume)

indicator_bb = BollingerBands(close=df.close, window=14, window_dev=2)
df['bb_bbm'] = indicator_bb.bollinger_mavg()
df['bb_bbh'] = indicator_bb.bollinger_hband()
df['bb_bbl'] = indicator_bb.bollinger_lband()
df['bb_bbhi'] = indicator_bb.bollinger_hband_indicator()
df['bb_bbli'] = indicator_bb.bollinger_lband_indicator()
start = pd.to_datetime(start)
end = pd.to_datetime(end)

# Read data
data = yf.download(symbol, start, end)

# Adjusted Close Price
st.header(f"Adjusted Close Price\n {company_name}")
st.line_chart(data['Adj Close'])

# ## SMA and EMA
#Simple Moving Average
data['SMA'] = ta1.sma(data['Adj Close'], timeperiod=20)

# Exponential Moving Average
data['EMA'] = ta1.ema(data['Adj Close'], timeperiod=20)

# Plot
st.header(
    f"Simple Moving Average vs. Exponential Moving Average\n {company_name}")
st.line_chart(data[['Adj Close', 'SMA', 'EMA']])

# Bollinger Bands
data[['lower_band',
      'middle_band', 'upper_band']] = ta1.bbands(data['Adj Close'],
                                                 timeperiod=20).iloc[:, 0:3]

# Plot
st.header(f"Bollinger Bands\n {company_name}")
st.line_chart(data[['Adj Close', 'upper_band', 'middle_band', 'lower_band']])
Пример #22
0
#default val
df = make_riz_targets(df)
df = make_riz_targets(df,30,70)
df = make_riz_targets(df,20,80)
df = make_riz_targets(df,15,85)
df = make_riz_targets(df,40,60)
df.head()

## i can make my own vwap riz... sweet

import ta

ddf = df.copy

df['vwap_riz'] = pta.momentum.rsi(df['vwap'])
df['vwap_riz_ema']= pta.ema(df['vwap_riz'])
df['vwap_ab_avg'] = df['vwap_riz']>df['vwap_riz_ema']
df['vwap_bl_avg'] = df['vwap_riz']<df['vwap_riz_ema']

df

## im only going to do 2 different sto's b/c they kill so much of the df

df

df = df.join(pta.momentum.stoch(df.High,df.Low,df.Close))




multi = 2
Пример #23
0
def ema_cross(ticker: str, start_date: Union[str, datetime],
              other_args: List[str]):
    """Strategy where we go long/short when EMA(short) is greater than/less than EMA(short)

    Parameters
    ----------
    ticker : str
        Stock to test
    start : Union[str, datetime]
        Backtest start date.  Can be either string or datetime
    other_args : List[str]
        List of argparse arguments
    """
    parser = argparse.ArgumentParser(
        add_help=False,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        prog="ema_cross",
        description=
        "Cross between a long and a short Exponential Moving Average.",
    )
    parser.add_argument(
        "-l",
        "--long",
        default=50,
        dest="long",
        type=check_positive,
        help="Long EMA period",
    )
    parser.add_argument(
        "-s",
        "--short",
        default=20,
        dest="short",
        type=check_positive,
        help="Short EMA period",
    )
    parser.add_argument(
        "--spy",
        action="store_true",
        default=False,
        help="Flag to add spy hold comparison",
        dest="spy",
    )
    parser.add_argument(
        "--no_bench",
        action="store_true",
        default=False,
        help="Flag to not show buy and hold comparison",
        dest="no_bench",
    )
    parser.add_argument(
        "--no_short",
        action="store_false",
        default=True,
        dest="shortable",
        help="Flag that disables the short sell",
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return

        if ns_parser.long < ns_parser.short:
            print("Short EMA period is longer than Long EMA period\n")
            return

        ticker = ticker.lower()
        # prices = bt.get(ticker, start=start_date)
        prices = get_data(ticker, start_date)
        short_ema = pd.DataFrame(ta.ema(prices[ticker], ns_parser.short))
        short_ema.columns = [ticker]
        long_ema = pd.DataFrame(ta.ema(prices[ticker], ns_parser.long))
        long_ema.columns = [ticker]

        # signals
        signals = long_ema.copy()
        signals[short_ema > long_ema] = 1.0
        signals[short_ema <= long_ema] = -1.0 * ns_parser.shortable
        signals[long_ema.isnull()] = 0.0

        combined_data = bt.merge(signals, prices, short_ema, long_ema)
        combined_data.columns = ["signal", "price", "ema_short", "ema_long"]
        bt_strategy = bt.Strategy(
            "EMA_Cross",
            [
                bt.algos.WeighTarget(signals),
                bt.algos.Rebalance(),
            ],
        )
        bt_backtest = bt.Backtest(bt_strategy, prices)

        if ns_parser.spy:
            spy_bt = buy_and_hold("spy", start_date, "SPY Hold")
            if ns_parser.no_bench:
                res = bt.run(bt_backtest, spy_bt)
            else:
                stock_bt = buy_and_hold(ticker, start_date,
                                        ticker.upper() + " Hold")
                res = bt.run(bt_backtest, spy_bt, stock_bt)
        else:
            if ns_parser.no_bench:
                res = bt.run(bt_backtest)
            else:
                stock_bt = buy_and_hold(ticker, start_date,
                                        ticker.upper() + " Hold")
                res = bt.run(bt_backtest, stock_bt)

        plot_bt(res,
                f"EMA Cross for EMA({ns_parser.short})/EMA({ns_parser.long})")
        print(res.display(), "\n")

    except Exception as e:
        print(e, "\n")
Пример #24
0
import seaborn as sns
from sklearn.model_selection import train_test_split
from sklearn.metrics import classification_report, confusion_matrix
import pickle

sns.set()

initial = pd.read_csv(
    'https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&interval=1min&symbol=msft&apikey=OUMVBY0VK0HS8I9E&datatype=csv&outputsize=full'
)
initial = initial[::-1].reset_index(drop=True)
volume = initial['volume']
initial.drop(['volume', 'timestamp'], axis=1, inplace=True)
bbands = ta.bbands(initial['close'], length=50, std=2)  #calculating indicators
rsi = ta.rsi(initial['close'], length=20)
ema_50 = ta.ema(initial['close'], length=5)
ema_200 = ta.ema(initial['close'], length=20)
ema_500 = ta.ema(initial['close'], length=50)
#macd = ta.macd(initial['close'], 5, 35, 5)
vwap = ta.vwap(initial['high'], initial['low'], initial['close'], volume)
initial = pd.concat([initial, bbands, ema_50, ema_200, ema_500, vwap], axis=1)

initial.columns = [
    'open', 'high', 'low', 'close', 'bband1', 'useless', 'bband2', 'ema1',
    'ema2', 'ema3', 'vwap'
]
initialInvestment = 1000
b = backtester.Backtester(initialInvestment)
initial = initial.dropna()
X = initial[:-1]
y = initial['close'].shift(-1)
Пример #25
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
    stock = StockDataFrame.retype(subset[["Date","Open", "Close", "Adj Close", "High", "Low", "Volume"]])

    #stock.columns = ["open", "close", "adj close", "low", "close", "volume"]
    stock.index.names = ['dt']

    #EVWMA
    Short_EVWMA = pd.DataFrame(TA.EVWMA(stock,12))
    Long_EVWMA = pd.DataFrame(TA.EVWMA(stock,26))
    Short_EVWMA.columns = ['EVWMA_12']
    Long_EVWMA.columns = ['EVWMA_26']

    #p 209 of ttr doc
    MACD_EVWMA = pd.DataFrame(Short_EVWMA['EVWMA_12'] - Long_EVWMA['EVWMA_26'])
    MACD_EVWMA.columns = ['MACD-line']

    Signal_EVWMA = pd.DataFrame(ta.ema(MACD_EVWMA["MACD-line"], length=9))
    Signal_EVWMA.columns = ['Signal_EMA_9_MACD']
    Signal_EVWMA
    stock['custom'] = Signal_EVWMA['Signal_EMA_9_MACD']
    stock['RSI'] = computeRSI(stock['close']*stock['volume'], 14)
    stock[['bbands_upper', 'bbands_lower']] = bbands(stock)
    stock['ATR'] = atrVolume(stock)
    
    #stock = stock.set_index('dt')

    mergeCompare = pd.merge(stock['close'].shift(+1),stock['close'], how='inner', left_index=True, right_index=True)

    actualReturns = ((mergeCompare['close_y']-mergeCompare['close_x'])/mergeCompare['close_x'])

    orderbook = pd.DataFrame()
Пример #27
0
def ema(l_args, s_ticker, s_interval, df_stock):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="ema",
        description="""
            The Exponential Moving Average is a staple of technical
            analysis and is used in countless technical indicators. In a Simple Moving
            Average, each value in the time period carries equal weight, and values outside
            of the time period are not included in the average. However, the Exponential
            Moving Average is a cumulative calculation, including all data. Past values have
            a diminishing contribution to the average, while more recent values have a greater
            contribution. This method allows the moving average to be more responsive to changes
            in the data.
        """,
    )

    parser.add_argument(
        "-l",
        "--length",
        action="store",
        dest="n_length",
        type=check_positive,
        default=20,
        help="length",
    )
    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.ema(
                df_stock["5. adjusted close"],
                length=ns_parser.n_length,
                offset=ns_parser.n_offset,
            ).dropna()

        # Intraday
        else:
            df_ta = ta.ema(
                df_stock["4. close"],
                length=ns_parser.n_length,
                offset=ns_parser.n_offset,
            ).dropna()

        _, axPrice = plt.subplots()
        plt.title(f"{ns_parser.n_length} EMA on {s_ticker}")
        if s_interval == "1440min":
            plt.plot(
                df_stock["5. adjusted close"].index,
                df_stock["5. adjusted close"].values,
                "k",
                lw=3,
            )
            plt.xlim(
                df_stock["5. adjusted close"].index[0],
                df_stock["5. adjusted close"].index[-1],
            )
        else:
            plt.plot(df_stock["4. close"].index,
                     df_stock["4. close"].values,
                     "k",
                     lw=3)
            plt.xlim(df_stock["4. close"].index[0],
                     df_stock["4. close"].index[-1])
        plt.xlabel("Time")
        plt.ylabel(f"Share Price of {s_ticker} ($)")
        axTa = axPrice.twinx()
        plt.plot(df_ta.index, df_ta.values)
        # Pandas series
        if len(df_ta.shape) == 1:
            l_legend = [f"{ns_parser.n_length} EMA"]
        # Pandas dataframe
        else:
            l_legend = df_ta.columns.tolist()
        plt.legend(l_legend)
        axTa.set_ylabel("{ns_parser.n_length} EMA", color="tab:blue")
        axTa.spines["right"].set_color("tab:blue")
        axTa.tick_params(axis="y", colors="tab:blue")
        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.ion()
        plt.show()
        print("")

    except Exception as e:
        print(e)
        print("")
Пример #28
0
def simple_ema(ticker: str, start_date: Union[str, datetime],
               other_args: List[str]):
    """Strategy where stock is bought when Price > EMA(l)

    Parameters
    ----------
    ticker : str
        Stock to test
    start : Union[str, datetime]
        Backtest start date.  Can be either string or datetime
    other_args : List[str]
        List of argparse arguments
    """
    parser = argparse.ArgumentParser(
        add_help=False,
        formatter_class=argparse.ArgumentDefaultsHelpFormatter,
        prog="ema",
        description="Strategy where stock is bought when Price > EMA(l)",
    )
    parser.add_argument(
        "-l",
        default=20,
        dest="length",
        type=check_positive,
        help="EMA period to consider",
    )
    parser.add_argument(
        "--spy",
        action="store_true",
        default=False,
        help="Flag to add spy hold comparison",
        dest="spy",
    )
    parser.add_argument(
        "--no_bench",
        action="store_true",
        default=False,
        help="Flag to not show buy and hold comparison",
        dest="no_bench",
    )

    try:
        ns_parser = parse_known_args_and_warn(parser, other_args)
        if not ns_parser:
            return
        ticker = ticker.lower()
        ema = pd.DataFrame()
        # prices = bt.get(ticker, start=start_date)
        # bt.get not working
        prices = get_data(ticker, start_date)
        ema[ticker] = ta.ema(prices[ticker], ns_parser.length)
        bt_strategy = bt.Strategy(
            "AboveEMA",
            [
                bt.algos.SelectWhere(prices >= ema),
                bt.algos.WeighEqually(),
                bt.algos.Rebalance(),
            ],
        )
        bt_backtest = bt.Backtest(bt_strategy, prices)

        if ns_parser.spy:
            spy_bt = buy_and_hold("spy", start_date, "SPY Hold")
            if ns_parser.no_bench:
                res = bt.run(bt_backtest, spy_bt)
            else:
                stock_bt = buy_and_hold(ticker, start_date,
                                        ticker.upper() + " Hold")
                res = bt.run(bt_backtest, spy_bt, stock_bt)
        else:
            if ns_parser.no_bench:
                res = bt.run(bt_backtest)
            else:
                stock_bt = buy_and_hold(ticker, start_date,
                                        ticker.upper() + " Hold")
                res = bt.run(bt_backtest, stock_bt)

        plot_bt(res, f"Equity for EMA({ns_parser.length})")
        print(res.display(), "\n")

    except Exception as e:
        print(e, "\n")
Пример #29
0
 def setUp(self, df):
     df['slow_ma'] = ta.ema(df['close'], self.slow_ma_len)
     df['fast_ma'] = ta.ema(df['close'], self.fast_ma_len)
     self.dataframe = df
Пример #30
0
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