def addEvidence(self, symbol = "IBM", \
        sd=dt.datetime(2008,1,1), \
        ed=dt.datetime(2009,1,1), \
        sv = 10000):

        # add your code to do learning here

        # example usage of the old backward compatible util function
        syms = [symbol]
        dates = pd.date_range(sd, ed)
        prices_all = ut.get_data(syms, dates)  # automatically adds SPY
        prices = prices_all[syms]  # only portfolio symbols
        prices_SPY = prices_all['SPY']  # only SPY, for comparison later
        if self.verbose: print prices

        # example use with new colname
        volume_all = ut.get_data(syms, dates,
                                 colname="Volume")  # automatically adds SPY
        volume = volume_all[syms]  # only portfolio symbols
        volume_SPY = volume_all['SPY']  # only SPY, for comparison later
        if self.verbose: print volume

        bb_val, upper, lower, rm, rs = get_bb(prices)
        sma = get_sma(prices)
        mom = get_momentum(prices)
        x_train = np.zeros(shape=(len(prices), 7))

        for i in range(20, len(prices) - self.N):
            x_train[i][0] = bb_val[i]
            x_train[i][1] = upper[i]
            x_train[i][2] = lower[i]
            x_train[i][3] = rm[i]
            x_train[i][4] = rs[i]
            x_train[i][5] = sma[i]
            x_train[i][6] = mom[i]

        x_train = pd.DataFrame(x_train)
        x_train = x_train[:-self.N]
        x_train.fillna(0, inplace=True)
        x_train = x_train.values
        y = []

        for i in range(0, len(prices) - self.N):
            if (prices.ix[i + self.N, symbol] /
                    prices.ix[i, symbol]) > 1.0009 + self.impact:
                y.append(1)
            elif (prices.ix[i + self.N, symbol] /
                  prices.ix[i, symbol]) < 0.9991 - self.impact:
                y.append(-1)
            else:
                y.append(0)

        y_train = np.array(y)

        #print y_train
        self.learner.addEvidence(x_train, y_train)
def testPolicy(symbol, sd, ed, sv):
    symbols = ['JPM']
    dates = pd.date_range(sd, ed)
    benchmark = get_data(symbols, dates, addSPY=False).dropna()
    prices = benchmark['JPM'].values
    trades = pd.DataFrame(data=np.zeros(len(prices)),
                          index=benchmark.index,
                          columns=['JPM'])
    print benchmark
    sma = get_sma(benchmark)
    mom = get_momentum(benchmark)
    bbval, upper, lower, rolling_m, rolling_s = get_bb(benchmark)
    holding = 0
    benchmark = pd.DataFrame({'Date': dt.datetime(2008, 1, 2), 'JPM': [1000]})
    benchmark.set_index("Date", inplace=True)
    for i in range(12, len(prices)):
        if sma[i] < 0.95 and bbval[i] < 0:
            trades['JPM'].iloc[i] = 1000 - holding
            holding = 1000
        elif sma[i] > 1.05 and bbval[i] > 1:
            trades['JPM'].iloc[i] = -holding - 1000
            holding = -1000
    return trades, benchmark
Exemple #3
0
def check_signal(stock):

    sleep(3)

    #set indicators
    ema_co_long = 50
    ema_co_short = 25

    cci_length = 20

    ppo_length_short = 12
    ppo_length_long = 26

    atr_length = 14

    min_ppo_change = 0.2
    min_cci_change = 20

    #get stock data
    stock_data = get_stock_data(stock)

    if (stock_data["open"][0] <= 0) and (stock_data["close"][0] <= 0):
        return

    #get indicator values
    cci = get_cci(stock_data, cci_length)

    ema_short = get_ema(stock_data, ema_co_short)
    ema_long = get_sma(stock_data, ema_co_long)

    ppo = get_ppo(stock_data, ppo_length_short, ppo_length_long)

    atr = get_atr(stock_data, atr_length)

    cci_reversal = False


    #check trend with ema crossover
    if ema_short[0] > ema_long[0]:

        #Kommt CCI aus Short-Trend und ist jetzt neutral/long?
        for i in range(1,3):
            if (cci[0] > -100) and (cci[i] < -100):
                cci_reversal = True
                print("CCI Reversal")
                break

        #wenn CCI im Longtrend oder Reversal aus -100
        if (cci[0] >= 100) or (cci_reversal):

            #Wenn PPO und CCI steigen (mindestens um X) + PPO/CCI-Momentum -> PPO/CCI steigt stärker als am Vortag
            if ((ppo[0]-ppo[1]) >= min_ppo_change) and (ppo[0]-ppo[1] > ppo[1]-ppo[2]) and ((cci[0]-cci[1]) >= min_cci_change) and (cci[0]-cci[1] > cci[1]-cci[2]):

                print("--------------------!!!--------------------")
                print("GO LONG "+stock+" at "+str(stock_data["close"][0]))
                print("Stop Loss 2D Low - 1 ATR: "+str(min(stock_data["low"][0], stock_data["low"][1], stock_data["low"][2])-atr[0]))
                print("Stop Loss 2 ATR: "+str(stock_data["low"][0]-(2*atr[0])))
                print("--------------------!!!--------------------")

            elif ((ppo[0]-ppo[1]) >= min_ppo_change*0.7) and (ppo[0]-ppo[1] > ppo[1]-ppo[2]) and ((cci[0]-cci[1]) >= min_cci_change*0.7) and (cci[0]-cci[1] > cci[1]-cci[2]):
                print("--------------------!!!--------------------")
                print(stock+": about to show LONG signal")
                print("--------------------!!!--------------------")

        else:
            print(stock+": kein Signal")


    elif ema_short[0] < ema_long[0]:

        #Kommt CCI aus Long-Trend und ist jetzt neutral/short?
        for i in range(1,3):
            if (cci[0] < 100) and (cci[i] > 100):
                cci_reversal = True
                print("CCI Reversal")
                break

        #wenn CCI im Shorttrend oder Reversal aus 100
        if (cci[0] <= -100) or (cci_reversal):

            #Wenn PPO und CCI fallen (mindestens um X) + PPO-Momentum -> PPO fällt stärker als am Vortag
            if ((ppo[1]-ppo[0]) >= min_ppo_change) and (ppo[1]-ppo[0] > ppo[2]-ppo[1]) and ((cci[1]-cci[0]) >= min_cci_change) and (cci[1]-cci[0] > cci[2]-cci[1]):

                print("--------------------!!!--------------------")
                print("GO SHORT "+stock+" at "+str(stock_data["close"][0]))
                print("Stop Loss 2D High - 1 ATR: "+str(max(stock_data["high"][0], stock_data["high"][1], stock_data["high"][2])+atr[0]))
                print("Stop Loss 2 ATR: "+str(stock_data["high"][0]+(2*atr[0])))
                print("--------------------!!!--------------------")

            elif ((ppo[1]-ppo[0]) >= min_ppo_change*0.7) and (ppo[1]-ppo[0] > ppo[2]-ppo[1]) and ((cci[1]-cci[0]) >= min_cci_change*0.7) and (cci[1]-cci[0] > cci[2]-cci[1]):
                print("--------------------!!!--------------------")
                print(stock+": about to show SHORT signal")
                print("--------------------!!!--------------------")

        else:
            print(stock+": kein Signal")
Exemple #4
0
def showvalues():
    # Specify the start and end dates for this period.
    start_d = dt.date(2008, 1, 1)
    #end_d = dt.datetime(2018, 10, 30)
    yesterday = dt.date.today() - dt.timedelta(1)

    # Get portfolio values from Yahoo
    symbol = request.form['symbol']
    portf_value = fetchOnlineData(start_d, yesterday, symbol)

    # ****Stock prices chart****
    plot_prices = plot_stock_prices(portf_value.index,
                                    portf_value['Adj Close'], symbol)

    # ****Momentum chart****
    # Normalize the prices Dataframe
    normed = pd.DataFrame()
    normed['Adj Close'] = portf_value['Adj Close'].values / portf_value[
        'Adj Close'].iloc[0]

    # Compute momentum
    sym_mom = get_momentum(normed['Adj Close'], window=10)

    # Create momentum chart
    plot_mom = plot_momentum(portf_value.index, normed['Adj Close'], sym_mom,
                             "Momentum Indicator", (12, 8))

    # ****Bollinger Bands****
    # Compute rolling mean
    rm_JPM = get_rolling_mean(portf_value['Adj Close'], window=10)

    # Compute rolling standard deviation
    rstd_JPM = get_rolling_std(portf_value['Adj Close'], window=10)

    # Compute upper and lower bands
    upper_band, lower_band = get_bollinger_bands(rm_JPM, rstd_JPM)

    # Plot raw symbol values, rolling mean and Bollinger Bands
    dates = pd.date_range(start_d, yesterday)
    plot_boll = plot_bollinger(dates,
                               portf_value.index,
                               portf_value['Adj Close'],
                               symbol,
                               upper_band,
                               lower_band,
                               rm_JPM,
                               num_std=1,
                               title="Bollinger Indicator",
                               fig_size=(12, 6))

    # ****Simple moving average (SMA)****
    # Compute SMA
    sma_JPM, q = get_sma(normed['Adj Close'], window=10)

    # Plot symbol values, SMA and SMA quality
    plot_sma = plot_sma_indicator(dates, portf_value.index,
                                  normed['Adj Close'], symbol, sma_JPM, q,
                                  "Simple Moving Average (SMA)")

    # ****Relative Strength Index (RSI)****
    # Compute RSI
    rsi_value = get_RSI(portf_value['Adj Close'])

    # Plot RSI
    plot_rsi = plot_rsi_indicator(dates,
                                  portf_value.index,
                                  portf_value['Adj Close'],
                                  symbol,
                                  rsi_value,
                                  window=14,
                                  title="RSI Indicator",
                                  fig_size=(12, 6))

    # Session variables
    session['start_val'] = request.form['start_val']
    session['symbol'] = request.form['symbol']
    session['start_d'] = start_d.strftime('%Y/%m/%d')
    session['num_shares'] = request.form['num_shares']
    session['commission'] = request.form['commission']
    session['impact'] = request.form['impact']

    return render_template(
        # name of template
        "stockpriceschart.html",

        # now we pass in our variables into the template
        start_val=request.form['start_val'],
        symbol=request.form['symbol'],
        commission=request.form['commission'],
        impact=request.form['impact'],
        num_shares=request.form['num_shares'],
        start_date=start_d,
        end_date=yesterday,
        tables=[portf_value.to_html(classes=symbol)],
        titles=['na', 'Stock Prices '],
        div_placeholder_stock_prices=Markup(plot_prices),
        div_placeholder_momentum=Markup(plot_mom),
        div_placeholder_bollinger=Markup(plot_boll),
        div_placeholder_sma=Markup(plot_sma),
        div_placeholder_rsi=Markup(plot_rsi))
    def testPolicy(self, symbol = "IBM", \
        sd=dt.datetime(2009,1,1), \
        ed=dt.datetime(2010,1,1), \
        sv = 10000):

        # here we build a fake set of trades
        # your code should return the same sort of data
        dates = pd.date_range(sd, ed)
        prices_all = ut.get_data([symbol], dates)  # automatically adds SPY
        prices = prices_all[[
            symbol,
        ]]  # only portfolio symbols
        trades_SPY = prices_all['SPY']  # only SPY, for comparison later

        bb_val, upper, lower, rm, rs = get_bb(prices)
        sma = get_sma(prices)
        mom = get_momentum(prices)
        x_test = np.zeros(shape=(len(prices), 7))

        for i in range(20, len(prices) - self.N):
            x_test[i][0] = bb_val[i]
            x_test[i][1] = upper[i]
            x_test[i][2] = lower[i]
            x_test[i][3] = rm[i]
            x_test[i][4] = rs[i]
            x_test[i][5] = sma[i]
            x_test[i][6] = mom[i]

        x_test = pd.DataFrame(x_test)
        x_test = x_test[:-self.N]
        x_test = x_test.values
        y_test = self.learner.query(x_test)

        trades = pd.DataFrame(0, columns=prices.columns, index=prices.index)

        flag = 0
        for i in range(0, len(prices) - self.N):
            if y_test[i] == 1:
                if flag == 0:
                    flag = 1000
                    trades[symbol].iloc[i] = 1000
                elif flag == -1000:
                    flag = 1000
                    trades.iloc[i, 0] = 2000
            if y_test[i] == -1:
                if flag == 0:
                    flag = -1000
                    trades[symbol].iloc[i] = -1000
                elif flag == 1000:
                    flag = -1000
                    trades[symbol].iloc[i] = -2000

        # trades.values[:,:] = 0 # set them all to nothing
        # trades.values[0,:] = 1000 # add a BUY at the start
        # trades.values[40,:] = -1000 # add a SELL
        # trades.values[41,:] = 1000 # add a BUY
        # trades.values[60,:] = -2000 # go short from long
        # trades.values[61,:] = 2000 # go long from short
        # trades.values[-1,:] = -1000 #exit on the last day
        # if self.verbose: print type(trades) # it better be a DataFrame!
        # if self.verbose: print trades
        # if self.verbose: print prices_all
        return trades
Exemple #6
0
def check_signal(stock):

    stock_data = {}
    output = []
    sum = 50000

    #get stock data
    stock_data = get_stock_data_wotd(stock)

    if (stock_data[0]["open"] <= 0) and (stock_data[0]["close"] <= 0):
        output.append(stock + ' ZERO VALUES!')
        return output

    sma_length = 50

    cci_length = 100

    hma_1_length = 12
    hma_2_length = 25
    hma_3_length = 100

    atr_1_length = 14
    atr_2_length = 1

    #get indicator values

    sma = get_sma(stock_data, sma_length)

    atr_1 = get_atr(stock_data, atr_1_length)
    atr_2 = get_atr(stock_data, atr_2_length)

    hma_1 = get_hma(stock_data, hma_1_length)
    hma_2 = get_hma(stock_data, hma_2_length)
    hma_3 = get_hma(stock_data, hma_3_length)

    cci = get_cci(stock_data, cci_length)

    # Alle Listen so lange machen, wie die kürzeste, damit von hinten durchiteriert werden kann
    min_length = min(len(hma_3), len(hma_2), len(hma_1), len(sma), len(atr_1),
                     len(atr_2), len(cci))
    sma = sma[:min_length]
    atr_1 = atr_1[:min_length]
    atr_2 = atr_2[:min_length]
    hma_1 = hma_1[:min_length]
    hma_2 = hma_2[:min_length]
    hma_3 = hma_3[:min_length]
    cci = cci[:min_length]

    #stock_data = stock_data[:min_length]
    '''
    print(sma[0])
    print(atr_1[0])
    print(atr_2[0])
    print(hma_1[0])
    print(hma_2[0])
    print(hma_3[0])
    print(cci[0])
    '''

    if ((cci[0] > 100) and ((hma_1[0] - hma_1[1]) > 0)
            and ((hma_2[0] - hma_2[1]) > 0) and ((hma_3[0] - hma_3[1]) > 0)
            and ((sma[0] - sma[1]) > 0) and ((hma_1[0] - hma_1[1]) >
                                             (hma_1[1] - hma_1[2]))):

        output.append("!!!!!!!!!!" + stock + "!!!!!!!!!!")

        vol_avg = 0

        for i in range(14):
            vol_avg += stock_data[i]["volume"]

        vol_avg = vol_avg / 14

        if ((stock_data[0]["volume"] * atr_2[0] > vol_avg * atr_1[0])
                and (stock_data[0]["close"] > stock_data[0]["open"])
                and (stock_data[0]["close"] > stock_data[1]["close"])):

            trade = {"EK": 0, "Anzahl": 0, "SL": 0, "TP": 0}
            trade["EK"] = stock_data[0]["close"]
            trade["Anzahl"] = round((0.005 * sum) / (2.5 * atr_1[0]))
            trade["SL"] = stock_data[0]["close"] - (2.5 * atr_1[0])
            trade["TP"] = stock_data[0]["close"] + (2.5 * atr_1[0])

            output.append("Buy " + str(trade["Anzahl"]) + " Stück für " +
                          str(trade["EK"]))
            output.append("ATR = " + str(atr_1[0]))
            output.append("Stop Loss 2.5 ATR: " + str(trade["SL"]))
            output.append("Take Profit 2.5 ATR: " + str(trade["TP"]))

    if len(output) == 0:
        output.append("----------" + stock + "----------")

    return output