def main():
	print 'Argument List:', str(sys.argv)
	
	startdaysplit = sys.argv[1].split(',')
	enddaysplit = sys.argv[2].split(',')
	spxversion = sys.argv[3]
	nameofchartfile = sys.argv[4]
	lookbackPeriod = int(sys.argv[5])
	market = 'SPY'
	
	dt_start = dt.datetime(int(startdaysplit[0]),int(startdaysplit[1]), int(startdaysplit[2]), 16, 00, 00)
	dt_end = dt.datetime(int(enddaysplit[0]),int(enddaysplit[1]), int(enddaysplit[2]), 16, 00, 00)
	
	# Fetching the NYSE data
	closingPrices, ldt_timestamps, ls_symbols, d_data = fetchNYSEDataForEvents(dt_start, dt_end, spxversion, market)
	
	# Converting the two outputs from NYSEDataFetch into one dataframe
	df_closingprices = pd.DataFrame(closingPrices, columns = ls_symbols, index = ldt_timestamps)
	
	# Sending the df_closingprices and lookback period to get the bollinger band values, simple moving average of the equities and rolling stddev of the equities
	df_bollinger_vals, df_movingavg, df_movingstddev = bo.bollinger(df_closingprices, lookbackPeriod)
	
	# Finding the events
	df_events = find_bollinger_events(df_bollinger_vals)
	
	#print "Creating Study"
	ep.eventprofiler(df_events, d_data, i_lookback=20, i_lookforward=20, s_filename=nameofchartfile, b_market_neutral=True, b_errorbars=True,s_market_sym='SPY')
Esempio n. 2
0
    def GetData(self, event):

        try:
            self.timabil = int(self.period.GetValue())
        except:
            self.period.SetValue("200")
        try:
            self.delta = int(self.avg.GetValue())
        except:
            self.avg.SetValue("20")

        if self.currentsymbol == "":
            self.SelectTicker()
        else:

            # **** to remove title text in matplotlib graph ****
            self.fig.clear()
            self.axes = self.fig.add_subplot(self.gs[0], axisbg="black")
            self.axes1 = self.fig.add_subplot(self.gs[1], axisbg="black")

            # Name of company
            self.companyname = self.biglist[self.currentvalue + 1][1].split("-")[0]
            self.fig.suptitle(self.companyname, fontsize=20)

            self.sizer_for_rightpanel = wx.BoxSizer(wx.VERTICAL)
            self.sizer_for_rightpanel.Add(self.canvas, 1, wx.GROW)
            self.rightpanel.SetSizer(self.sizer_for_rightpanel)
            self.mgr.Update()
            # **** to remove title text in matplotlib graph ****

            now = date.today()
            dagsetn_nuna = now.strftime("%Y%m%d")

            # dagsetning fyrir 'timabil' dogum
            then = date.today() - timedelta(
                self.delta + self.timabil + 1
            )  # +1 thvi fyrsti dalkur i datalist er heiti dalka
            then2 = date.today() - timedelta(self.timabil + 1)
            dagsetn_tha = then.strftime("%Y%m%d")
            try:
                datalist = ystockquote.get_historical_prices(self.currentsymbol, dagsetn_tha, dagsetn_nuna)
            except:
                self.NoInternetConnection()
                return

            dates = []
            viewdata = []

            # datalist: list of values for open days in the selected period of days + delta days
            # back in time (to calculate moving average for the first day)
            for i in range(1, len(datalist)):
                date1 = datetime.strptime(datalist[i][0], "%Y-%m-%d")
                self.place = i
                if date1.date() <= then2:
                    viewdata = datalist[1 : i + 1]
                    # +1 because the list is backwards.
                    # (value for today is first in the list)
                    break

            for i in range(len(viewdata)):
                date2 = datetime.strptime(viewdata[i][0], "%Y-%m-%d")
                dates.append(date2)

            dates.reverse()
            dates = matplotlib.dates.date2num(dates)

            volume = []
            price = []
            openprice = []
            closeprice = []

            for x in datalist[1:]:
                openprice.append(float(x[1]))
                closeprice.append(float(x[4]))
                price.append(float(x[6]))
                volume.append(float(x[5]))

            color = []
            for i in range(len(openprice)):
                if openprice[i] < closeprice[i]:
                    color.append("r")
                elif openprice[i] > closeprice[i]:
                    color.append("g")
                else:
                    color.append("grey")
            (pricemean, pricestd) = movAVG.AVG(price, self.place, self.delta)

            (priceupperb, pricelowerb, lastUpInner, lastLoInner) = bollinger.bollinger(pricemean, pricestd, self.delta)

            # Take the last values for the bollinger bands, moving average and the current price
            # To find out whether there's a bollinger squeeze or you can

            # BuyOrSellCheck
            bos = buyorsell.BuyOrSell(self.currentprice, openprice[0], lastUpInner, lastLoInner)

            if bos == "NEUTRAL":
                self.buytxt.SetLabel("Stocks for \n" + self.companyname)
                self.buyorsell.SetValue("are in a NEUTRAL zone")
            elif bos == "BUY":
                self.buytxt.SetLabel("Stocks for \n" + self.companyname)
                self.buyorsell.SetValue("are in the BUY zone")
            elif bos == "SELL":
                self.buytxt.SetLabel("Stocks for \n" + self.companyname)
                self.buyorsell.SetValue("are in the SELL zone")

            volume.reverse()
            price.reverse()
            pricemean.reverse()

            priceupperb.reverse()
            pricelowerb.reverse()

            self.axes.clear()

            self.axes1.clear()

            # self.axes.xaxis.set_major_locator(MultipleLocator((int)(len(price[volume])/10))
            self.axes.plot_date(
                dates, price[: self.place], color="yellow", linewidth="1", linestyle="-", marker="None", ydate=False
            )
            self.axes.plot_date(dates, pricemean[: self.place], color="red", linestyle="-", marker="None", ydate=False)
            self.axes.plot_date(dates, priceupperb, color="green", linestyle="-", marker="None", ydate=False)
            self.axes.plot_date(dates, pricelowerb, color="green", linestyle="-", marker="None", ydate=False)

            plt.setp(self.axes.xaxis.get_majorticklabels(), visible=False)
            self.axes.set_ylabel("Price (per share)")
            self.axes.yaxis.grid(color="gray", linestyle="dashed")
            self.axes.xaxis.grid(color="gray", linestyle="dashed")

            # self.axes1.xaxis.set_major_locator(MultipleLocator(int(len(volume)/10))
            plt.setp(self.axes1.xaxis.get_majorticklabels(), horizontalalignment="right", rotation=25)
            plt.setp(self.axes1.yaxis.get_majorticklabels(), fontsize=9)
            self.axes1.xaxis_date()

            # self.axes1.xaxis.set_major_formatter( DateFormatter('%d:%m:%Y'))
            # when the bars will mash together if they're shown for a bigger period than 150
            if self.timabil < 151:
                self.axes1.bar(dates, volume[: self.place], color=color, align="center")
            # shows a line graph instead of a bar chart if over 150 day timeperiod is selected
            else:
                self.axes1.plot_date(
                    dates, volume[: self.place], ydate=False, marker="", color="yellow", linestyle="-", linewidth=0.5
                )
            self.axes1.set_ylabel("Volume")
            self.axes1.yaxis.grid(color="gray", linestyle="dashed", alpha=0.5)
            self.axes1.xaxis.grid(color="gray", linestyle="dashed", alpha=0.5)

            self.axes.fill_between(dates, priceupperb, pricelowerb, facecolor="green", alpha=0.3)

            DateLoc = AutoDateLocator(maxticks=12)

            self.axes.xaxis.set_major_locator(DateLoc)
            self.axes1.xaxis.set_major_locator(DateLoc)
            self.axes1.xaxis.set_major_formatter(DateFormatter("%d %b %Y"))
            self.fig.autofmt_xdate()
            # if ( DateFormatter.scale == 365.0 ):
            #     self._formatter = DateFormatter("%Y", self._tz)
            # elif ( scale == 30.0 ):
            #     self._formatter = DateFormatter("%b %Y", self._tz)
            # elif ( (scale == 1.0) or (scale == 7.0) ):
            #     self._formatter = DateFormatter("%b %d \n %Y", self._tz)

            self.canvas.draw()
Esempio n. 3
0
import datetime
import itertools
from collections import Counter

import bollinger as B

stock = B.bollinger()

begins = Counter()
ends = Counter()
ends
for transaction in stock.transactions:
    # begins[transaction.signal_begin.index] += 1
    ends[transaction.signal_end.index] += 1
    print(
        f"begin = {transaction.signal_begin.date}\nend = {transaction.signal_end.date}"
    )