-3

Here's a simple code for downloading daily stock data and computing Bollinger band indicator, but what I am not able to do is set up a logic for generating a buy and sell signal. Can someone help me with that.

What i want is for the system to check if previous close price is less than Bollinger Band low and last close price should be above the Bollinger Band low. if yes then the system should show it as a buy and vice versa.

PS: I am only using Pandas, numpy, matplotlib and Quandl. Code:

import quandl

download_source = (r'F:\Trading\download.xlsx')

df = quandl.get('NSE/RELIANCE', api_key = '*Quandl Api key*')
sma20 = df['Close'].rolling(window=20, min_periods=20 - 1).mean()
std = df['Close'].rolling(window=20, min_periods=20 - 1).std()

df['bbMid'] = sma20
df['bbUp'] = (sma20 + (std * 2))
df['bblower'] = (sma20 - (std * 2))


df.to_excel(download_source)
eyllanesc
  • 235,170
  • 19
  • 170
  • 241

1 Answers1

0
    previous_close = df['Close'].shift(1).values
    last_close = df['Close'].values

    bband_low = df['bblower'].values
    bband_up = df['bbUp'].values

    cond_buy1 = previous_close < bband_low
    cond_buy2 = last_close > bband_low
    df['BUY'] = np.where((cond_buy1 & cond_buy2), True, False)

    cond_sell1 = previous_close > bband_up
    cond_sell2 = last_close < bband_up
    df['SELL'] = np.where((cond_sell1 & cond_sell2), True, False)

I think this is what you are looking for.

Put these few lines of codes in your script before "df.to_excel(download_source)" and it should work.

  • Thank you. That worked exactly as I wanted. So all I had to do was define variable for each value and then give the condition. I was doing it directly without variables. I still have lots to learn in Python. Thank you once again. – Mahesh Sapaliga Dec 23 '17 at 15:22