본문 바로가기

Programming/Python for Stock Analysis

볼린저밴드 구현하기 using python | Cal Bollinger bands using Python

파이썬을 이용해서 볼린저밴드 구현하기 Ver. 0.1

def anaylize_bolllinger(df,dir_name,dest_path,date_list):
    df_normalize=df['Close']/df['Close'].ix[0,:]
            
            
    # Compute rolling mean,rolling standard deviation,upper and lower band of Bollinger
    rm=df['Close'].rolling(window=20,center=False).mean()
    rmstd=df['Close'].rolling(window=20,center=False).std()
    upper_band, lower_band = get_bollinger_bands(rm,rmstd)
    dp=df['Close'].rolling(window=1,center=False).mean()
            
    # low_price
    dlp=df['Low'].rolling(window=1,center=False).mean()
            
            
            
    # Plot the graph
    ax=df['Close'].plot(title="Bollinger Bands", label=CompanyNm)
    rm.plot(label='Rolling mean', ax=ax)
    upper_band.plot(label='upper band', ax=ax)
    lower_band.plot(label='lower band',ax=ax)
            
    ax.set_xlabel("Date")
    ax.set_ylabel("Price")
    ax.legend(loc='upper left')
            
    #plt.show()
            
    # Compute the close price of the day which is under the low_band
    for i in range(len(df)):
        cal_rm=rm[str(df.index[i])]
        cal_rmstd=rmstd[str(df.index[i])]
        cal_low_band=cal_rm-cal_rmstd*2
    
        day_low_price=dp[str(df.index[i])]
                
    
        #print("YES FOR LOOP")
        # compare low price to low_band
        if cal_low_band>day_low_price:
                    
                    
        #print("CAL")
        # find normalized value >= 1.05 and satisfied search_days condition.
            for d_list in date_list:
                #print(str(df.index[i], str(d_list)))
                if (str(df.index[i]) == str(d_list)) and df_normalize.ix[-1,-1] >= 1.05 :
                    print("YES, I found BUY signal(s) !!",CompanyNm, df.index[i])
                    subprocess.call(['bash', dir_name + 'Send_Alarm_for_Stock_Signal_Found.sh'\
                                    ,str(df.index[i]),str(CompanyNm)])
                    if not os.path.exists(dest_path):
                        try:
                            os.mkdir(dest_path)
                        except OSError as exc: # Guard against race condition
                            if exc.errno != errno.EEXIST:
                                raise
                                        
                    plt.savefig(dest_path + '/' + str(st[1]) + '-' + str(st[2]) + '-Bollinger.png')
                    with open(dest_path + '/' + timestr +'.csv','a') as csvfile:
                        writer = csv.writer(csvfile, delimiter=',')
                        writer.writerow([str(df.index[i]),str(EventCode),str(CompanyNm)])
                        
    plt.clf()