Python trading logic

妖精的绣舞 提交于 2019-12-13 09:46:48

问题


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)

回答1:


    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.



来源:https://stackoverflow.com/questions/47952696/python-trading-logic

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!