示例#1
0
def sma(s_interval: str, df_stock: pd.DataFrame, length: int,
        offset: int) -> pd.DataFrame:
    """Gets simple moving average (EMA) for stock

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

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

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

    return pd.DataFrame(df_ta)
示例#2
0
def task():
    for i in range(100):
        print('check')
        cursor.execute("SELECT * from config")
        results = cursor.fetchone()
        url = results[8]
        resjson = requests.get(url).json()
        if (resjson['s'] != 'error'):
            candleinfo = resjson['candles']
            columns = ['timestamp', 'Open', 'High', 'Low', 'Close', 'OI']
            df = pd.DataFrame(candleinfo, columns=columns)
            Open = df['Open']
            High = df['High']
            Low = df['Low']
            Close = df['Close'].values
            sma9 = ta.sma(df["Close"], length=9)
            sma21 = ta.sma(df["Close"], length=21)
            value = (Open + High + Low + Close) / 4
            # print(sma9.iloc[-2])
            # print(sma21.iloc[-2])
            if (sma9.iloc[-2] < sma21.iloc[-2]) and (sma9.iloc[-9] >
                                                     sma21.iloc[-9]):
                print('BUy')
                storetrade(75, 1, 'nifty', Close.tail(1), 1, 'sma921')
            if (sma9.iloc[-2] > sma21.iloc[-2]) and (sma9.iloc[-9] <
                                                     sma21.iloc[-9]):
                print('Sell')
                storetrade(75, -1, 'nifty', Close[-1], 1, 'sma921')
        time.sleep(60)
示例#3
0
 def act(self):
     vals = self._getvals()
     self.lowersma = ta.sma(vals, length=GoldenCross.LOWER_LENGTH)
     self.uppersma = ta.sma(vals, length=GoldenCross.UPPER_LENGTH)
     if not self._lower_above_upper():
         self._handle_negative()
         return
     if self.negative_flag:
         self._reset_negative_flag()
     self._handle_positive()
示例#4
0
def add_sma_crossover():
    data['LMA'] = ta.sma(data['4. close'], 21)
    data['SMA'] = ta.sma(data['4. close'], 9)
    data['psma'] = data['SMA'].shift(1)
    data['plma'] = data['LMA'].shift(1)
    #if (((data['SMA'][-1]>data['LMA'][-1])and(data['psma'][-1]<data['plma'][-1])) or ((data['SMA'][-1]<data['LMA'][-1])and(data['psma'][-1]>data['plma'][-1]))) or (((data['SMA'][-2]>data['LMA'][-2])and(data['psma'][-2]<data['plma'][-2])) or ((data['SMA'][-2]<data['LMA'][-2])and(data['psma'][-2]>data['plma'][-2]))) :
    data['buy_sma'] = (data['SMA'] > data['LMA']) & (data['psma'] <
                                                     data['plma'])
    data['sell_sma'] = (data['SMA'] < data['LMA']) & (data['psma'] >
                                                      data['plma'])
示例#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
    def on_15min_bar(self, bar: BarData):
        """"""
        self.am15.update_bar(bar)
        if not self.am15.inited:
            return

        close_15 = pd.Series(self.am15.close_array)

        self.fast_ma = ta.sma(close_15, self.fast_window).iloc[-1]
        self.slow_ma = ta.sma(close_15, self.slow_window).iloc[-1]

        if self.fast_ma > self.slow_ma:
            self.ma_trend = 1
        else:
            self.ma_trend = -1
示例#7
0
    def on_5min_bar(self, bar: BarData):
        """"""
        self.am.update_bar(bar)
        if not self.am.inited:
            self.set_signal_pos(0)

        close = pd.Series(self.am.close_array)
        fast_ma = ta.sma(close, self.fast_window).iloc[-1]
        slow_ma = ta.sma(close, self.slow_window).iloc[-1]

        if fast_ma > slow_ma:
            self.set_signal_pos(1)
        elif fast_ma < slow_ma:
            self.set_signal_pos(-1)
        else:
            self.set_signal_pos(0)
 def consume(self, candle: TDACandle):
     self.candles.append(candle)
     vals = self._getvals()[0]
     averages = list(
         filter(lambda a: a is not None,
                [ta.sma(vals, length=length) for length in self.lengths]))
     return averages
示例#9
0
    def on_5min_bar(self, bar: BarData):
        """"""
        for orderid in self.vt_orderids:
            self.cancel_order(orderid)
        self.vt_orderids.clear()

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        high = pd.Series(am.high_array)
        low = pd.Series(am.low_array)
        close = pd.Series(am.close_array)

        range_ = ta.true_range(high, low, close)

        basis = ta.sma(close, self.kk_length)
        band = ta.sma(range_, self.kk_length)
        up = basis + self.kk_dev * band
        down = basis - self.kk_dev * band

        self.kk_up, self.kk_down = up.iloc[-1], down.iloc[-1]

        if self.pos == 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = bar.low_price
            self.send_oco_order(self.kk_up, self.kk_down, self.fixed_size)

        elif self.pos > 0:
            self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
            self.intra_trade_low = bar.low_price

            vt_orderids = self.sell(self.intra_trade_high * (1 - self.trailing_percent / 100),
                                    abs(self.pos), True)
            self.vt_orderids.extend(vt_orderids)

        elif self.pos < 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = min(self.intra_trade_low, bar.low_price)

            vt_orderids = self.cover(self.intra_trade_low * (1 + self.trailing_percent / 100),
                                     abs(self.pos), True)
            self.vt_orderids.extend(vt_orderids)

        self.put_event()
示例#10
0
    def extract_features(self):
        min_max_scaler = preprocessing.MinMaxScaler()

        # RSI
        # ref in https://arxiv.org/pdf/1911.10107.pdf
        rsi = ta.rsi(self.data.close, length=28)
        normalized_rsi = rsi.to_numpy().reshape(-1,
                                                1) / 100 - 0.5  # (-0.5, 0.5)

        # normalized close
        # ref in https://arxiv.org/pdf/1911.10107.pdf
        min_max_scaler = preprocessing.MinMaxScaler()
        normalized_close = min_max_scaler.fit_transform(
            self.data.close.to_frame()).reshape(-1, 1) - 0.5

        # normalized return
        # ref in https://arxiv.org/pdf/1911.10107.pdf
        ret_window = 60
        ret_60 = self.data.close / self.data.close.shift(ret_window) - 1
        normalized_ret_60 = ret_60 / ta.stdev(
            ret_60, ret_window)  #ret_60.rolling(ret_window).std()
        normalized_ret_60 = normalized_ret_60.to_numpy().reshape(-1, 1)

        ret_window = 120
        ret_120 = self.data.close / self.data.close.shift(ret_window) - 1
        normalized_ret_120 = ret_120 / ta.stdev(ret_120, ret_window)
        normalized_ret_120 = normalized_ret_120.to_numpy().reshape(-1, 1)

        # MACD indicators
        # ref in https://arxiv.org/pdf/1911.10107.pdf
        qt = (ta.sma(self.data.close, 30) -
              ta.sma(self.data.close, 60)) / ta.stdev(self.data.close, 60)
        macd = qt / ta.stdev(qt, 60)
        macd = macd.to_numpy().reshape(-1, 1)

        # concat features
        features = np.concatenate(
            (normalized_rsi, normalized_close, normalized_ret_60,
             normalized_ret_120, macd),
            axis=1)
        self.features = features
示例#11
0
 def __setHistory__(self, path):
     df = pd.read_csv(path)
     df = df.dropna()
     df = df.iloc[::-1]
     df = df.reset_index(drop=True)
     sma50 = ta.sma(df["close"], length=50)
     df = pd.concat([
         df,
         sma50,
     ], axis=1)
     df = df[(df['SMA_50'] > 0)]
     df = df.reset_index(drop=True)
     return df
示例#12
0
def pandasta():
    cursor.execute("SELECT * from config")
    results = cursor.fetchone()
    url = results[8]
    # url = 'https://data.fyers.in/history/V7/?symbol=NSE%3ANIFTY50-INDEX&resolution=1&from=1620561415&to=1620790435&token_id=gAAAAABgm0w-XnrWX52NA-h4wMaK6YIxWE25nhMIqpOHjmBVyaiMjh0qIAABt0Z7x_iT0_h8SBgpUTb_qFQX9flwWap_ZvWhrqwpIQ0ma-obBr7UqGOeVqM%3D&contFlag=1&marketStat=75946787eb1b0c34d9effd84d9a48ff3&dataReq=1620790375'
    resjson = requests.get(url).json()
    candleinfo = resjson['candles']
    columns = ['timestamp', 'Open', 'High', 'Low', 'Close', 'OI']
    df = pd.DataFrame(candleinfo, columns=columns)
    df.reset_index()
    Open = df['Open']
    High = df['High']
    Low = df['Low']
    Close = df['Close'].values
    sma9 = ta.sma(df["Close"], length=9)
    sma21 = ta.sma(df["Close"], length=21)
    print(Close[-1])
    # print(macdhist[-2])
    # macdhist = macdhist[~np.isnan(macdhist)]
    # return render_template('index.html', results=candleinfo)

    return 'macd'
    def on_bar(self, bar: BarData):
        """
        Callback of new bar data update.
        """

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        close = pd.Series(am.close_array)

        fast_ma = ta.sma(close, self.fast_window)
        self.fast_ma0 = fast_ma.iloc[-1]
        self.fast_ma1 = fast_ma.iloc[-2]

        slow_ma = ta.sma(close, self.slow_window)
        self.slow_ma0 = slow_ma.iloc[-1]
        self.slow_ma1 = slow_ma.iloc[-2]

        cross_over = self.fast_ma0 > self.slow_ma0 and self.fast_ma1 < self.slow_ma1
        cross_below = self.fast_ma0 < self.slow_ma0 and self.fast_ma1 > self.slow_ma1

        if cross_over:
            if self.pos == 0:
                self.buy(bar.close_price, 1)
            elif self.pos < 0:
                self.cover(bar.close_price, 1)
                self.buy(bar.close_price, 1)

        elif cross_below:
            if self.pos == 0:
                self.short(bar.close_price, 1)
            elif self.pos > 0:
                self.sell(bar.close_price, 1)
                self.short(bar.close_price, 1)

        self.put_event()
示例#14
0
def calculate_moving_average(source, debug_param=False):
    '''
    ### Generate mean values
    # Generate features - Mean value

    '''

    if not debug_param:
        #meanList = [2, 5, 8, 10, 13, 15, 18, 20, 22, 34, 40, 50, 75, 100, 125, 150, 175, 200];
        meanList = [20, 50, 75, 100, 150, 200]
    # meanList = [5, 10, 20, 50, 100, 200];
    else:
        meanList = [50, 200]

    close = source['Close']
    meanfeatures = pd.DataFrame(index=source.index)

    for i in meanList:
        # Mean
        ta.sma(close, i, 0)
        meanCol = ta.sma(close, i, 0)  #MA(close, i, 0);  # Trailing MA with i
        # meanCol.fillna(0, inplace=True)
        meanColreshaped = np.reshape(meanCol.values,
                                     (1, np.product(meanCol.values.shape)))[0]
        # Calculate diff from price in %
        diffPriceCol = np.divide(meanColreshaped - close.values, close.values)
        temp_source = pd.DataFrame(diffPriceCol,
                                   columns=['MA' + str(i) + 'Norm'])
        # print(temp_source)
        meanfeatures = meanfeatures.join(temp_source)
        # meanTable(:,i) = diffPriceCol;
        # print("Calculated MA{}".format(i));

    print("Number of features: {}".format(meanfeatures.shape))
    print(meanfeatures.head(5))

    return meanfeatures
示例#15
0
def generate_features_data():
    market_data_df = pd.DataFrame(
        columns=['timestamp', 'high', 'low', 'open', 'close', 'volume'])
    market_data_df = market_data_df.append(data())
    timestamp_df = market_data_df['timestamp'].copy(deep=True)
    slow_vwma_value_df = pd.DataFrame(
        vwma(market_data_df.close, market_data_df.volume, length=15, offset=0))
    fast_vwma_value_df = pd.DataFrame(
        vwma(market_data_df.close, market_data_df.volume, length=5, offset=0))
    slow_sma_value_df = pd.DataFrame(sma(market_data_df.close, 15))
    fast_sma_value_df = pd.DataFrame(sma(market_data_df.close, 5))
    rsi_data_value_df = pd.DataFrame(rsi(market_data_df.close, 10))

    slow_vwma_df = pd.concat([timestamp_df, slow_vwma_value_df], axis=1)
    fast_vwma_df = pd.concat([timestamp_df, fast_vwma_value_df], axis=1)
    slow_sma_df = pd.concat([timestamp_df, slow_sma_value_df], axis=1)
    fast_sma_df = pd.concat([timestamp_df, fast_sma_value_df], axis=1)
    rsi_df = pd.concat([timestamp_df, rsi_data_value_df], axis=1)

    slow_vwma_df.to_csv('slow_vwma_data.csv', index=False)
    fast_vwma_df.to_csv('fast_vwma_data.csv', index=False)
    slow_sma_df.to_csv('slow_sma_data.csv', index=False)
    fast_sma_df.to_csv('fast_sma_data.csv', index=False)
    rsi_df.to_csv('rsi_data.csv', index=False)
示例#16
0
    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()
示例#17
0
def sma(values: pd.DataFrame, length: int, offset: int) -> pd.DataFrame:
    """Gets simple moving average (EMA) for stock

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

     Returns
     ----------
    pd.DataFrame
         Dataframe containing prices and SMA
    """
    return pd.DataFrame(ta.sma(values, length=length, offset=offset)).dropna()
示例#18
0
    def on_15min_bar(self, bar: BarData):
        self.cancel_all()

        am = self.am
        am.update_bar(bar)
        if not am.inited:
            return

        high = pd.Series(am.close_array)
        low = pd.Series(am.low_array)
        close = pd.Series(am.close_array)

        atr_array = ta.atr(high, low, close, self.atr_length)
        self.atr_value = atr_array.iloc[-1]

        self.atr_ma = ta.sma(atr_array, self.atr_ma_length).iloc[-1]
        self.rsi_value = ta.rsi(close, self.rsi_length).iloc[-1]

        if self.pos == 0:
            self.intra_trade_high = bar.high_price
            self.intra_trade_low = bar.low_price

            self.trading_size = self.trading_money / bar.close_price
            if self.atr_value > self.atr_ma:
                if self.rsi_value > self.rsi_buy:
                    self.buy(bar.close_price + 5, self.trading_size)
                elif self.rsi_value < self.rsi_sell:
                    self.short(bar.close_price - 5, self.trading_size)

        elif self.pos > 0:
            self.intra_trade_high = max(self.intra_trade_high, bar.high_price)
            self.intra_trade_low = bar.low_price

            long_stop = self.intra_trade_high * \
                        (1 - self.trailing_percent / 100)
            self.sell(long_stop, abs(self.pos), stop=True)

        elif self.pos < 0:
            self.intra_trade_low = min(self.intra_trade_low, bar.low_price)
            self.intra_trade_high = bar.high_price

            short_stop = self.intra_trade_low * \
                         (1 + self.trailing_percent / 100)
            self.cover(short_stop, abs(self.pos), stop=True)
示例#19
0
                    int(data['event_time'] / 1000),
                    data['kline']['open_price'], data['kline']['high_price'],
                    data['kline']['low_price'], data['kline']['close_price'],
                    data['kline']['base_volume']
                ])
                if len(data_list) < min_items:
                    print(
                        f"Please wait, we need {min_items - len(data_list)} more klines!"
                    )
                else:
                    # We create a completely new dataframe with each loop. There is also the possibility to work with
                    # `pd.concat()` or `df.append()`:
                    # https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.append.html
                    df = pd.DataFrame(data_list,
                                      columns=[
                                          'time', 'open', 'high', 'low',
                                          'close', 'volume'
                                      ])
                    # Now we extend the array with new columns, add the date and the values of the RSI and SMA
                    df["date"] = pd.to_datetime(df["time"], unit="s")
                    df["rsi"] = ta.rsi(close=df.close, length=10)
                    df["sma10"] = ta.sma(df.close, length=10)
                    print(
                        f"Extended dataframe with RSI ({df['rsi'].iloc[-1]}) and SMA10 ({df['sma10'].iloc[-1]}) for "
                        f"symbol '{data['symbol']}':\r\n{df}\r\n")
        except TypeError as error_msg:
            print("TypeError: " + str(error_msg))
        except KeyError as error_msg:
            if "kline" not in str(error_msg):
                print("KeyError: " + str(error_msg))
示例#20
0
api_keys = {}
with open(secrets_filename, 'r') as f:
    api_keys = json.loads(f.read())

bot = TelegramBot(api_keys['token'], int(api_keys['user_id']))

dataframes = {}

for filename in os.listdir('datasets'):
    symbol = filename.split(".")[0]

    df = pandas.read_csv('datasets/{}'.format(filename))
    if df.empty:
        continue

    df['20sma'] = ta.sma(df['Close'], length=20)
    df['stddev'] = df['Close'].rolling(window=20).std()
    df['lower_band'] = df['20sma'] - (1 * df['stddev'])
    df['upper_band'] = df['20sma'] + (1 * df['stddev'])

    df['TR'] = abs(df['High'] - df['Low'])
    df['ATR'] = df['TR'].rolling(window=20).mean()

    df['lower_keltner'] = df['20sma'] - (df['ATR'] * 1)
    df['upper_keltner'] = df['20sma'] + (df['ATR'] * 1)
    df['diff'] = (df['upper_band'] - df['lower_band']) / df['20sma']

    ADX = ta.adx(df['High'], df['Low'], df['Close'], length=14)
    RSI = ta.rsi(df['Close'], length=14)

    def tight_squeeze(df):
示例#21
0
def get_SMA(data_series_of_target_feature, lookback_value):
    return panda.sma(data_series_of_target_feature, length=lookback_value)
示例#22
0
def sma(l_args, s_ticker, s_interval, df_stock):
    parser = argparse.ArgumentParser(
        prog='sma',
        description=
        """ Moving Averages are used to smooth the data in an array to 
                                     help eliminate noise and identify trends. The Simple Moving Average is literally 
                                     the simplest form of a moving average. Each output value is the average of the 
                                     previous n values. 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. 
                                     This makes it less responsive to recent changes in the data, which can be useful for 
                                     filtering out those changes. """)

    parser.add_argument('-l',
                        "--length",
                        dest="l_length",
                        type=lambda s: [int(item) for item in s.split(',')],
                        default=[20, 50],
                        help='length of MA window')
    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":
            plt.plot(df_stock.index,
                     df_stock['5. adjusted close'].values,
                     color='k')
            l_legend = list()
            l_legend.append(s_ticker)
            for length in ns_parser.l_length:
                df_ta = ta.sma(df_stock['5. adjusted close'],
                               length=length,
                               offset=ns_parser.n_offset).dropna()
                plt.plot(df_ta.index, df_ta.values)
                l_legend.append(f"{length} SMA")
            plt.title(f"SMA on {s_ticker}")
            plt.xlim(df_stock.index[0], df_stock.index[-1])
            plt.xlabel('Time')
            plt.ylabel('Share Price ($)')
            plt.legend(l_legend)
            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.show()

        # Intraday
        else:
            plt.plot(df_stock.index, df_stock['4. close'].values, color='k')
            l_legend = list()
            l_legend.append(s_ticker)
            for length in ns_parser.n_length:
                df_ta = ta.sma(df_stock['4. close'],
                               length=length,
                               offset=ns_parser.n_offset).dropna()
                plt.plot(df_ta.index, df_ta.values)
                l_legend.append(f"{length} SMA")
            plt.title(f"SMA on {s_ticker}")
            plt.xlim(df_stock.index[0], df_stock.index[-1])
            plt.xlabel('Time')
            plt.ylabel('Share Price ($)')
            plt.legend(l_legend)
            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.show()
        print("")

    except:
        print("")
示例#23
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
示例#24
0
import pandas as pd
import pandas_ta as TA
import numpy as np
import matplotlib.pyplot as plt

df = pd.read_csv('btcprice.csv')
rsi = TA.rsi(close=df['market-price'], length=30)
moving_rsi = TA.sma(close=rsi, length=30)

fft = np.fft.fft(moving_rsi)
fftfreq = np.fft.fftfreq(len(moving_rsi), d=len(moving_rsi))

plt.style.use('classic')
fig, ax = plt.subplots(3)

ax[0].plot(df['market-price'])
ax[1].plot(rsi)
ax[1].plot(moving_rsi)
ax[2].plot(fftfreq, fft)

plt.show()
示例#25
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
示例#26
0
def sma(l_args, s_ticker, s_interval, df_stock):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="sma",
        description="""
            Moving Averages are used to smooth the data in an array to
            help eliminate noise and identify trends. The Simple Moving Average is literally
            the simplest form of a moving average. Each output value is the average of the
            previous n values. 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.
            This makes it less responsive to recent changes in the data, which can be useful for
            filtering out those changes.
        """,
    )

    parser.add_argument(
        "-l",
        "--length",
        dest="l_length",
        type=lambda s: [int(item) for item in s.split(",")],
        default=[20, 50],
        help="length of MA window",
    )
    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

        plt.figure()
        if s_interval == "1440min":
            plt.plot(df_stock.index,
                     df_stock["5. adjusted close"].values,
                     color="k")
        else:
            plt.plot(df_stock.index, df_stock["4. close"].values, color="k")
        l_legend = list()
        l_legend.append(s_ticker)
        for length in ns_parser.l_length:
            if s_interval == "1440min":
                df_ta = ta.sma(
                    df_stock["5. adjusted close"],
                    length=length,
                    offset=ns_parser.n_offset,
                ).dropna()
            else:
                df_ta = ta.sma(df_stock["4. close"],
                               length=length,
                               offset=ns_parser.n_offset).dropna()
            plt.plot(df_ta.index, df_ta.values)
            l_legend.append(f"{length} SMA")
        plt.title(f"SMA on {s_ticker}")
        plt.xlim(df_stock.index[0], df_stock.index[-1])
        plt.xlabel("Time")
        plt.ylabel("Share Price ($)")
        plt.legend(l_legend)
        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("")
示例#27
0
from pandas_ta import vwma
from pandas_ta import sma
from pandas_ta import rsi
from pandas_ta import bbands
import torch
from torch import nn
from sklearn.preprocessing import MinMaxScaler


# importing training data sets
from torch.autograd import Variable

data_cleaned = pd.read_csv('data_cleaned.csv')
data_cleaned = data_cleaned.assign(slow_vwma_value=(vwma(data_cleaned.close, data_cleaned.volume, length=2, offset=0)),
                                   fast_vwma_value=(vwma(data_cleaned.close, data_cleaned.volume, length=5, offset=0)),
                                   slow_sma_value=(sma(data_cleaned.close, 15)),
                                   fast_sma_value=(sma(data_cleaned.close, 5)),
                                   rsi_data_value=(rsi(data_cleaned.close, 10)),
                                   )
bbands_train = pd.DataFrame(bbands(data_cleaned.close, length=30, std=1.7))
data_cleaned = pd.concat([data_cleaned, bbands_train], axis=1)
# data_cleaned['timestamp'] = pd.to_datetime(data_cleaned['timestamp'], format='%Y-%m-%d %H')
data_cleaned = data_cleaned.set_index('timestamp')
data_cleaned = data_cleaned.dropna()
# print(data_cleaned)
# print(len(data_cleaned))

# importing test data sets
data_cleaned_test = pd.read_csv("data_cleaned_test.csv")
data_cleaned_test = data_cleaned_test.assign(
    slow_vwma_value=(vwma(data_cleaned_test.close, data_cleaned_test.volume, length=15, offset=0)),
示例#28
0
    for symbol in barsets:
        # print(f"processing symbol {symbol}")

        recent_closes = [[bar.o, bar.h, bar.l, bar.c] for bar in barsets[symbol]]
        _s = pd.DataFrame(recent_closes)
        close_idx = 3
        rsi, sma_20, sma_50 = None, None, None

        for bar in barsets[symbol]:
            good_date = date.today().isoformat() == bar.t.date().isoformat()
            stock_id = stock_dict[symbol]

            if len(_s) > 14 and good_date:
                rsi = ta.rsi(_s[close_idx], lenght=14)
                rsi = rsi.to_numpy()[-1]
                sma_20 = ta.sma(_s[close_idx], length=20)
                sma_20 = sma_20.to_numpy()[-1]

            if len(_s) > 50 and good_date:
                sma_50 = ta.sma(_s[close_idx], length=50)
                sma_50 = sma_50.to_numpy()[-1]

            cursor.execute(
                """
                INSERT INTO stock_price (
                    stock_id, date, open, high, low, close, volume,
                sma_20, sma_50, rsi_14)
                VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
            """,
                (
                    stock_id,
company_name = get_symbol(symbol.upper())

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
示例#30
0
          print(f'{item} removed')
      except KeyError:
          print('The dictionary has no item now...')
          break
# sma  = a.sma # calculate smas
 # insert into smaanalysistable data for 1 symbol, 2 symbol

# Daily
#get today date


#print(dict1)
data=pd.DataFrame.from_dict(dict1)


data['sma10']= ta.sma(data["CLOSE"], length=10,append=True)
#print(data)

data=pd.DataFrame.from_dict(dict1)
data['sma05']=data['CLOSE'].rolling(window=5).mean()
data['sma10']=data['CLOSE'].rolling(window=10).mean()
data['sma15']=data['CLOSE'].rolling(window=15).mean()
data['sma20']=data['CLOSE'].rolling(window=20).mean()
data['sma50']=data['CLOSE'].rolling(window=50).mean()
testdata=(data[['SYMBOL','SERIES','TIMESTAMP','CLOSE','sma05','sma10','sma15','sma15','sma20','sma50']])

rec=testdata.to_dict("records")
 print(rec)
testdata.to_csv("final1121699.csv")
mycol1.insert_many(rec)