Beispiel #1
0
def showCandles(stock, days):
    quotes = []
    prices = stock.prices[len(stock.prices)-days:]
    for day in prices:
        date = map(int,tuple(day['date'].split('-')))
        date = date2num(datetime.date(*date))
        quotes.append((date, float(day['open']), float(day['close']),float(day['high']),float(day['low'])))

    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays    = DayLocator()              # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # Eg, Jan 12
    dayFormatter = DateFormatter('%d')      # Eg, 12
    
    fig = figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)
    
    candlestick(ax, quotes, width=0.6)

    ax.xaxis_date()
    ax.autoscale_view()
    setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    show()
Beispiel #2
0
    def generateGraph(self, quotes):
        self.clearGraphData()

        #print "DEBUG:"
        #print "\tquotes = %s" % quotes

        #for i in range(len(highs)):
        #    print "DEBUG: (%s, %s, %s, %s)" %(lows[i], opens[i], closes[i], highs[i])
        #    print "DEBUG: diffs h/l: %s o/c: %s" %(lows[i] - highs[i], opens[i] - closes[i])

        self.ax = self.fig.add_subplot(111)

        self.ax.set_title(_("Session candlestick graph"))

        #Set axis labels and grid overlay properites
        self.ax.set_xlabel(_("Sessions"), fontsize=12)
        self.ax.set_ylabel("$", fontsize=12)
        self.ax.grid(color='g', linestyle=':', linewidth=0.2)

        candlestick(self.ax,
                    quotes,
                    width=0.50,
                    colordown='r',
                    colorup='g',
                    alpha=1.00)
        self.graphBox.add(self.canvas)
        self.canvas.show()
        self.canvas.draw()
Beispiel #3
0
def printKline(stock):
    re = getFullQuoteByStock(stock)
    re = re.set_index('date')
    #re.index = pd.to_datetime(re.index)
    data_list = []
    re = re.drop('index', 1)
    for dates, row in re.iterrows():
        date_time = datetime.datetime.strptime(dates, '%Y-%m-%d')
        t = date2num(date_time)
        open, high, low, close = row[:4]
        datas = (t, open, high, low, close)
        data_list.append(datas)

    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis_date()
    plt.xticks(rotation=45)
    plt.yticks()
    plt.title("STOCK:" + stock)
    plt.xlabel("time")
    plt.ylabel("price")
    mpf.candlestick(ax, data_list, width=1.5, colorup='r', colordown='green')
    plt.grid()
    plt.show()
    plt.savefig('/Users/momo/Programs/python/result/' + stock + '.png')
Beispiel #4
0
 def candlePlot(self,ax,quotes, width=0.6,colorup='r', colordown='g',alpha=0.5): 
     if sys.version > '3':
         PY3 = True
     else:
         PY3 = False   
         
     if (PY3 == True):        
         mpf.candlestick_ohlc(ax, quotes, width,colorup, colordown,alpha)
     else:        
         #opens, closes, highs, lows,
         time  = quotes[:,0]
         opens = quotes[:,1]
         closes= quotes[:,4]
         highs = quotes[:,2]
         lows  = quotes[:,3]    
         quotesNew = np.vstack((time,opens,closes,highs,lows))
         mpf.candlestick(ax, quotesNew.T, width,colorup, colordown,alpha)
     ax.xaxis_date()
     ax.autoscale_view()
     #self.addText(ax,quotes[:,0],quotes[:,4])
     for label in ax.xaxis.get_ticklabels():
         label.set_color("red")
         label.set_rotation(30)
         label.set_fontsize(12)   
     ax.grid(True)        
    def __init__(self, ticker):
        gtk.VBox.__init__(self)

        startdate = datetime.date(2001, 1, 1)
        today = enddate = datetime.date.today()

        date1 = datetime.date(2011, 1, 1)
        date2 = datetime.date.today()

        mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
        alldays = DayLocator()  # minor ticks on the days
        weekFormatter = DateFormatter("%b %d")  # Eg, Jan 12
        dayFormatter = DateFormatter("%d")  # Eg, 12

        quotes = quotes_historical_yahoo(ticker, date1, date2)
        if len(quotes) == 0:
            raise SystemExit

        fig = Figure(facecolor="white", figsize=(5, 4), dpi=100)
        fig.subplots_adjust(bottom=0.2)
        ax = fig.add_subplot(111)
        ax.xaxis.set_major_locator(mondays)
        ax.xaxis.set_minor_locator(alldays)
        ax.xaxis.set_major_formatter(weekFormatter)
        candlestick(ax, quotes, width=0.6)

        ax.xaxis_date()
        ax.autoscale_view()
        pylab.setp(pylab.gca().get_xticklabels(), rotation=45, horizontalalignment="right")

        canvas = FigureCanvas(fig)  # a gtk.DrawingArea
        self.pack_start(canvas)
        toolbar = NavigationToolbar(canvas, win)
        self.pack_start(toolbar, False, False)
def candlestickExample():
    # (Year, month, day) tuples suffice as args for quotes_historical_yahoo
    date1 = ( 2004, 2, 1)
    date2 = ( 2004, 4, 12 )
    
    
    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays    = DayLocator()              # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
    dayFormatter = DateFormatter('%d')      # e.g., 12
    
    quotes = quotes_historical_yahoo('INTC', date1, date2)
    if len(quotes) == 0:
        raise SystemExit
    
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)
    
    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick(ax, quotes, width=0.6)
    
    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    
    print quotes
    plt.show()
Beispiel #7
0
def QueryAndShowData(ins, beginTime, num):
	dics = GetMarketData(ins, beginTime, num)
	datas = []
	i = 1
	for item in dics:
		data = []
		data.append(i)
		i = i + 1
		data.append(item['openPrice'])
		data.append(item['closePrice'])
		data.append(item['highPrice'])
		data.append(item['lowPrice'])
		datas.append(data)

	fig = plt.figure(figsize = (18, 9))
	ax = fig.add_subplot(211)
	candlestick(ax, datas, width = 0.4, colorup = 'r', colordown = 'g')
	ax.autoscale_view()

	volumeX = fig.add_subplot(212)
	datas = []
	index = []
	i = 1
	for item in dics:
		index.append(i)
		i = i + 1
		datas.append(item['volume'])
	volumeX.set_xlim(0, num)
	plt.bar(index, datas, 0.5, color = 'r', label = '成交量')
		
	plt.show()
Beispiel #8
0
def plot_chart(*tfs, norm=True, realtime=True, markers = None):
    import matplotlib.dates as mdt
    fig, ax = plt.subplots()
    if len(tfs) == 1 and norm is True:
        y = [(mdt.date2num(candle.DateTime), candle.Open, candle.Close, candle.High, candle.Low) for candle in tfs[0].container]
        candlestick(ax, y, width=0.4, colorup='r', colordown='b')
        ax.xaxis_date()
        plt.title(tfs[0].symbol + " chart")
        if markers is not None:
            marker_y, marker_x = [], []
            for elem in tfs[0].container:
                if elem.DateTime in markers:
                    marker_y.append(.5*(elem.Open+elem.Close))
                    marker_x.append(mdt.date2num(elem.DateTime))
            plt.plot(marker_x, marker_y, 'gD')
    else:
        for tf in tfs:
            if realtime is True:
                x = tf.get_Time_list()
            else:
                x = range(len(tf))
            y = np.array(tf.get_C_list())
            if norm is True:
                y -= y.min()
                y /= y.max()
            plt.plot(x, y, label=tf.symbol)
            plt.title("Charts graph")
    plt.legend(loc='upper center', shadow=True)
    plt.xlabel("Time")
    plt.ylabel("Price")
    plt.grid()
    plt.show()
Beispiel #9
0
def plot_data(data,stock):
  ticks = eg.choicebox(msg = 'choose ticks for the plot',choices = ['day','week','month'])
  if ticks == 'month':
    loc = MonthLocator()
  elif ticks == 'week':
    loc = WeekdayLocator(byweekday=MONDAY)
  elif ticks == 'day':
    loc = DayLocator()
  weekFormatter = DateFormatter('%b %d')
  dayFormatter = DateFormatter('%d')
    
#  if candle_chart == 1:
  fig = plt.figure()
  ax1 = fig.add_subplot(211)
  datelist = [matplotlib.dates.date2num(x) for x in data['Time']]
  Prices = []
  for idx in xrange(len(data)):
    Prices.append((datelist[idx],data['Open'].ix[idx],data['Close'].ix[idx],data['High'].ix[idx],data['Low'].ix[idx]))
#    candlestick(ax1,[datelist,data['Open'],data['Close'],data['High'],data['Low']])
  candlestick(ax1,Prices)
  ax1.set_xlabel('Date')
  ax1.set_ylabel('$')
  ax1.set_title('Candlestick plot for %s' %stock)
  ax2 = fig.add_subplot(212)
  ax2.plot(datelist,data['Adj Close'],'-r',label = 'Adj. Close')
  ax2.set_ylabel('$')
  ax2.legend()
  ax3 = ax2.twinx()
  ax3.bar(data['Time'],data['Volume'])
  ax3.set_ylabel('Shares')
  ax1.xaxis_date()
  ax2.xaxis_date()
  ax3.xaxis_date()
  plt.show()
  return
Beispiel #10
0
    def candlestick(self,
                    index,
                    open,
                    high,
                    low,
                    close,
                    width=0.3,
                    secondary_y=False,
                    *args,
                    **kwargs):
        """
            Takes a df and plots a candlestick. 
            Will auto search for proper columns
        """
        data = {}
        data['open'] = open
        data['high'] = high
        data['low'] = low
        data['close'] = close
        df = pd.DataFrame(data, index=index)

        if self.index is None:
            self.index = index

        # grab merged data
        xax = np.arange(len(self.index))
        quotes = izip(xax, df['open'], df['close'], df['high'], df['low'])

        ax = self.find_ax(secondary_y, kwargs)

        self.setup_datetime(index)
        candlestick(ax, quotes, width=width, colorup='g')
    def candlePlot(self,
                   ax,
                   quotes,
                   width=0.6,
                   colorup='r',
                   colordown='g',
                   alpha=0.5):
        if sys.version > '3':
            PY3 = True
        else:
            PY3 = False

        if (PY3 == True):
            mpf.candlestick_ohlc(ax, quotes, width, colorup, colordown, alpha)
        else:
            #opens, closes, highs, lows,
            time = quotes[:, 0]
            opens = quotes[:, 1]
            closes = quotes[:, 4]
            highs = quotes[:, 2]
            lows = quotes[:, 3]
            quotesNew = np.vstack((time, opens, closes, highs, lows))
            mpf.candlestick(ax, quotesNew.T, width, colorup, colordown, alpha)
        ax.xaxis_date()
        ax.autoscale_view()
        #self.addText(ax,quotes[:,0],quotes[:,4])
        for label in ax.xaxis.get_ticklabels():
            label.set_color("red")
            label.set_rotation(30)
            label.set_fontsize(12)
        ax.grid(True)
def plot(key, day, title, filepath, inc24h=False):

    data_raw = get_plot_data(key, day)

    if inc24h:
        if len(data_raw) > 0:
            latest = dt.strptime(data_raw[-1][0], dt_fmt_time)
        else:
            latest = day
        bef24h = latest - timedelta(days=1)
        daya_yest = [ l for l in get_plot_data(key, bef24h) if
                     dt.strptime(l[0], dt_fmt_time) > bef24h ]
        data_raw = daya_yest + data_raw

    # openとcloseは温度計測インターバルで表示が崩れるので使わない。
    # open == closeとし、平均値を表示する。
    data = [ [mdates.date2num(dt.strptime(j[0],dt_fmt_time)), 
                 float(j[1]), float(j[1]), float(j[2]), float(j[3])]
                 for j in data_raw ]

    fig = plt.figure(figsize=(12, 4))
    ax = fig.add_subplot(1, 1, 1)
    ax.set_ymargin(0.001)
    mpl_finance.candlestick(ax, data, width=0.005, alpha=0.5, colorup='r', colordown='b')
    
    ax.grid()
    locator = mdates.AutoDateLocator()
    formatter = mdates.AutoDateFormatter(locator)
    formatter.scaled[1.0/24] = '%H:%M'
    ax.xaxis.set_major_locator(locator)
    ax.xaxis.set_major_formatter(formatter)
    ax.set_title(title)
    plt.savefig(filepath)
Beispiel #13
0
def printKlines(stocks, savepath, fileName):
    stockNum = len(stocks)
    fig = plt.figure()
    fig.set_size_inches(18.5, 18.5)
    i = 1
    for stock in stocks:

        re = getFullQuoteByStock(stock)
        re = re.set_index('date')
        #re.index = pd.to_datetime(re.index)
        data_list = []
        re = re.drop('index', 1)
        for dates, row in re.iterrows():
            date_time = datetime.datetime.strptime(dates, '%Y-%m-%d')
            t = date2num(date_time)
            open, high, low, close = row[:4]
            datas = (t, open, high, low, close)
            data_list.append(datas)

        ax = fig.add_subplot(stockNum, 1, i)
        #fig.subplots_adjust(bottom=0.2)
        ax.xaxis_date()
        #plt.xticks(rotation=45)
        plt.xticks()
        plt.yticks()
        plt.title("STOCK:" + stock)
        plt.xlabel("time")
        plt.ylabel("price")
        mpf.candlestick(ax, data_list, width=1, colorup='r', colordown='green')
        plt.grid()
        i = i + 1
    #plt.show()
    plt.savefig(savepath + fileName, dpi=100)
Beispiel #14
0
    def buildgraph(self):
        
        left, width = 0.1, 0.9
        rect1 = [left, 0.05, width, 0.99]
        size = len(self.mts.getData()) * 0.2
        if size >= 32768:
            size = 31767
        fig = figure(figsize = (size, 10))
        
        axescolor  = '#f6f6f6'
        
        ax = fig.add_axes(rect1, axisbg=axescolor)  #left, bottom, width, height

        # build the series for candles

        M = []
        ts = self.mts.getData()#[0:self.graphperiod]
        t = len(self.mts.getData())
        for i in ts:
            M.insert(0, (t, i[0], i[3], i[1], i[2], 0))
            t -= 1

        candlestick(ax, M, width=0.6)

        M1 = []
        M2 = []
        M3 = []
        t2 = 1
        for i in ts:
            if i[4] == None or i[5] == None:
                t2 += 1
            else:
                M1.insert(0, i[4] + self.K2 * i[5])
                M2.insert(0, i[4])
                M3.insert(0, i[4] - self.K * i[5])

        date=range(t2+t,t+t2+len(M1))
        ax.plot(date, M1)
        ax.plot(date, M2)
        ax.plot(date, M3)

        for i in self.open:
            if i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='cyan')

        for i in self.close:
            if i[2] == "stoploss" and i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='red')
            elif i[2] == "stopgain" and i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='green')
            elif i[2] == "timeout(open)" and i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='blue')
            elif i[2] == "timeout(close)" and i[0] >= t:
                ax.plot([i[0]], [i[1]], 'o', color='blue')

        now = datetime.today().strftime("-%Y-%m-%d-%H-%M-%S");

        filename = "./charts/" + sys.argv[1] + "/" + sys.argv[1] + now + ".png"
        fig.savefig(filename)
Beispiel #15
0
def gpcs_trade(series, trade):
    """Function to plot a candle graph from a given series"""
    
    """takes as input the security code, default TY"""
    from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator, \
         DayLocator, MONDAY
    from matplotlib.finance import quotes_historical_yahoo, candlestick,\
         plot_day_summary, candlestick2
    
    
    mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
    
    alldays    = DayLocator()              # minor ticks on the days
    monthFormatter = DateFormatter('%b %d')  # Eg, Jan 12
    dayFormatter = DateFormatter('%d')      # Eg, 12


    #quotes contains a list of tuples:
    #(date, open, close, high, low, volume)
    quotes = series
    if len(quotes) == 0:
        today = datetime.datetime.now()
        
        date2 = (today.year, today.month, today.day)
        date1 = ( today.year -1, today.month, 1)
        quotes = quotes_historical_yahoo('fut_code', date1, date2)
    if len(quotes) == 0:
        raise SystemExit

    fig = figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    #ax.xaxis.set_major_locator(mondays)
    #ax.xaxis.set_minor_locator(mondays)
    #ax.xaxis.set_major_formatter(monthFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    dt, o, c, h, l, v = zip(*quotes)
    dt2 = []
    for d in dt:
        dt2.append(datetime.datetime.fromordinal(int(d)))
    ser = DataFrame(data = {0:o, 1:c, 2:h, 3:l, 4:v}, index = dt2)
    tmdelta = len(ser[trade.trend.a:])
    ax.plot([trade.trend.a, max(ser.index)], [trade.trend.c_reg, (tmdelta*trade.trend.m_reg + trade.trend.c_reg)], color='r', linestyle='-', linewidth=2)
    ax.plot([trade.trend.a, max(ser.index)], [trade.trend.c_reg+trade.trend.stdev_p_reg, (trade.trend.stdev_p_reg +tmdelta*trade.trend.m_reg + trade.trend.c_reg)], color='g', linestyle='-', linewidth=2)
    ax.plot([trade.trend.a, max(ser.index)], [trade.trend.c_reg-trade.trend.stdev_p_reg, (-trade.trend.stdev_p_reg +tmdelta*trade.trend.m_reg + trade.trend.c_reg)], color='g', linestyle='-', linewidth=2)
    tmdelta = len(ser[trade.trend.a:trade.trend.e])
    ax.plot([trade.trend.a, trade.trend.e], [trade.trend.c_reg, (tmdelta*trade.trend.m_reg + trade.trend.c_reg)], color='b', linestyle='-', linewidth=2)
    
    candlestick(ax, quotes, width=0.6)

    #ax.xaxis_date()
    ax.autoscale_view()
    setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    show()
Beispiel #16
0
 def plot(self, mplSubplot, dateTimes, color):
     if self.__useCandleSticks:
         values = []
         for dateTime in dateTimes:
             bar = self.getValue(dateTime)
             values.append((dates.date2num(dateTime), bar.getOpen(), bar.getClose(), bar.getHigh(), bar.getLow()))
         finance.candlestick(mplSubplot, values, width=0.5, colorup="g", colordown="r")
     else:
         Series.plot(self, mplSubplot, dateTimes, color)
 def candlestick(self, df, width=0.3):
     """
     """
     xax = np.arange(len(df.index))
     quotes = izip(xax, df.open, df.close, df.high, df.low)
     ax = self.ax
     self.df = df
     self.setup_datetime(df.index)
     candlestick(ax, quotes, width=width, colorup="g")
Beispiel #18
0
 def candlestick(self, df, width=0.3):
     """
     """
     xax = np.arange(len(df.index))
     quotes = izip(xax, df.open, df.close, df.high, df.low)
     ax = self.ax
     self.df = df
     self.setup_datetime(df.index)
     candlestick(ax, quotes, width=width, colorup='g')
Beispiel #19
0
    def showTrade(self, position, instrumentName):
        #beforeBars = 300
        #afterBars = 100

        #barsNum = beforeBars + afterBars + (position.closeTime - position.openTime).seconds * 60
        secondsBeforeTrade = 60 * 60
        secondsAfterTrade = 60
        from datetime import timedelta
        data = self.getHistoryBarsByTime(instrumentName, position.openTime - timedelta(seconds=secondsBeforeTrade), position.closeTime + timedelta(seconds=secondsAfterTrade))

        from matplotlib.finance import candlestick


        fig = figure()
        fig.subplots_adjust(bottom=0.2)
        ax = fig.add_subplot(111)
        data = self.quotesToCandlestick(data)

        from matplotlib.lines import Line2D
        from matplotlib.dates import date2num
        color = 'red'
        if position.order.orderType is 1:
            color='green'

        candlestick(ax, data, width=0.00006, colorup='g', colordown='r')

        enter = Line2D(
        xdata=(date2num(position.openTime), date2num(position.closeTime)), ydata=(position.openPrice, position.closePrice),
        color=color,
        linewidth=5,
        antialiased=True,
        )

        if position.order.target is not 0:
            tp = Line2D(
            xdata=(date2num(position.openTime), date2num(position.closeTime)), ydata=(position.order.target, position.order.target),
            color='g',
            linewidth=0.5,
            antialiased=True,
            )
            ax.add_line(tp)

        if position.order.stop is not 0:
            sl = Line2D(
            xdata=(date2num(position.openTime), date2num(position.closeTime)), ydata=(position.order.stop, position.order.stop),
            color='r',
            linewidth=0.5,
            antialiased=True,
            )
            ax.add_line(sl)


        ax.add_line(enter)
        ax.autoscale_view()

        show()
Beispiel #20
0
def plotStats():
	#columns: time, opening, close, high, low
	candlestick_data = 5 
	quotes = [(0, 103.62, 102.01, 103.62, 101.90),
          (1, 102.24, 102.90, 103.16, 102.09),
          (2, 100.89, 102.59, 102.86, 100.51)]

	fig, ax = plt.subplots()	
	candlestick(ax, quotes, width=0.5, colorup='g', colordown='r')
	plt.show()
Beispiel #21
0
 def plot(self, mplSubplot, dateTimes, color):
     if self.__useCandleSticks:
         values = []
         for dateTime in dateTimes:
             bar = self.getValue(dateTime)
             if bar:
                 values.append((dates.date2num(dateTime), bar.getOpen(), bar.getClose(), bar.getHigh(), bar.getLow()))
         finance.candlestick(mplSubplot, values, width=0.5, colorup='g', colordown='r',)
     else:
         Series.plot(self, mplSubplot, dateTimes, color)
def graphDataCandlestick(ticker, date, openp, highp, lowp, closep, volume, intradata):
    fig = plt.figure() # facecolor='#07000d'
    
    ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4) #, axisbg='#07000d'
    candlestick(ax1, intradata[-len(intradata):], width=.0005, colorup='#53c156', colordown='#ff1717')
    #plot_day_summary2_ochl(ax1, openp, closep, closep, lowp, ticksize=4, colorup='k', colordown='r')
    
    # CUSTOMIZE AXES 1
    ax1.grid(True)
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M:%S'))
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.set_ylim(0.75 * lowp.min(), 1.25 * highp.max())
    plt.ylabel('Stock price and Volume')
    
    # Colors
    ax1.yaxis.label.set_color('w')
    ax1.spines['bottom'].set_color('#5998ff')
    ax1.spines['left'].set_color('#5998ff')
    ax1.spines['right'].set_color('#5998ff')
    ax1.spines['top'].set_color('#5998ff')
    ax1.tick_params(axis='y', colors='w')
    ax1.tick_params(axis='x', colors='w')
    
    for label in ax1.xaxis.get_ticklabels():
        label.set_rotation(45)
    
    volumeMin = 0
    
    ax1v = ax1.twinx()
    ax1v.axes.yaxis.set_ticklabels([])
    ax1v.grid(False)
    ax1v.set_ylim(0, 3*volume.max())
    ax1v.axes.yaxis.set_ticklabels([])
    
    # Colors
    ax1v.spines['bottom'].set_color('#5998ff')
    ax1v.spines['left'].set_color('#5998ff')
    ax1v.spines['right'].set_color('#5998ff')
    ax1v.spines['top'].set_color('#5998ff')
    ax1v.tick_params(axis='y', colors='w')
    ax1v.tick_params(axis='x', colors='w')
    ax1v.bar(date, volume, color='w', width=.0005)
    
    #ax2 = plt.subplot2grid((4,4), (5,0), rowspan=2, colspan=4) # 3 rows down
    
    #ax2.grid(True)
    #plt.ylabel('Volume')
    
    # Formats the plot
    plt.subplots_adjust(left=.09, bottom=.18, right=.94, top=.95, wspace=.20, hspace=0)
    plt.setp(ax1.get_xticklabels(), visible=True)
    plt.xlabel('Date')
    
    plt.show()
Beispiel #23
0
 def peakValleyPlot(self):
     fig = py.figure()
     fig.subplots_adjust(bottom=0.2)
     ax = fig.add_subplot(111)
     candlestick(ax,self.quotes, width=0.6)   
     ax.xaxis_date()
     ax.autoscale_view()
     setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')        
     # plot the peaks and valleys
     plot(self.quotes[:,0],self.peakPrices,'go',markersize = 6)
     
     plot(self.quotes[:,0],self.valleyPrices,'r^', markersize = 6)       
Beispiel #24
0
def graphData(datafile, MA1, MA2):

    def bytedate2num(fmt):
        def converter(b):
            return mdates.strpdate2num(fmt)(b.decode('utf8'))
        return converter

    datep, openp, highp, lowp, closep, volume = \
        np.loadtxt(datafile, unpack=True , usecols=(0,2,3,4,5,6), \
                converters={ 0: bytedate2num("%Y-%m-%d")})

    candleAr = []
    #while x < y:
    for x in range(len(datep)):
        appendLine = datep[x],openp[x],closep[x],highp[x],lowp[x],volume[x] #highp[x],lowp[x],closep[x],volume[x]
        candleAr.append(appendLine)
    #print (candleAr)

    AV1 = movingaverage(closep, MA1)
    AV2 = movingaverage(closep, MA2)
    SP = len(datep[MA2-1:])

    fig = plt.figure()
    ax1 = plt.subplot2grid((5,4),(0,0),rowspan=4, colspan=4)
    candlestick(ax1, candleAr, width=0.5, colorup='g', colordown='r')

    ax1.plot(datep[-SP:],AV1[-SP:])
    ax1.plot(datep[-SP:],AV2[-SP:])

    #ax1.plot(datep, openp)
    #ax1.plot(datep, highp)
    #ax1.plot(datep, lowp)
    #ax1.plot(x=datep, y=closep)
    ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    plt.ylabel('Stock price')
    ax1.grid(True)

    ax2 = plt.subplot2grid((5,4),(4,0), sharex=ax1, rowspan=1, colspan=4)
    ax2.bar(datep, volume)
    ax2.axes.yaxis.set_ticklabels([])
    plt.ylabel('Volume')
    ax2.grid(True)

    for label in ax2.xaxis.get_ticklabels():
        label.set_rotation(45)

    plt.subplots_adjust(left=.10,bottom=.19,right=.93,top=.95, wspace=.20, hspace=.07)
    plt.xlabel('Date')
    plt.suptitle('GAZP')
    plt.setp(ax1.get_xticklabels(), visible=False)
    #fig.savefig('example.png')
    plt.show()
Beispiel #25
0
def create_figure(quotes):

    f = Figure(figsize=(5, 4), dpi=100)

    a = f.add_subplot(111)
    canvas = FigureCanvas(f)  # a gtk.DrawingArea
    canvas.set_size_request(800, 300)

    a.xaxis_date()

    finance.candlestick(a, quotes, width=0.5)

    return f
Beispiel #26
0
def create_figure(quotes):

  f = Figure(figsize=(5,4), dpi=100)

  a = f.add_subplot(111)
  canvas = FigureCanvas(f)  # a gtk.DrawingArea
  canvas.set_size_request(800,300)

  a.xaxis_date()
  
  finance.candlestick(a, quotes, width=0.5)

  return f
Beispiel #27
0
    def plotByChange(self, savePic):
        timeAxis=self.quotes[:,0]
        fig = py.figure()
        
        fig.subplots_adjust(bottom=0.2)
        ax = fig.add_subplot(111)
        candlestick(ax, self.quotes, width=0.6)
        
        ax.xaxis_date()
        ax.autoscale_view()
        setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')

        plot(timeAxis[self.flagPeaks],self.peakPrices,'go',markersize = 6)
        plot(timeAxis[self.flagValleys],self.valleyPrices,'r^', markersize = 6)
        

                     
                     
        if self.score != 0:
            # check if the peak or trough flag the current price    
            for i in range(len(self.comparators)):
                if sum(self.flagIndicatorsCounter,0)[i] == 0:
                    continue
                else:
                    
                    plot(timeAxis[self.comparatorIndices[i]], self.comparators[i], '*')
                    
             
        for e in self.annotation:
            time = e[0]
            price = e[1]
            flag = e[2]
            ax.annotate(str(price)+'('+flag+')',xy=(time,price))
                
        
        #ax.annotate(str(round(self.quotes[-1,4],2)),xy=(timeAxis[-1],self.quotes[-1,4]))
        ax.annotate(str(round(self.currentPriceWeCare,2)),xy=(timeAxis[-1],self.quotes[-1,4]))
        
        currentTime = str(datetime.date.fromordinal(int(timeAxis[-1]))) 
        title=['Flagging points for',self.tradeType,'trading strategy of',self.stock,currentTime]
        py.title(' '.join(title))
        py.grid()
        
        
        if savePic==True:
            if 1:
                py.savefig('pic/all/'+self.stock+currentTime+'.png', format='png')
            else:
                py.savefig('pic/sell_ft/'+self.stock+currentTime+'.png', format='png')
            py.clf()
            py.close()
Beispiel #28
0
def graphData(stock):
    try:
        stockFile = 'data.csv'

        date, closep, highp, lowp, openp, volume = np.loadtxt(
            stockFile,
            delimiter=',',
            unpack=True,
            converters={0: mdates.strpdate2num('%Y%m%d')})

        x = 0
        y = len(date)
        candleAr = []
        while x < y:
            appendLine = date[x], openp[x], closep[x], highp[x], lowp[
                x], volume[x]
            candleAr.append(appendLine)
            x += 1

        fig = plt.figure()
        ax1 = plt.subplot2grid((5, 4), (0, 0), rowspan=4, colspan=4)
        candlestick(ax1, candleAr, width=1, colorup='g', colordown='r')

        ax1.grid(True)
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        plt.ylabel('Stock price')

        ax2 = plt.subplot2grid((5, 4), (4, 0),
                               sharex=ax1,
                               rowspan=1,
                               colspan=4)
        ax2.bar(date, volume, color='red', align='center')
        ax2.grid(True)
        plt.ylabel('Volume')
        for label in ax2.xaxis.get_ticklabels():
            label.set_rotation(45)

        plt.xlabel('Date')
        plt.suptitle(stock + ' Stock Price')
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.subplots_adjust(left=.09,
                            bottom=.18,
                            right=.94,
                            top=.94,
                            wspace=.20,
                            hspace=0)
        plt.show()

    except Exception, e:
        print 'main loop', str(e)
def candleStickGraph(inputData):
    fig = plt.figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    ax.set_xticklabels()
    ax.set_title()
    #ax.xaxis.set_minor_formatter(dayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick(ax, inputData, width=0.2)

    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
Beispiel #30
0
    def plotCandle(self,*args):

        df = self.getData()
        df['date'] = date2num(df.index)
        fig, ax = subplots()
        candlestick(ax, df[['date', 'Open', 'Close', 'High', 'Low']].values, width=.75, colorup='g',
                    colordown='r')
        ax.xaxis_date()
        plt.xlabel('Date')
        #plt.suptitle(ticker)
        ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        for label in ax.xaxis.get_ticklabels():
            label.set_rotation(45)
        ax.grid(True)
        plt.show()
Beispiel #31
0
def plot(tickBarsPlot, ma, trades, plotCandle=True, plotMa=True):
    # Create a numpy array for more manipulation flexibility
    data = np.array(tickBarsPlot)
    dataSwitched = data[:, 1][np.newaxis].T                                     # Open
    dataSwitched = np.append(dataSwitched, data[:, 4][np.newaxis].T, axis=1)    # Close
    dataSwitched = np.append(dataSwitched, data[:, 2][np.newaxis].T, axis=1)    # High
    dataSwitched = np.append(dataSwitched, data[:, 3][np.newaxis].T, axis=1)    # Low
    # This replaces the first column with numbers 0..size-1
    data2 = np.append(np.arange(data[:,0].size)[:, np.newaxis], dataSwitched, axis=1)
    data2tuple = [tuple(x) for x in data2]
    # Chart ticks are on the hour
    ticks = np.unique(np.trunc(data[:,0] / 10000), return_index=True)
    fig = plt.figure(figsize=(10, 5))
    # These numbers define margin from window edge
    ax = fig.add_axes([0.1, 0.2, 0.85, 0.7])
    ax.set_xticks(data2[ticks[1], 0])
    ax.set_xticklabels(map(int, data[ticks[1], 0]), rotation=90)
    
    # Plot prices
    if plotCandle:
        candlestick(ax, data2tuple, width=0.5, colorup='g', colordown='r')
    else:
        ax.plot(data[:,4])

    # Plot moving average
    if plotMa:
        ax.plot(ma)

    # Plot trades
    buys = []
    sells = []
    for trade in trades:
        timestampFloat = (float(trade.timestamp[0:2]) * 1000000 +
                          float(trade.timestamp[3:5]) * 10000 +
                          float(trade.timestamp[6:8]) * 100 +
                          float(trade.timestamp[9:11]))
        if trade.quantity > 0:
            buys.append(timestampFloat)
        else:
            sells.append(timestampFloat)
    # Find index of buys in the data array before plotting
    ix = np.where(np.in1d(data[:,0], buys))[0]
    ax.plot(ix, data[:,4][ix], 'g^')
    # Find index of sells in the data array before plotting
    ix = np.where(np.in1d(data[:,0], sells))[0]
    ax.plot(ix, data[:,4][ix], 'rv')
    plt.show()
def graphData(stock):
    try:
        stockFile = stock+'.txt'

        date, closep,highp,lowp,openp,volume = np.loadtxt(stockFile,delimiter=',',unpack=True,converters ={ 0: mdates.strpdate2num('%Y%m%d')})

        x = 0
	y = len(date)
	candleAr = []
	while x < y:
	    appendLine = date[x],openp[x],closep[x],highp[x],lowp[x],volume[x]
	    candleAr.append(appendLine)
	    x+=1
#        

	fig = plt.figure()
#	ax1 = plot.subplot(2,1,1)#(2,3,1) would be position 1 in a 2 by 3 square
        ax1 = plt.subplot2grid((5,4), (0,0), rowspan=4, colspan=4)
        candlestick(ax1, candleAr, width=.75, colorup ='g', colordown='r')

	ax1.grid(True)
	ax1.xaxis.set_major_locator(mticker.MaxNLocator(10)) #max of 10 dates
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
	plt.ylabel('Stock price')

#	ax2 = plt.subplot(2,1,2 sharex=ax1) #shares the zoomin
        ax2 = plt.subplot2grid((5,4), (4,0), sharex=ax1, rowspan=1, colspan=4)
	ax2.bar(date, volume)
	ax2.axes.yaxis.set_ticklabels([])
	ax2.grid(True)
	plt.ylabel('Volume')
	for label in ax2.xaxis.get_ticklabels():
	    label.set_rotation(45)

        plt.xlabel('Date')
	plt.ylabel('Stock Price')
	plt.suptitle(stock+' Stock Price')
	#ax1.axes.yaxis.set_visible(False)  nope
        #ax1.axes.xaxis.set_ticklabels([])  nope
        plt.setp(ax1.get_xticklabels(), visible=False)
	plt.subplots_adjust(left=.09,top = .94,bottom = .18, right = .94, wspace = .20, hspace = 0)

	plt.show()
        fig.savefig(stock+'.png')

    except Exception,e:
        print 'filed main loop',str(e)
Beispiel #33
0
    def plot(self):

        self.axes.clear()
        self.axes.grid(True)

        candlestick(self.axes, self.quotes, width=0.01)

        self.axes.xaxis_date()
        self.axes.autoscale_view()
        x_labels = self.axes.get_xticklabels()
        setp(x_labels, rotation=45, horizontalalignment='right')
        
        if self.below_absolute_enabled:
            self.axes.axhline(self.below_absolute_value)
        if self.above_absolute_enabled:
            self.axes.axhline(self.above_absolute_value)

        self.draw()
Beispiel #34
0
def gpcs(series):
    """Function to plot a candle graph from a given series"""
    
    """takes as input the security code, default TY"""
    from matplotlib.dates import  DateFormatter, WeekdayLocator, HourLocator, \
         DayLocator, MONDAY
    from matplotlib.finance import quotes_historical_yahoo, candlestick,\
         plot_day_summary, candlestick2
    
    
    mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
    
    alldays    = DayLocator()              # minor ticks on the days
    monthFormatter = DateFormatter('%b %d')  # Eg, Jan 12
    dayFormatter = DateFormatter('%d')      # Eg, 12


    #quotes contains a list of tuples:
    #(date, open, close, high, low, volume)
    quotes = series
    if len(quotes) == 0:
        today = datetime.datetime.now()
        
        date2 = (today.year, today.month, today.day)
        date1 = ( today.year -1, today.month, 1)
        quotes = quotes_historical_yahoo('fut_code', date1, date2)
    if len(quotes) == 0:
        raise SystemExit

    fig = figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    #ax.xaxis.set_major_locator(mondays)
    #ax.xaxis.set_minor_locator(mondays)
    #ax.xaxis.set_major_formatter(monthFormatter)
    #ax.xaxis.set_minor_formatter(dayFormatter)

    #plot_day_summary(ax, quotes, ticksize=3)
    candlestick(ax, quotes, width=0.6)

    #ax.xaxis_date()
    ax.autoscale_view()
    setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')
Beispiel #35
0
    def draw_subgraph(self, stockdat, numt):
        """ 绘制K线图 """
        ohlc = list(
            zip(np.arange(0, len(stockdat.index)), stockdat.Open,
                stockdat.Close, stockdat.High, stockdat.Low))  #使用zip方法生成数据列表
        mpf.candlestick(self.am, ohlc, width=0.5, colorup='r',
                        colordown='g')  #绘制K线走势
        ''' 绘制均线 '''
        self.am.plot(numt, stockdat['Ma20'], 'black', label='M20', lw=1.0)
        self.am.plot(numt, stockdat['Ma60'], 'green', label='M60', lw=1.0)
        self.am.plot(numt, stockdat['Ma120'], 'blue', label='M120', lw=1.0)
        self.am.legend(loc='best', shadow=True, fontsize='10')
        ''' 绘制成交量 '''
        self.vol.bar(numt,
                     stockdat.Volume,
                     color=[
                         'g' if stockdat.Open[x] > stockdat.Close[x] else 'r'
                         for x in range(0, len(stockdat.index))
                     ])
        ''' 绘制MACD '''
        #绘制BAR>0 柱状图
        bar_red = np.where(stockdat['macd_bar'] > 0, 2 * stockdat['macd_bar'],
                           0)
        #绘制BAR<0 柱状图
        bar_green = np.where(stockdat['macd_bar'] < 0,
                             2 * stockdat['macd_bar'], 0)

        self.macd.plot(numt, stockdat['macd_dif'], 'red',
                       label='macd dif')  #dif
        self.macd.plot(numt, stockdat['macd_dea'], 'blue',
                       label='macd dea')  #dea
        self.macd.bar(numt, bar_red, facecolor='red', label='hist bar')
        self.macd.bar(numt, bar_green, facecolor='green', label='hist bar')
        self.macd.legend(loc='best', shadow=True, fontsize='10')
        #legend = self.macd.legend(loc='best',shadow=True, fontsize ='10')
        #legend.get_frame().set_facecolor('#00FFCC')# Put a nicer background color on the legend.
        #legend.get_title().set_fontsize(fontsize = 20)
        ''' 绘制KDJ '''
        self.devol.plot(numt, stockdat['K'], 'blue', label='K')  #K
        self.devol.plot(numt, stockdat['D'], 'g--', label='D')  #D
        self.devol.plot(numt, stockdat['J'], 'r-', label='J')  #J
        self.devol.legend(loc='best', shadow=True, fontsize='10')
Beispiel #36
0
def draw_graph(quotes, title, bull_market):
    if not hasattr(draw_graph, "fig"):
        draw_graph.fig = figure()  # it doesn't exist yet, so initialize it
    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays = DayLocator()              # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # Eg, Jan 12
    dayFormatter = DateFormatter('%d')      # Eg, 12
    draw_graph.fig.clear()
    graph = draw_graph.fig.add_subplot(111)
    graph.xaxis.set_major_locator(mondays)
    graph.xaxis.set_minor_locator(alldays)
    graph.xaxis.set_major_formatter(weekFormatter)
    graph.xaxis_date()
    graph.autoscale_view()
    candlestick(graph, quotes, width=0.6)
    setp(gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    draw_graph.fig.suptitle(title + " " + str(bull_market), fontsize=12)
    draw_graph.fig.subplots_adjust(bottom=0.2)
    draw_graph.fig.canvas.mpl_connect('key_press_event', press)
    draw_graph.fig.canvas.draw()
Beispiel #37
0
def save_candlestick_chart(fname, quotes):
    '''
    quotes should have the following format: [(date1, open1, close1, high1, low1), (date2, open2, ...), (...), ...]
    '''
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %d')

    fig = pl.figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)

    candlestick(ax, quotes, width=0.6, colorup='g')
    ax.xaxis_date()
    ax.autoscale_view()
    pl.setp(pl.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    pl.savefig(fname)
Beispiel #38
0
    def plot(self):
        if len(self.tdata) > self.maxt:  # roll the arrays
            self.tdata = self.tdata[-self.maxt:]
            self.sdata = self.sdata[-self.maxt:]
            self.mdata = self.mdata[-self.maxt:]
            self.result = self.result[-self.maxt:]

        # Plot the next set of line data
        line_min = Line2D(self.tdata, self.sdata, color='r')
        self.ax.add_line(line_min)
        line_max = Line2D(self.tdata, self.mdata, color='g')
        self.ax.add_line(line_max)

        # Plot the next set of candlestick data
        candlestick(self.ax, self.result, width=60 / 86400.0,  colorup='g', colordown='r')

        # Update the x-axis time date and limits
        if len(self.tdata) > 1:
            self.ax.set_xlim(self.tdata[0], self.tdata[-1])

        # Update the y-axis limits
        self.ax.set_ylim(min(self.sdata) * 0.99, max(self.mdata) * 1.01)
Beispiel #39
0
def plot(tickBarsPlot, ma, trades, candle=False):
    # Create a numpy array for more manipulation flexibility
    data = np.array(tickBarsPlot)
    # This replaces the first column with numbers 1..size
    data2 = np.hstack([np.arange(data[:, 0].size)[:, np.newaxis], data[:, 1:]])
    # Ticks are on the hour
    ticks = np.unique(np.trunc(data[:, 0] / 10000), return_index=True)
    fig = plt.figure(figsize=(10, 5))
    # These numbers define margin from window edge
    ax = fig.add_axes([0.1, 0.2, 0.85, 0.7])
    ax.set_xticks(data2[ticks[1], 0])
    ax.set_xticklabels(data[ticks[1], 0], rotation=90)

    # Plot prices
    if candle:
        candlestick(ax, data2, width=0.5, colorup='g', colordown='r')
    else:
        ax.plot(data[:, 4])

    # Plot moving average
    ax.plot(ma)

    # Plot trades
    buys = []
    sells = []
    for trade in trades:
        timestampFloat = float(trade.timestamp[0:2]) * 10000 + float(
            trade.timestamp[3:5]) * 100 + float(trade.timestamp[6:8])
        if trade.tradeQuantity > 0:
            buys.append(timestampFloat)
        else:
            sells.append(timestampFloat)
    # Find index of buys in the data array before plotting
    ix = np.where(np.in1d(data[:, 0], buys))[0]
    ax.plot(ix, data[:, 4][ix], 'g^')
    # Find index of sells in the data array before plotting
    ix = np.where(np.in1d(data[:, 0], sells))[0]
    ax.plot(ix, data[:, 4][ix], 'rv')
    plt.show()
Beispiel #40
0
    def candlestick(self, index, open, high, low, close, width=0.3, secondary_y=False,
                   *args, **kwargs):
        """
            Takes a df and plots a candlestick. 
            Will auto search for proper columns
        """
        data = {}
        data['open'] = open
        data['high'] = high
        data['low'] = low
        data['close'] = close
        df = pd.DataFrame(data, index=index)
        self.add_data(df)

        # grab merged data
        xax = np.arange(len(self.df.index))
        quotes = izip(xax, self.df['open'], self.df['close'], self.df['high'], self.df['low'])

        ax = self.find_ax(secondary_y, kwargs)

        self.setup_datetime(index)
        candlestick(ax, quotes, width=width, colorup='g')
Beispiel #41
0
def save_candlestick_chart(fname, quotes):
    '''
    quotes should have the following format: [(date1, open1, close1, high1, low1), (date2, open2, ...), (...), ...]
    '''
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %d')

    fig = pl.figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)

    candlestick(ax, quotes, width=0.6, colorup='g')
    ax.xaxis_date()
    ax.autoscale_view()
    pl.setp(pl.gca().get_xticklabels(),
            rotation=45,
            horizontalalignment='right')

    pl.savefig(fname)
Beispiel #42
0
    def update(self, quotes, clear=False):

        if clear:
            # clear old data
            self.ax.cla()

        # axis formatting
        d = []
        for value in quotes:
            data = value[0]
            d.append(data)
        self.ax.set_xlim([min(d), max(d) + 0.0010])

        self.ax.xaxis.set_major_formatter(dates.DateFormatter('%H:%M:%S'))
        # plot quotes
        candlestick(self.ax, quotes, width=0.00005)

        # more formatting
        self.ax.xaxis_date()
        self.ax.autoscale_view()
        plt.setp(plt.gca().get_xticklabels(),
                 rotation=45,
                 horizontalalignment='right')
    def update(self, quotes, clear=False):

        if clear:
            # clear old data
            self.ax.cla()

        # axis formatting
        self.ax.xaxis.set_major_locator(mondays)
        self.ax.xaxis.set_minor_locator(alldays)
        self.ax.xaxis.set_major_formatter(weekFormatter)

        # plot quotes
        candlestick(self.ax, quotes, width=0.6)

        # more formatting
        self.ax.xaxis_date()
        self.ax.autoscale_view()
        plt.setp(plt.gca().get_xticklabels(),
                 rotation=45,
                 horizontalalignment='right')

        # use draw() instead of show() to update the same window
        plt.draw()
Beispiel #44
0
    def generateGraph(self, quotes):
        self.clearGraphData()

        #print "DEBUG:"
        #print "\tquotes = %s" % quotes

        #for i in range(len(highs)):
        #    print "DEBUG: (%s, %s, %s, %s)" %(lows[i], opens[i], closes[i], highs[i])
        #    print "DEBUG: diffs h/l: %s o/c: %s" %(lows[i] - highs[i], opens[i] - closes[i])

        self.ax = self.fig.add_subplot(111)

        self.ax.set_title(_("Session candlestick graph"))

        #Set axis labels and grid overlay properites
        self.ax.set_xlabel(_("Sessions"), fontsize = 12)
        self.ax.set_ylabel("$", fontsize = 12)
        self.ax.grid(color='g', linestyle=':', linewidth=0.2)

        candlestick(self.ax, quotes, width=0.50, colordown='r', colorup='g', alpha=1.00)
        self.graphBox.add(self.canvas)
        self.canvas.show()
        self.canvas.draw()
def quote_track(stock_num):
    from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY
    from matplotlib.finance import quotes_historical_yahoo, candlestick
    from matplotlib.font_manager import FontProperties

    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=18)
    # 定义起始、终止日期和股票代码
    date2 = datetime.date.today()
    date1 = date2 - datetime.timedelta(days=30)
    # 定义日期格式
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %d')
    # 获取股票数据
    quotes = quotes_historical_yahoo(stock_num, date1, date2)
    if len(quotes) == 0:
        raise SystemExit
    print(quotes)
    # 绘制蜡烛线或美国线
    fig = figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #注释掉下面的其中一行,可以得到蜡烛线或美国线
    candlestick(ax, quotes, width=0.6)
    #plot_day_summary(ax, quotes, ticksize=3)
    ax.xaxis_date()
    ax.autoscale_view()
    setp(gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    stockdata = get_stock_hexun(stock_num)
    title(u'%s %s 昨收盘:%s 今开盘:%s 当前价:%s' %
          (stock_num, stockdata['na'], stockdata['pc'], stockdata['op'],
           stockdata['la']),
          fontproperties=font)
    show()
Beispiel #46
0
def main():
    os.system('clear')

    print('Program Start')
    print('Scraping: NASDAQ for AAPL')
    
    det_titles, det_open, det_high, det_low, det_close = stock_report()
    print('Result: The following information has been pulled from NASDAQ')
    prices = []

    for detail_title, detail_open, detail_high, detail_low, detail_close in zip(det_titles, det_open, det_high, det_low, det_close):
        date1 = detail_title
        date1 = date2num(datetime.strptime(date1, '%b %d, %Y'))
        tup = (date1, float(detail_open), float(detail_close), float(detail_high), float(detail_low))
        prices.append(tup)
        
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %d')
    dayFormatter = ('%d')
    
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    candlestick(ax, prices, width=0.6)

    ax.xaxis_date()
#    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    plt.show()

    py.sign_in('chriskoh', 'yyy0hoavmt')

    plot_url = py.plot_mpl(fig)
Beispiel #47
0
def showStock(stock_num, date1, date2):
    # define the code number and begin end date
    # date1 = ( 2012, 12, 25 )
    # date2 = ( 2013, 6, 1 )
    # stock_num = '000651.sz'
    # define date format
    # get the stock data
    quotes = quotes_historical_yahoo(stock_num, date1, date2)
    if len(quotes) == 0:
        raise SystemExit
    # draw k line of stock
    fig = figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    candlestick(ax, quotes, width=0.6)
    # plot_day_summary(ax, quotes, ticksize=3)
    ax.xaxis_date()
    ax.autoscale_view()
    setp(gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    title(u'2012,12,25-2013,6,1', fontproperties=font)
    show()
def quote_track(stock_num):
    from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY
    from matplotlib.finance import quotes_historical_yahoo, candlestick
    from matplotlib.font_manager import FontProperties

    font = FontProperties(fname=r"c:\windows\fonts\simsun.ttc", size=18)
    # 定义起始、终止日期和股票代码
    date2 = datetime.date.today()
    date1 = date2 - datetime.timedelta(days=30)
    # 定义日期格式
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %d')
    # 获取股票数据
    quotes = quotes_historical_yahoo(stock_num, date1, date2)
    if len(quotes) == 0:
        raise SystemExit
    print(quotes)
    # 绘制蜡烛线或美国线
    fig = figure()
    fig.subplots_adjust(bottom=0.2)
    ax = fig.add_subplot(111)
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(alldays)
    ax.xaxis.set_major_formatter(weekFormatter)
    #注释掉下面的其中一行,可以得到蜡烛线或美国线
    candlestick(ax, quotes, width=0.6)
    #plot_day_summary(ax, quotes, ticksize=3)
    ax.xaxis_date()
    ax.autoscale_view()
    setp(gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    stockdata = get_stock_hexun(stock_num)
    title(
        u'%s %s 昨收盘:%s 今开盘:%s 当前价:%s' % (stock_num, stockdata['na'], stockdata['pc'], stockdata['op'], stockdata['la']),
        fontproperties=font)
    show()
Beispiel #49
0
def graphDataMACDRSI(stock, MA1, MA2, dateRange=365):
    try:
        stockFile = 'web2py/applications/blash/static/prices/' + stock + '.txt'
        date, closep, highp, lowp, openp, volume = np.loadtxt(
            stockFile,
            delimiter=',',
            unpack=True,
            converters={0: mdates.strpdate2num('%Y%m%d')})

        x = 0
        y = len(date)
        candleAr = []

        #print date
        while x < y:
            appendLine = date[x], openp[x], closep[x], highp[x], lowp[
                x], volume[x]
            candleAr.append(appendLine)
            x += 1

        # using close data with either 12 or 26 day moving average
        Av1 = movingaverage(closep, MA1)
        Av2 = movingaverage(closep, MA2)
        # Starting point of data since we need at least 12 or 26 data points to get an SMAS
        SP = len(date[MA2 - 1:])

        label1 = str(MA1) + ' SMA'
        label2 = str(MA2) + ' SMA'

        fig = plt.figure(facecolor='gray')  # blue = '30414D'

        # How many graphs appear on png, in this case, it has place for 2 and we are choosing slot 1
        # ax1 = plt.subplot(2,1,1)
        ax1 = plt.subplot2grid((6, 4), (1, 0),
                               rowspan=4,
                               colspan=4,
                               axisbg='#30414D')
        #Black = #07000d Blue = #30414D
        # Calling the Candlestick function made from the previous while loop

        candlestick(ax1,
                    candleAr,
                    width=0.7,
                    colorup='#9eff15',
                    colordown='#ff1717')
        # Graphing the date vs moving average starting from SP to current
        ax1.plot(date[-SP:], Av1[-SP:], '#5998ff', label=label1, linewidth=1.5)
        ax1.plot(date[-SP:], Av2[-SP:], '#e1edf9', label=label2, linewidth=1.5)
        # Shows a max of 10 dates on x-axis, formats it it Year-Month-Day
        #ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        #ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

        ax1.yaxis.label.set_color("black")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
        ax1.spines['left'].set_color("#5998ff")
        ax1.spines['right'].set_color("#5998ff")
        ax1.tick_params(axis='y', colors='black')
        ax1.tick_params(axis='x', colors='black')
        plt.ylabel('Stock price')
        #ax1.set_xlim(left=735872.)
        ax1.grid(True)
        ax1.xaxis_date()

        volumeMin = 0  #volume.min()

        maLeg = plt.legend(loc=9, ncol=2, prop={'size': 10}, fancybox=True)
        maLeg.get_frame().set_alpha(0.4)
        textEd = pylab.gca().get_legend().get_texts()
        pylab.setp(textEd[0:5], color='w')

        ax0 = plt.subplot2grid((6, 4), (0, 0),
                               sharex=ax1,
                               rowspan=1,
                               colspan=4,
                               axisbg='#30414D')
        rsi = rsiFunc(closep)
        rsiBottomColor = 'green'
        rsiTopColor = 'red'
        ax0.plot(date, rsi, 'w', linewidth=1.5)
        #ax0.axhline(70, color = rsiTopColor)
        #ax0.axhline(70, color = rsiTopColor) # These did not work in mpld3
        ax0.plot(date, constantFunc(70, date), 'red')
        ax0.plot(date, constantFunc(30, date), color=rsiBottomColor)
        ax0.spines['bottom'].set_color("#5998ff")
        ax0.spines['top'].set_color("#5998ff")
        ax0.spines['left'].set_color("#5998ff")
        ax0.spines['right'].set_color("#5998ff")
        ax0.tick_params(axis='x', colors='black')
        ax0.tick_params(axis='y', colors='black')
        ax0.set_yticks([30, 70])
        ax0.yaxis.label.set_color('black')
        ax0.xaxis_date()
        #plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='both'))
        plt.ylabel('RSI')

        # Version 1.4: Volume Overlay
        # -------------------------------------------------------------------------------------------
        # Overlay, but it doesn't work in mpld3
        '''
        ax1v = ax1.twinx()
        # Using the volumeMin to start as bottom, for stylistic purpose
        ax1v.fill_between(date, volumeMin, volume, facecolor='#00ffe8', alpha=0.5)
        ax1v.axes.yaxis.set_ticklabels([])
        ax1v.grid(False)
        ax1v.spines['bottom'].set_color("#5998ff")
        ax1v.spines['top'].set_color("#5998ff")
        ax1v.spines['left'].set_color("#5998ff")
        ax1v.spines['right'].set_color("#5998ff")
        ax1v.set_ylim(0,5*volume.max())
        ax1v.tick_params(axis='x', colors = 'black')
        ax1v.tick_params(axis='y', colors = 'black')
        '''
        # Version 1.6: MACD
        ax2 = plt.subplot2grid((6, 4), (5, 0),
                               sharex=ax1,
                               rowspan=1,
                               colspan=4,
                               axisbg='#30414D')
        nslow = 26
        nfast = 12
        nema = 9

        emaslow, emafast, macd = computeMACD(closep)
        ema9 = ExpMovingAverage(macd, nema)  # signal line

        ax2.plot(date, macd, color='w', label='MACD')
        ax2.plot(date, ema9, color='r', label='EMA')
        ax2.plot(date, constantFunc(0, date), color='yellow')
        ax2Legend = ax2.legend(loc='upper left',
                               ncol=2,
                               prop={'size': 8},
                               fancybox=True)
        ax2Legend.get_frame().set_alpha(0.40)
        ax2LegText = pylab.gca().get_legend().get_texts()
        pylab.setp(ax2LegText[0:5], color='w')
        #ax2.fill_between(date, macd-ema9, 0, alpha = 0.5, facecolor = 'red', edgecolor = 'w')

        ax2.spines['bottom'].set_color("#5998ff")
        ax2.spines['top'].set_color("#5998ff")
        ax2.spines['left'].set_color("#5998ff")
        ax2.spines['right'].set_color("#5998ff")
        ax2.tick_params(axis='x', colors='black')
        ax2.tick_params(axis='y', colors='black')

        ax2.xaxis.set_major_locator(mticker.MaxNLocator(5))
        #ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

        ax2.xaxis_date()
        for label in ax2.xaxis.get_ticklabels():
            label.set_rotation(45)

        plt.ylabel('MACD', color='black')
        sortDate(date, dateRange)
        # all adjustments on format of graph png
        plt.subplots_adjust(left=.10,
                            bottom=.15,
                            right=.93,
                            top=.95,
                            wspace=.20,
                            hspace=0)
        plt.xlabel('Date')
        plt.suptitle(stock + ' Stock Price', color='black')
        plt.setp(ax0.get_xticklabels(), visible=False)
        plt.setp(ax1.get_xticklabels(), visible=False)

        mpld3.save_html(
            fig, 'web2py/applications/blash/static/prices/' + stock + '.html')
        #pickle.dump(ax1, file(stock+'.pickle', 'w'))
        #plt.show() # show the plot
        #mpld3.show()
        #fig.savefig('exampleRSI.png', facecolor=fig.get_facecolor())

    except Exception, e:
        print 'failed main loop', str(e)
Beispiel #50
0
quotes = _parse_delimited_data(_request())
ochl = np.array(
    pd.DataFrame({
        '0': range(1,
                   np.array(quotes['g1_o']).size + 1),
        '1': np.array(quotes['g1_o']).astype(np.float),
        '2': np.array(quotes['g1_c']).astype(np.float),
        '3': np.array(quotes['g1_h']).astype(np.float),
        '4': np.array(quotes['g1_l']).astype(np.float)
    }))

quotes['g1_c'] = np.array(quotes['g1_c']).astype(np.float)
analysis = pd.DataFrame(index=quotes['date'])
analysis['sma_f'] = ta.SMA(quotes['g1_c'], SMA_FAST)
print analysis['sma_f']
analysis['sma_s'] = ta.SMA(quotes['g1_c'], SMA_SLOW)
print analysis['sma_s']
# Prepare plot
fig, ax = plt.subplots(1, 1, sharex=True)
ax.set_ylabel('SP500', size=20)

# Plot candles
candlestick(ax, ochl, width=0.5, colorup='g', colordown='r', alpha=1)

# Draw Moving Averages
analysis.sma_f.plot(c='g')
analysis.sma_s.plot(c='b')

# Show the picture!
plt.show()
Beispiel #51
0
def animate(i):

    #Colors
    green = "#53C156"
    red = "#ff1717"
    blue = "#3b5998"
    macolor1 = "#e1edf9"
    macolor2 = "#4ee6fd"

    rsicolor = "#1a8762"
    volumecolor = "#12e1b6"
    macdcolor1 = "#4ee6fd"
    macdcolor2 = "#e1edf9"
    yellow = "#EDD415"
    pink = "#E32DC2"
    backgroundcolor = "#07001A"
    bordercolor = "w"
    


    ax1 = plt.subplot2grid((1,9), (0,0) ,colspan=8,  axisbg=backgroundcolor) 
    ax1.clear()
    candlestick(ax1, candleAr[-40:], width=.002, colorup = green, colordown = red)
    ax1.tick_params(axis="x", colors="w")
    ax1.grid(True, color = "w")
    ax1.xaxis_date()
    ax1.yaxis.label.set_color("w")
    ax1.xaxis.label.set_color("w")
    ax1.spines["bottom"].set_color(bordercolor)
    ax1.spines["top"].set_color(bordercolor)
    ax1.spines["left"].set_color(bordercolor)
    ax1.spines["right"].set_color(bordercolor)
    ax1.tick_params(axis="y", colors="w")

    
    ############
    # Moving Average
    ############
    smaTimePeriods = 15
    dateAr = dateFunc()
    sma = simpleMovingAverage(smaTimePeriods)
    

    ax1.plot(dateAr[-40:],sma[-40:], color=macdcolor1,linewidth=1.5)
    
    
    currentBid, currentBidVol, currentAsk, currentAskVol = bid_askTicker()
    lastPrice = candleAr[-1]
    lastPrice= lastPrice[2]
    differenceAsk = currentAsk - lastPrice
    differenceBid = lastPrice - currentBid
    
    bidTxt ="Ask: \n%s" % round(currentAsk,2)
    askTxt ="Bid: \n%s" % round(currentBid,2)
    currentTimeText = "Current time:  \n %s" % time.strftime('%H:%M:%S')
    

    ax2 = plt.subplot2grid((1,9), (0,8), colspan=1, axisbg=backgroundcolor)
    ax2.axis('off')
    ax2.text(0.15,0.9,currentTimeText, color = "w",fontsize=20, )
    ax2.text(0.15,0.7,bidTxt, color = green,fontsize=36, )
    ax2.text(0.15,0.6,round(abs(differenceAsk),3), color = green,fontsize=20,)  
    ax2.text(0.15,0.5,lastPrice, color = "w", fontsize=36) 
    ax2.text(0.15,0.4,round(abs(differenceBid),3), color = red,fontsize=20,) 
    ax2.text(0.15,0.2,askTxt, color = red, fontsize=36,  )
Beispiel #52
0
def graphData(stock,MA1,MA2):
	try:
		try:
			print 'pulling data on',stock
			urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
			stockFile = []
			try:
				sourceCode = urllib2.urlopen(urlToVisit).read()
				splitSource = sourceCode.split('\n')
				for eachLine in splitSource:
					splitLine = eachLine.split(',')
					if len(splitLine)==6:
						if 'values' not in eachLine:
							stockFile.append(eachLine)

			except Exception, e:
				print str(e),'failed to organized pulled data'

		except Exception, e:
			print str(e), 'failed to pull price data'		

		date, closep, highp, lowp, openp, volume = np.loadtxt(stockFile,delimiter=',',unpack=True,converters={ 0: mdates.strpdate2num('%Y%m%d')})

### CANDLESTICK ###
		x = 0
		y = len(date)
		candleAr = []
		while x < y:
			appendLine = date[x],openp[x],closep[x],highp[x],lowp[x],volume[x]
			candleAr.append(appendLine)
			x+=1

		Av1 = movingaverage(closep, MA1)
		Av2 = movingaverage(closep, MA2)

		SP = len(date[MA2-1:])

		label1=str(MA1)+' SMA'
		label2=str(MA2)+' SMA'

		fig = plt.figure(facecolor='#07000d')

		ax1 = plt.subplot2grid((6,4), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
		candlestick(ax1, candleAr[-SP:], width=1, colorup='#53c156', colordown='#ff1717')		

		ax1.plot(date[-SP:],Av1[-SP:],'#e1edf9',label=label1, linewidth=1.5)
		ax1.plot(date[-SP:],Av2[-SP:],'#4ee6fd',label=label2, linewidth=1.5)
		ax1.grid(True, color='w')
		ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
		ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
		plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='both'))
		ax1.yaxis.label.set_color('w')
		ax1.spines['bottom'].set_color('#5998ff')
		ax1.spines['top'].set_color('#5998ff')
		ax1.spines['left'].set_color('#5998ff')
		ax1.spines['right'].set_color('#5998ff')
		ax1.tick_params(axis='y', colors='w')
		plt.ylabel('Stock price')
		
		



### LEGEND ###
		maLeg = plt.legend(loc=9, ncol=2, prop={'size': 7}, fancybox=True, borderaxespad=0.)
		maLeg.get_frame().set_alpha(0.4)
		textEd = pylab.gca().get_legend().get_texts()
		pylab.setp(textEd[0:5], color = 'w')





### RELATIVE STRENGTH INDEX ###
		ax0 = plt.subplot2grid((6,4), (0,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
		rsiCol = '#c1f9f7'
		posCol = '#386d14'
		negCol = '#5f2020'
		midCol = '#bdbdb1'
		rsi = rsiFunc(closep)
		ax0.plot(date[-SP:],rsi[-SP:],rsiCol,linewidth=1.5)
		ax0.axhline(70, color = negCol)
		ax0.axhline(30, color = posCol)
		ax0.axhline(50, color = midCol)
		ax0.fill_between(date[-SP:],rsi[-SP:], 70, where=(rsi[-SP:]>=70), facecolor=negCol, edgecolor=negCol)
		ax0.fill_between(date[-SP:],rsi[-SP:], 30, where=(rsi[-SP:]<=30), facecolor=posCol, edgecolor=posCol)
		ax0.spines['bottom'].set_color('#5998ff')
		ax0.spines['top'].set_color('#5998ff')
		ax0.spines['left'].set_color('#5998ff')
		ax0.spines['right'].set_color('#5998ff')
		ax0.text(0.015, 0.95, 'RSI (14)', va='top', color='w', transform=ax0.transAxes)
		ax0.tick_params(axis='x', colors='w')
		ax0.tick_params(axis='y', colors='w')
		ax0.set_yticks([30,70])
		ax0.yaxis.label.set_color('w')
		#plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='lower'))





### VOLUME ###
		volumeMin = 0

		ax1v = ax1.twinx()
		ax1v.fill_between(date[-SP:],volumeMin, volume[-SP:], facecolor='#00ffe8', alpha=.5)
		ax1v.axes.yaxis.set_ticklabels([])
		ax1v.grid(False)
		ax1v.spines['bottom'].set_color('#5998ff')
		ax1v.spines['top'].set_color('#5998ff')
		ax1v.spines['left'].set_color('#5998ff')
		ax1v.spines['right'].set_color('#5998ff')
		ax1v.set_ylim(0, 2*volume.max())
		ax1v.tick_params(axis='x', colors='w')
		ax1v.tick_params(axis='y', colors='w')	





### MACD ###
		ax2 = plt.subplot2grid((6,4), (5,0), sharex=ax1, rowspan=1, colspan=4, axisbg='#07000d')
		fillcolor = '#00ffe8'
		nslow = 26
		nfast = 12
		nema = 9

		emaslow, emafast, macd = computeMACD(closep)
		ema9 = ExpMovingAverage(macd, nema)

		ax2.plot(date[-SP:], macd[-SP:], color='#e1edf9', lw=2)
		ax2.plot(date[-SP:], ema9[-SP:], color='#4eeffd', lw=1)
		ax2.fill_between(date[-SP:], macd[-SP:] -ema9[-SP:], 0, alpha=0.5, facecolor=fillcolor, edgecolor=fillcolor)
		ax2.text(0.015, 0.95, 'MACD (12, 26, 9)', va='top', color='w', transform=ax2.transAxes)
		ax2.spines['bottom'].set_color('#5998ff')
		ax2.spines['top'].set_color('#5998ff')
		ax2.spines['left'].set_color('#5998ff')
		ax2.spines['right'].set_color('#5998ff')
		ax2.tick_params(axis='x', colors='w')
		ax2.tick_params(axis='y', colors='w')	
		ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))

		for label in ax2.xaxis.get_ticklabels():
			label.set_rotation(45)





###
		plt.suptitle(stock + ' Stock Price', color='w')
		
		plt.setp(ax0.get_xticklabels(), visible=False)
		plt.setp(ax1.get_xticklabels(), visible=False)
		plt.subplots_adjust(left=.09, bottom=.14, right=.94, top=.95, wspace=.20, hspace=.00)
		plt.show()
		fig.savefig(stock + '.png',facecolor=fig.get_facecolor())
Beispiel #53
0
 def _plot(data, ax, **kwds):
     candles = candlestick(ax, data.values, **kwds)
     return candles
Beispiel #54
0
            x += 1

        Av1 = movingaverage(closep, MA1)
        Av2 = movingaverage(closep, MA2)

        SP = len(date[MA2 - 1:])

        fig = plt.figure(facecolor='#07000d')

        ax1 = plt.subplot2grid((6, 4), (1, 0),
                               rowspan=4,
                               colspan=4,
                               axisbg='#07000d')
        candlestick(ax1,
                    newAr[-SP:],
                    width=.6,
                    colorup='#53c156',
                    colordown='#ff1717')

        Label1 = str(MA1) + ' SMA'
        Label2 = str(MA2) + ' SMA'

        ax1.plot(date[-SP:], Av1[-SP:], '#e1edf9', label=Label1, linewidth=1.5)
        ax1.plot(date[-SP:], Av2[-SP:], '#4ee6fd', label=Label2, linewidth=1.5)

        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        ax1.yaxis.label.set_color("w")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
Beispiel #55
0
date1 = ( 2004, 2, 1)
date2 = ( 2004, 4, 12 )


mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
alldays    = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # Eg, Jan 12
dayFormatter = DateFormatter('%d')      # Eg, 12

quotes = quotes_historical_yahoo('INTC', date1, date2)
if len(quotes) == 0:
    raise SystemExit

fig = figure()
fig.subplots_adjust(bottom=0.2)
ax = fig.add_subplot(111)
ax.xaxis.set_major_locator(mondays)
ax.xaxis.set_minor_locator(alldays)
ax.xaxis.set_major_formatter(weekFormatter)
#ax.xaxis.set_minor_formatter(dayFormatter)

#plot_day_summary(ax, quotes, ticksize=3)
candlestick(ax, quotes, width=0.6)

ax.xaxis_date()
ax.autoscale_view()
setp( gca().get_xticklabels(), rotation=45, horizontalalignment='right')

show()

def graphData(stock, MA1, MA2):
    #######################################
    #######################################
    '''
        Use this to dynamically pull a stock:
    '''
    try:
        print('Currently Pulling', stock)

        netIncomeAr = []
        revAr = []
        ROCAr = []

        endLink = 'sort_order=asc&auth_token=a3fpXxHfsiN7AF4gjakQ'
        try:
            print('running urlopen')
            netIncome = urlopen(
                'http://www.quandl.com/api/v1/datasets/OFDP/DMDRN_' +
                stock.upper() + '_NET_INC.csv?&' + endLink).read()
            revenue = urlopen(
                'http://www.quandl.com/api/v1/datasets/OFDP/DMDRN_' +
                stock.upper() + '_REV_LAST.csv?&' + endLink).read()
            ROC = urlopen('http://www.quandl.com/api/v1/datasets/OFDP/DMDRN_' +
                          stock.upper() + '_ROC.csv?&' + endLink).read()
            print('GOT HERE 1')
            splitNI = netIncome.split('\n')
            print('Net Income:')
            for eachNI in splitNI[1:-1]:
                print(eachNI)
                netIncomeAr.append(eachNI)

            print('_________')
            splitRev = revenue.split('\n')
            print('Revenue:')
            for eachRev in splitRev[1:-1]:
                print(eachRev)
                revAr.append(eachRev)

            print('_________')
            splitROC = ROC.split('\n')
            print('Return on Capital:')
            for eachROC in splitROC[1:-1]:
                print(eachROC)
                ROCAr.append(eachROC)

            incomeDate, income = np.loadtxt(
                netIncomeAr,
                delimiter=',',
                unpack=True,
                converters={0: mdates.strpdate2num('%Y-%m-%d')})

            revDate, revenue = np.loadtxt(
                revAr,
                delimiter=',',
                unpack=True,
                converters={0: mdates.strpdate2num('%Y-%m-%d')})

            rocDate, ROC = np.loadtxt(
                ROCAr,
                delimiter=',',
                unpack=True,
                converters={0: mdates.strpdate2num('%Y-%m-%d')})

        except Exception:
            print('failed in the quandl grab')
            print(str(Exception))
            time.sleep(555)

        print(
            str(
                datetime.datetime.fromtimestamp(int(
                    time.time())).strftime('%Y-%m-%d %H:%M:%S')))
        #Keep in mind this is close high low open, lol.
        urlToVisit = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=10y/csv'
        stockFile = []
        try:
            sourceCode = urlopen(urlToVisit).read()
            splitSource = sourceCode.split('\n')
            for eachLine in splitSource:
                splitLine = eachLine.split(',')
                if len(splitLine) == 6:
                    if 'values' not in eachLine:
                        stockFile.append(eachLine)
        except Exception:
            print(str(e), 'failed to organize pulled data.')
    except Exception:
        print(str(Exception), 'failed to pull pricing data')
    #######################################
    #######################################
    try:
        date, closep, highp, lowp, openp, volume = np.loadtxt(
            stockFile,
            delimiter=',',
            unpack=True,
            converters={0: mdates.strpdate2num('%Y%m%d')})
        x = 0
        y = len(date)
        newAr = []
        while x < y:
            appendLine = date[x], openp[x], closep[x], highp[x], lowp[
                x], volume[x]
            newAr.append(appendLine)
            x += 1

        Av1 = movingaverage(closep, MA1)
        Av2 = movingaverage(closep, MA2)

        SP = len(date[MA2 - 1:])

        fig = plt.figure(facecolor='#07000d')

        ax1 = plt.subplot2grid((9, 4), (1, 0),
                               rowspan=4,
                               colspan=4,
                               axisbg='#07000d')
        candlestick(ax1,
                    newAr[-SP:],
                    width=.6,
                    colorup='#53c156',
                    colordown='#ff1717')

        Label1 = str(MA1) + ' SMA'
        Label2 = str(MA2) + ' SMA'

        ax1.plot(date[-SP:], Av1[-SP:], '#e1edf9', label=Label1, linewidth=1.5)
        ax1.plot(date[-SP:], Av2[-SP:], '#4ee6fd', label=Label2, linewidth=1.5)

        ax1.grid(True, color='w')
        ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
        ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
        ax1.yaxis.label.set_color("w")
        ax1.spines['bottom'].set_color("#5998ff")
        ax1.spines['top'].set_color("#5998ff")
        ax1.spines['left'].set_color("#5998ff")
        ax1.spines['right'].set_color("#5998ff")
        ax1.tick_params(axis='y', colors='w')
        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax1.tick_params(axis='x', colors='w')
        plt.ylabel('Stock price and Volume')

        maLeg = plt.legend(loc=9,
                           ncol=2,
                           prop={'size': 7},
                           fancybox=True,
                           borderaxespad=0.)
        maLeg.get_frame().set_alpha(0.4)
        textEd = pylab.gca().get_legend().get_texts()
        pylab.setp(textEd[0:5], color='w')

        volumeMin = 0

        ax0 = plt.subplot2grid((9, 4), (0, 0),
                               sharex=ax1,
                               rowspan=1,
                               colspan=4,
                               axisbg='#07000d')
        rsi = rsiFunc(closep)
        rsiCol = '#c1f9f7'
        posCol = '#386d13'
        negCol = '#8f2020'

        ax0.plot(date[-SP:], rsi[-SP:], rsiCol, linewidth=1.5)
        ax0.axhline(70, color=negCol)
        ax0.axhline(30, color=posCol)
        ax0.fill_between(date[-SP:],
                         rsi[-SP:],
                         70,
                         where=(rsi[-SP:] >= 70),
                         facecolor=negCol,
                         edgecolor=negCol,
                         alpha=0.5)
        ax0.fill_between(date[-SP:],
                         rsi[-SP:],
                         30,
                         where=(rsi[-SP:] <= 30),
                         facecolor=posCol,
                         edgecolor=posCol,
                         alpha=0.5)
        ax0.set_yticks([30, 70])
        ax0.yaxis.label.set_color("w")
        ax0.spines['bottom'].set_color("#5998ff")
        ax0.spines['top'].set_color("#5998ff")
        ax0.spines['left'].set_color("#5998ff")
        ax0.spines['right'].set_color("#5998ff")
        ax0.tick_params(axis='y', colors='w')
        ax0.tick_params(axis='x', colors='w')
        plt.ylabel('RSI')

        ax1v = ax1.twinx()
        ax1v.fill_between(date[-SP:],
                          volumeMin,
                          volume[-SP:],
                          facecolor='#00ffe8',
                          alpha=.4)
        ax1v.axes.yaxis.set_ticklabels([])
        ax1v.grid(False)
        ###Edit this to 3, so it's a bit larger
        ax1v.set_ylim(0, 3 * volume.max())
        ax1v.spines['bottom'].set_color("#5998ff")
        ax1v.spines['top'].set_color("#5998ff")
        ax1v.spines['left'].set_color("#5998ff")
        ax1v.spines['right'].set_color("#5998ff")
        ax1v.tick_params(axis='x', colors='w')
        ax1v.tick_params(axis='y', colors='w')
        ax2 = plt.subplot2grid((9, 4), (5, 0),
                               sharex=ax1,
                               rowspan=1,
                               colspan=4,
                               axisbg='#07000d')
        fillcolor = '#00ffe8'
        nslow = 26
        nfast = 12
        nema = 9
        emaslow, emafast, macd = computeMACD(closep)
        ema9 = ExpMovingAverage(macd, nema)
        ax2.plot(date[-SP:], macd[-SP:], color='#4ee6fd', lw=2)
        ax2.plot(date[-SP:], ema9[-SP:], color='#e1edf9', lw=1)
        ax2.fill_between(date[-SP:],
                         macd[-SP:] - ema9[-SP:],
                         0,
                         alpha=0.5,
                         facecolor=fillcolor,
                         edgecolor=fillcolor)

        plt.gca().yaxis.set_major_locator(mticker.MaxNLocator(prune='upper'))
        ax2.spines['bottom'].set_color("#5998ff")
        ax2.spines['top'].set_color("#5998ff")
        ax2.spines['left'].set_color("#5998ff")
        ax2.spines['right'].set_color("#5998ff")
        ax2.tick_params(axis='x', colors='w')
        ax2.tick_params(axis='y', colors='w')
        plt.ylabel('MACD', color='w')
        ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5,
                                                        prune='upper'))

        ######################################
        ######################################
        ax3 = plt.subplot2grid((9, 4), (6, 0),
                               sharex=ax1,
                               rowspan=1,
                               colspan=4,
                               axisbg='#07000d')
        ax3.plot(incomeDate, income, '#4ee6fd')
        ax3.spines['bottom'].set_color("#5998ff")
        ax3.spines['top'].set_color("#5998ff")
        ax3.spines['left'].set_color("#5998ff")
        ax3.spines['right'].set_color("#5998ff")
        ax3.tick_params(axis='x', colors='w')
        ax3.tick_params(axis='y', colors='w')
        ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4,
                                                        prune='upper'))
        plt.ylabel('NI', color='w')

        ax4 = plt.subplot2grid((9, 4), (7, 0),
                               sharex=ax1,
                               rowspan=1,
                               colspan=4,
                               axisbg='#07000d')
        ax4.plot(revDate, revenue, '#4ee6fd')
        ax4.spines['bottom'].set_color("#5998ff")
        ax4.spines['top'].set_color("#5998ff")
        ax4.spines['left'].set_color("#5998ff")
        ax4.spines['right'].set_color("#5998ff")
        ax4.tick_params(axis='x', colors='w')
        ax4.tick_params(axis='y', colors='w')
        ax4.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4,
                                                        prune='upper'))
        plt.ylabel('Rev', color='w')

        ax5 = plt.subplot2grid((9, 4), (8, 0),
                               rowspan=1,
                               sharex=ax1,
                               colspan=4,
                               axisbg='#07000d')
        ax5.plot(rocDate, ROC, '#4ee6fd')
        ax5.spines['bottom'].set_color("#5998ff")
        ax5.spines['top'].set_color("#5998ff")
        ax5.spines['left'].set_color("#5998ff")
        ax5.spines['right'].set_color("#5998ff")
        ax5.tick_params(axis='x', colors='w')
        ax5.tick_params(axis='y', colors='w')
        ax5.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4,
                                                        prune='upper'))
        plt.ylabel('ROC', color='w')

        for label in ax5.xaxis.get_ticklabels():
            label.set_rotation(45)

        plt.suptitle(stock, color='w')

        plt.setp(ax0.get_xticklabels(), visible=False)
        ### add this ####
        plt.setp(ax1.get_xticklabels(), visible=False)
        plt.setp(ax2.get_xticklabels(), visible=False)
        plt.setp(ax3.get_xticklabels(), visible=False)
        plt.setp(ax4.get_xticklabels(), visible=False)

        plt.subplots_adjust(left=.09,
                            bottom=.14,
                            right=.94,
                            top=.95,
                            wspace=.20,
                            hspace=0)
        plt.show()
        fig.savefig('example.png', facecolor=fig.get_facecolor())

    except Exception:
        print('main loop', str(Exception))
Beispiel #57
0
# Tick locator and formatter
mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
alldays = DayLocator()              # minor ticks on the days
weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
dayFormatter = DateFormatter('%Y-%m-%d')      # e.g., 12
#dayFormatter = DateFormatter('%b %d %Y')

# Plot
fig = plt.figure(facecolor='#07000d')
ax1 = plt.subplot2grid((4,4), (0,0), rowspan=3, colspan=4, axisbg='#07000d')
ax1.grid(True, color='w')
#fig.autofmt_xdate()
ax1.plot(ind, uband, '#2E2EFE', label='Bollinger Band')
ax1.plot(ind, lband, '#2E2EFE')
ax1.plot(ind, mavg, '#FE9A2E', label='SMA')
candlestick(ax1, dataAr, width=0.8, colorup='#9eff15', colordown='#ff1717')
# Convert back to date
ax1.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
# Axis and tick setting
ax1.yaxis.label.set_color('w')
ax1.yaxis.set_major_formatter(ticker.FormatStrFormatter('%.2f'))
ax1.spines['bottom'].set_color("#5998ff")
ax1.spines['top'].set_color("#5998ff")
ax1.spines['left'].set_color("#5998ff")
ax1.spines['right'].set_color("#5998ff")
ax1.tick_params(axis='y', colors='w')
# Legend
leg1 = ax1.legend(loc=2, prop={'size':8})
for text in leg1.get_texts():
    text.set_color('w')
frame1 = leg1.get_frame()