예제 #1
0
def strat():
    CustomStrategy = ta.Strategy(
        name="Momo and Volatility",
        description="SMA 50,200, BBANDS, RSI, MACD and Volume SMA 20",
        ta=[
            {
                "kind": "sma",
                "length": 11
            },
            {
                "kind": "sma",
                "length": 20
            },
            {
                "kind": "bbands",
                "length": 20
            },
            {
                "kind": "rsi"
            },
            {
                "kind": "macd",
                "fast": 8,
                "slow": 21
            },
            {
                "kind": "sma",
                "close": "volume",
                "length": 20,
                "prefix": "VOLUME"
            },
        ])
    # To run your "Custom Strategy"
    my_data.ta.strategy(CustomStrategy)
    print(my_data)
    def calculate_all_technicals_with_pandas_ta(
        technicals: pd.DataFrame, ) -> pd.DataFrame:
        default_strategy = ta.Strategy(
            name="Default",
            description=
            "PVOL, SMA15, SMA40, EMA200, RSI, MACD, Trix, Williams %R, MFI, ROC, EMV",
            ta=[
                {
                    "kind": "pvol"
                },
                {
                    "kind": "sma",
                    "length": 15
                },
                {
                    "kind": "sma",
                    "length": 40
                },
                {
                    "kind": "ema",
                    "length": 200
                },
                {
                    "kind": "rsi",
                    "length": 14
                },
                {
                    "kind": "macd",
                    "fast": 12,
                    "slow": 26,
                    "signal": 9
                },
                {
                    "kind": "trix",
                    "length": 14,
                    "signal": 9
                },
                {
                    "kind": "willr",
                    "length": 10
                },
                {
                    "kind": "mfi",
                    "length": 14
                },
                {
                    "kind": "roc",
                    "length": 14
                },
                {
                    "kind": "eom",
                    "length": 14
                },
            ],
        )

        technicals.ta.strategy(default_strategy)
        return technicals
 def test_get_technical_indicator(self, dictList_stock):
     data = dictList_stock
     df = pd.DataFrame(data)
     stock = Stock(data, 'Date')
     strategy = ta.Strategy(name='sma', ta=[{'kind': 'sma', 'length': 2}])
     df.ta.strategy(strategy)
     stock = stock.get_technical_indicator(strategy)
     test = to_pandas(stock, False, False, 'ignore')
     test.columns = test.columns.str.lower()
     df.columns = df.columns.str.lower()
     pd.testing.assert_frame_equal(df, test, False)
예제 #4
0
def customEntryStrategy(bot_controller, symbol):
    ## This is the function that pyjuque will call to check for entry signal
    ## the first parammeter is a bot_controller, through which we have access
    ## to the following objects:
    ##
    ## bot_controller.bot_model (a SQLAlchemy model, containing the info that
    #       we store in the database for this bot plus a few methods)
    ## bot_controller.session (a SQLAlchemy database session)
    ## bot_controller.exchange (a CcxtExchanges, exposing a few wrapped methods
    ##      written to work with pyjuque plus all the ccxt unified api methods,
    ##      through bot_controller.exchange.ccxt)
    ## bot_controller.strategy (in our case it will be None)
    ## bot_controller.status_printer (yaspin object)
    ##
    ## and the following method:
    ## bot_controller.executeBot() (executes a loop of the bot - checking
    ##      entry signals on all symbols, placing orders if any signals are
    ##      found, then checking all the open orders and updating them)
    ##
    ## it returns a boolean (the signal) and the current price of the asset

    # Get data from exchange for multiple timeframes
    df_15min = bot_controller.exchange.getOHLCV(symbol, '15m', limit=100)
    df_1hour = bot_controller.exchange.getOHLCV(symbol, '1h', limit=100)
    df_4hour = bot_controller.exchange.getOHLCV(symbol, '4h', limit=100)

    # Define and compute indicators for each timeframe
    Strat = ta.Strategy(name="EMAs",
                        ta=[
                            {
                                "kind": "ema",
                                "length": 20
                            },
                            {
                                "kind": "ema",
                                "length": 50
                            },
                        ])
    df_15min.ta.strategy(Strat)
    df_1hour.ta.strategy(Strat)
    df_4hour.ta.strategy(Strat)

    # Check entry signal on each timeframe separately
    entry_signal_15 = df_15min.iloc[-1]['EMA_50'] > df_15min.iloc[-1]['EMA_20']
    entry_signal_1h = df_1hour.iloc[-1]['EMA_50'] > df_1hour.iloc[-1]['EMA_20']
    entry_signal_4h = df_4hour.iloc[-1]['EMA_50'] > df_1hour.iloc[-1]['EMA_20'] and \
        df_4hour.iloc[-2]['EMA_50'] < df_1hour.iloc[-2]['EMA_20']

    # Combine them
    entry_signal = entry_signal_15 and entry_signal_1h and entry_signal_4h

    # Return the signal and the last price
    return entry_signal, df_4hour.iloc[-1]['close']
 def test_single_stock_technical_indicator(self, single_stock):
     strategy = ta.Strategy(name='sma', ta=[{'kind': 'sma', 'length': 2}])
     df = pd.DataFrame(single_stock['train'])
     sit = Stock_Technical_Indicator_Transformer(strategy, 'Date')
     sit.fit(df)
     y = sit.transform(df)
     df.ta.strategy(strategy)
     np.testing.assert_equal(y.reshape(-1), df['SMA_2'].values)
     df = pd.DataFrame(single_stock['train'])
     df = df.append(pd.DataFrame(single_stock['test']), True)
     df2 = pd.DataFrame(single_stock['test'])
     y = sit.transform(df2)
     df.ta.strategy(strategy)
     np.testing.assert_equal(y.reshape(-1), df.tail(3)['SMA_2'].values)
 def test_single_make_technical_indicator(self, dictList_stock):
     MyStrategy = ta.Strategy(name="DCSMA10",
                              ta=[{
                                  "kind": "sma",
                                  "length": 1
                              }])
     df = pd.DataFrame(dictList_stock)
     stockTrans = Stock_Transformer.from_pandas(df, 'Date', None)
     stockTrans = stockTrans.get_technial_indicator(MyStrategy)
     df.ta.strategy(MyStrategy)
     test = stockTrans.to_pandas(False, False, 'ignore')
     test.columns = test.columns.str.lower()
     df.columns = df.columns.str.lower()
     df = df[test.columns]
     pd.testing.assert_frame_equal(test, df, False)
 def test_get_technical_indicator(self, dictList_portfolio):
     data = dictList_portfolio
     df = pd.DataFrame(data)
     tsd = Time_Series_Data(data, 'Date')
     tsc = Time_Series_Data_Collection(tsd, 'Date', 'symbol')
     port = Portfolio.from_time_series_collection(tsc)
     strategy = ta.Strategy(name='sma', ta=[{'kind': 'sma', 'length': 2}])
     port = port.get_technical_indicator(strategy)
     test = to_pandas(port, False, False, 'ignore')
     test.columns = test.columns.str.lower()
     for i in port:
         tmp = df[df.symbol == i]
         tmp.ta.strategy(strategy)
         tmp.columns = tmp.columns.str.lower()
         tmp_test = test[test.symbol == i]
         tmp_test = tmp_test[tmp.columns]
         pd.testing.assert_frame_equal(tmp_test.reset_index(drop=True),
                                       tmp.reset_index(drop=True), False)
 def test_collection_make_technical_indicator(self, dictList_portfolio):
     MyStrategy = ta.Strategy(name="DCSMA10",
                              ta=[{
                                  "kind": "sma",
                                  "length": 1
                              }])
     df = pd.DataFrame(dictList_portfolio)
     stockTrans = Stock_Transformer.from_pandas(df, 'Date', None)
     stockTrans = stockTrans.get_technial_indicator(MyStrategy)
     test = stockTrans.to_pandas(False, False, 'ignore')
     test.columns = test.columns.str.lower()
     for i in test.symbol.unique():
         tmp_df = df[df.symbol == i]
         tmp_test = test[test.symbol == i]
         tmp_df.ta.strategy(MyStrategy)
         tmp_df.columns = tmp_df.columns.str.lower()
         tmp_df = tmp_df[tmp_test.columns]
         pd.testing.assert_frame_equal(tmp_test, tmp_df, False)
예제 #9
0
def custom_MACD(symbol, date):
    time_delta = 100
    trade = OpenClose.objects.filter(symbol=symbol, date__gte=date-timedelta(days=time_delta), date__lte=date).order_by('date')
    value = [[t.date,  t.open, t.high, t.low, t.close, t.volume] for t in trade]
    columns_name = ["date", "open", "high", "low", "close", "volume"]
    trade = pd.DataFrame(value, columns=columns_name).set_index("date")

    CustomMACDStrategy = ta.Strategy(
        name="EMAs, BBs, and MACD",
        description="Non Multiprocessing Strategy by rename Columns",
        ta=[
            {"kind": "macd", "fast": 8, "slow": 21},
            {"kind": "macd", "fast": 12, "slow": 26},
            {"kind": "macd", "fast": 14, "slow": 28},
        ]
    )
    trade.ta.strategy(CustomMACDStrategy)
    print(trade)
 def test_collection_stock_technical_indicator(self, collection_stock):
     strategy = ta.Strategy(name='sma', ta=[{'kind': 'sma', 'length': 2}])
     df = pd.DataFrame(collection_stock['train'])
     sit = Stock_Technical_Indicator_Transformer(strategy, 'Date', 'symbol')
     sit.fit(df)
     y = sit.transform(df)
     res = []
     for i in df.symbol.unique():
         tmp = df[df.symbol == i]
         tmp.ta.strategy(strategy)
         res.extend(tmp['SMA_2'])
     np.testing.assert_equal(y.reshape(-1), np.array(res))
     df = pd.DataFrame(collection_stock['test'])
     y = sit.transform(df)
     df = pd.DataFrame(collection_stock['train'])
     df = df.append(pd.DataFrame(collection_stock['test']), True)
     res = []
     for i in df.symbol.unique():
         tmp = df[df.symbol == i]
         tmp.ta.strategy(strategy)
         res.extend(tmp['SMA_2'].tail(2).tolist())
     np.testing.assert_equal(y.reshape(-1), np.array(res))
예제 #11
0
    def test_strategy(self, symbol, path):
        if not self.watchlist_contains(symbol):
            print("The selected symbol is not in the watchlist!")
            return

        acc = PaperAccount()
        acc.init_session(10000, False)
        csv_path = os.path.join(path, "{0}.csv".format(symbol))
        df = pd.read_csv(csv_path, sep=",")

        RSIStrategy = ta.Strategy(
            name="RSI",
            description="RSI to measure stock price strength",
            ta=[
                {"kind": "rsi"}
            ]
        )

        shares = 0
        df.ta.strategy(RSIStrategy)

        # Predefined ruleset: buy if RSI_14 less than 35, hold and sell until RSI_14 over 55
        for index, row in df.iterrows():
            if row['RSI_14'] < 35:
                shares = acc.buy_stock(symbol, row['close'], 10)
            if row['RSI_14'] > 50:
                shares = acc.sell_stock(symbol, row['close'], ALL_SHARES_AVAILABLE)

        # Analysis
        result = acc.get_profit_loss()
        if result < 0:
            print("Realized loss:" + str(result))
        else:
            print("Realized gain: " + str(result))

        buys, sells = acc.get_total_transactions()
        print("Total # buys: " + str(buys))
        print("Total # sells: " + str(sells))
예제 #12
0
import pandas_ta as ta

strategy_test = ta.Strategy(
    name=
    "Crossing Moving Average - https://www.investopedia.com/ask/answers/122314/how-do-i-use-moving-average-ma-create-forex-trading-strategy.asp",
    description="SMA 50,200, BBANDS, RSI, MACD and Volume SMA 20",
    ta=[
        {
            "kind": "ema",
            "length": 5
        },
        {
            "kind": "ema",
            "length": 20
        },
        {
            "kind": "ema",
            "length": 50
        },
    ])
예제 #13
0
파일: NN.py 프로젝트: stefanZorcic/Stock_NN
def neural_network(ticker, start, end, column, split):
    global lr
    df = data_get(ticker, start, end)

    CustomStrategy = ta.Strategy(
        name="Momo and Volatility",
        description="SMA 50,200, BBANDS, RSI, MACD and Volume SMA 20",
        ta=[
            #{"kind": "sma", "length": 50},
            #{"kind": "sma", "length": 200},
            #{"kind": "bbands", "length": 20},
            {
                "kind": "rsi"
            },
            {
                "kind": "stoch"
            },
            {
                "kind": "bbands"
            },
            {
                "kind": "ema"
            },
            {
                "kind": "ao"
            },
            {
                "kind": "apo"
            },
            {
                "kind": "brar"
            },
            {
                "kind": "cci"
            },
            {
                "kind": "ha"
            },
            {
                "kind": "aberration"
            },
            {
                "kind": "accbands"
            },
            {
                "kind": "adx"
            },
            {
                "kind": "bias"
            },
            {
                "kind": "cmf"
            },
            {
                "kind": "midprice"
            },
            {
                "kind": "pvol"
            },
            #{"kind": "macd", "fast": 8, "slow": 21},
            #{"kind": "sma", "close": "volume", "length": 20, "prefix": "VOLUME"},
        ])

    df.ta.strategy(CustomStrategy)  #error here
    #print(df)
    df = df.dropna()
    #print(df)

    #print("__________________________________")

    #print(df)

    X, y, X_test, y_test = data_process(df, column, split)

    lr.fit(np.array(X), np.array(y))

    a = lr.predict(np.array(X_test))
    b = np.array(y_test)

    t = 0

    # Accuracy Calculator
    for z in range(len(a)):
        w = a[z]
        v = b[z]

        if z != 0:
            u = b[z - 1]
            if (w[0] < u[0] and v[0] < u[0]) or (w[0] > u[0] and v[0] > u[0]):
                t += 1

    # Output Accuracy

    print(lr.score(np.array(X_test), np.array(y_test)))
    print("High Direction Accuracy: " + str(t / len(a) * 100) + "%")
    #print(df)
    return df, X, y, X_test, y_test
예제 #14
0
def stock_linear_trending_api(symbol, date):
    time_delta = 50
    tickers = OpenClose.objects.filter(symbol=symbol,
                                       date__gte=date -
                                       timedelta(days=time_delta),
                                       date__lte=date).order_by('-date')
    close = pd.DataFrame([[t.date, t.close, t.volume] for t in tickers],
                         columns=["date", "close", "volume"]).set_index("date")
    last_20 = close['close'][:20]

    _1 = np.quantile(last_20, q=0.25)
    _2 = np.quantile(last_20, q=0.5)
    _3 = np.quantile(last_20, q=0.75)

    if close['close'][0] > _3:
        q_l = 4
    elif _2 <= close['close'][0] < _3:
        q_l = 3
    elif _1 <= close['close'][0] < _2:
        q_l = 2
    else:
        q_l = 1

    if 5 < len(tickers) < 10:
        CustomSMAStrategy = ta.Strategy(
            name="EMAs, BBs, and MACD",
            description="Non Multiprocessing Strategy by rename Columns",
            ta=[
                {
                    "kind": "sma",
                    "length": 5
                },
            ])
        close.ta.strategy(CustomSMAStrategy)

        trend = TrendingRecord(
            date=date,
            symbol=symbol,
            close=tickers[0].close,
            sma_5d=close['SMA_5'][-1],
            quantile20=q_l,
            cross_sma5=tickers[0].close - close['SMA_5'][-1],
        )

        trend.save()

    if 10 <= len(tickers) < 20:
        CustomSMAStrategy = ta.Strategy(
            name="EMAs, BBs, and MACD",
            description="Non Multiprocessing Strategy by rename Columns",
            ta=[
                {
                    "kind": "sma",
                    "length": 5
                },
                {
                    "kind": "sma",
                    "length": 10
                },
            ])
        close.ta.strategy(CustomSMAStrategy)

        trend = TrendingRecord(
            date=date,
            symbol=symbol,
            close=tickers[0].close,
            sma_5d=close['SMA_5'][-1],
            sma_10d=close['SMA_10'][-1],
            quantile20=q_l,
            cross_sma5=tickers[0].close - close['SMA_5'][-1],
            cross_sma10=tickers[0].close - close['SMA_10'][-1],
        )

        trend.save()

    if 20 <= len(tickers) < 30:
        CustomSMAStrategy = ta.Strategy(
            name="EMAs, BBs, and MACD",
            description="Non Multiprocessing Strategy by rename Columns",
            ta=[
                {
                    "kind": "sma",
                    "length": 5
                },
                {
                    "kind": "sma",
                    "length": 10
                },
                {
                    "kind": "sma",
                    "length": 20
                },
            ])
        close.ta.strategy(CustomSMAStrategy)

        X = np.array([i for i in range(len(tickers[:20]))]).reshape((-1, 1))
        y = np.array([t.close for t in tickers[:20]])
        model = LinearRegression()
        reg = model.fit(X=X, y=y)
        slope = reg.coef_
        angle = np.rad2deg(np.arctan2(y[-1] - y[0], X[-1] - X[0]))

        trend = TrendingRecord(
            date=date,
            symbol=symbol,
            close=tickers[0].close,
            sma_5d=close['SMA_5'][-1],
            sma_10d=close['SMA_10'][-1],
            sma_20d=close['SMA_20'][-1],
            quantile20=q_l,
            cross_sma5=tickers[0].close - close['SMA_5'][-1],
            cross_sma10=tickers[0].close - close['SMA_10'][-1],
            cross_sma20=tickers[0].close - close['SMA_20'][-1],
            angle=angle,
            slope=slope)

        trend.save()

    if 30 <= len(tickers):
        CustomSMAStrategy = ta.Strategy(
            name="EMAs, BBs, and MACD",
            description="Non Multiprocessing Strategy by rename Columns",
            ta=[
                {
                    "kind": "sma",
                    "length": 5
                },
                {
                    "kind": "sma",
                    "length": 10
                },
                {
                    "kind": "sma",
                    "length": 20
                },
                {
                    "kind": "sma",
                    "length": 30
                },
            ])

        close.ta.strategy(CustomSMAStrategy)
        X = np.array([i for i in range(len(tickers[:20]))]).reshape((-1, 1))
        y = np.array([t.close for t in tickers[:20]])
        model = LinearRegression()
        reg = model.fit(X=X, y=y)
        slope = reg.coef_
        angle = np.rad2deg(np.arctan2(y[-1] - y[0], X[-1] - X[0]))

        trend = TrendingRecord(
            date=date,
            symbol=symbol,
            close=tickers[0].close,
            sma_5d=close['SMA_5'][-1],
            sma_10d=close['SMA_10'][-1],
            sma_20d=close['SMA_20'][-1],
            sma_30d=close['SMA_30'][-1],
            quantile20=q_l,
            cross_sma5=tickers[0].close - close['SMA_5'][-1],
            cross_sma10=tickers[0].close - close['SMA_10'][-1],
            cross_sma20=tickers[0].close - close['SMA_20'][-1],
            cross_sma30=tickers[0].close - close['SMA_30'][-1],
            angle=angle,
            slope=slope)

        trend.save()