Exemple #1
0
    def plotK(self,df,title='',fmt='%Y-%m-%d'):
        plt.rcParams['font.sans-serif'] = ['SimHei']
        plt.rcParams['axes.unicode_minus'] = False

        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

        dataArray= [[date2num(rev.date),rev['open'],rev['high'],rev['low'], rev['close']] for index, rev in df[:50].iterrows()]
        print(dataArray)
        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_ohlc(ax, dataArray, width=0.6)

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

        plt.title(title)
        plt.show()
def candlestickGraph(start, end, stock):
    mondays = WeekdayLocator(MONDAY)
    alldays = DayLocator()
    weekFormatter = DateFormatter('%b %y')  # e.g., Jan 12016
    dayFormatter = DateFormatter('%d')

    quotes = quotes_historical_yahoo_ohlc(stock, start, end)

    if len(quotes) == 0:
        raise SystemExit
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.1)
    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_ohlc(ax, quotes, width=.6, colorup='#77d879', colordown='#db3f3f', alpha=0.65)

    ax.xaxis.set_major_locator(mticker.MaxNLocator(10))


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

    ax.xaxis_date()

    plt.setp(plt.gca().get_xticklabels(), rotation=45)

    plt.show()
Exemple #3
0
def draw2(data):    
    chart_width = 0.5
    fig = plt.figure()
    
    gs1 = GridSpec(4, 1)
    ax1 = plt.subplot(gs1[:-1, :])
    ax2 = plt.subplot(gs1[-1, :])
    
    locator = MonthLocator(bymonth=range(1, 13, 3))
    formatter = DateFormatter('%Y-%m')
    ax1.xaxis.set_major_locator(locator)
    #ax1.xaxis.set_major_formatter(NullFormatter())
    
    ax1.set_yscale('log')
    ax1.yaxis.set_major_locator(SymmetricalLogLocator(base=1.2, linthresh=1))
    ax1.yaxis.set_minor_locator(NullLocator())
    ax1.yaxis.set_major_formatter(ScalarFormatter())
    ax1.set_ylabel('Price')
    ax1.grid(True)
    
    quote = dataframe2quote(data)
    candlestick_ohlc(ax1, quote, width=chart_width, colorup='#ff1717', colordown='#53c156')

    
    plt.bar(data.index, data['turnoverValue'], width = 20)
    ax2.set_ylabel('Volume')
    ax2.xaxis.set_major_locator(locator)
    ax2.xaxis.set_major_formatter(formatter)
    ax2.yaxis.set_major_formatter(ScalarFormatter())
    ax2.grid(True)
    
    plt.setp(plt.gca().get_xticklabels(), rotation=90, horizontalalignment='right')
    fig.suptitle(data.iloc[0]['id'], fontsize=12)
def spyBenchPlot(m1, d1, y1, m2, d2, y2):
    """
    plot the s%p 500 index(ticker: spy) candlestick chart
    :param m1: staring month
    :param d1: starting day
    :param y1: starting year
    :param m2: ending month
    :param d2: ending day
    :param y2: ending year
    :return:
    """
    date1 = (y1, m1, d1)
    date2 = (y2, m2, d2)
    mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
    alldays = DayLocator()  # minor ticks on the days
    weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12

    quotes = quotes_historical_yahoo_ohlc('spy', 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)
    candlestick_ohlc(ax, quotes, width=0.6)
    ax.xaxis_date()
    ax.autoscale_view()
    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    plt.title('S&P 500 ETF')
    plt.show()
def show_candlestick(ticker, startD, endD):
    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_ohlc(ticker, startD, endD)
    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_ohlc(ax, quotes, width=0.6)

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

    plt.show()
Exemple #6
0
def ohlc(g):
    date = []
    op = []
    hi = []
    lo = []
    cl = []
    for e in list(g)[1:]:
        lstmp = e.split(',')
        # DATE
        strl = lstmp[0]
        date.append(datetime.datetime.strptime(strl, '%d/%m/%y'))
        # OPEN
        strl = lstmp[2]
        op.append(float(strl))
        # HIGH
        strl = lstmp[3]
        hi.append(float(strl))
        # LOW
        strl = lstmp[4]
        lo.append(float(strl))
        # CLOSE
        strl = lstmp[5]
        cl.append(float(strl))

    ax = plt.subplot()
    quotes = []
    for e in zip(date2num(date), op, hi, lo, cl):
        quotes.append(e)
    candlestick_ohlc(ax, quotes, colorup='blue', colordown='black', width=0.9)
    for label in ax.xaxis.get_ticklabels():
        label.set_rotation(45)

    ax.xaxis.set_major_formatter(mdates.DateFormatter('%d-%m-%y'))
    ax.grid(True, linewidth=0.3)
    plt.show()
Exemple #7
0
def plot_K(tuples, name):
    mondays = mdates.WeekdayLocator(mdates.MONDAY)  # 主要刻度
    alldays = mdates.DayLocator()  # 次要刻度
    # weekFormatter = DateFormatter(‘%b %d‘)     # 如:Jan 12
    mondayFormatter = mdates.DateFormatter("%m-%d-%Y")  # 如:2-29-2015
    dayFormatter = mdates.DateFormatter("%d")  # 如:12

    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_locator(mdates.DayLocator(bymonthday=range(1, 32), interval=30))
    ax.xaxis.set_minor_locator(mondays)

    ax.xaxis.set_major_formatter(mondayFormatter)
    # ax.xaxis.set_minor_formatter(dayFormatter)

    # plot_day_summary(ax, quotes, ticksize=3)
    mfinance.candlestick_ohlc(ax, tuples, width=0.6, colorup="r", colordown="g")

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

    ax.grid(True)
    plt.title(name)
    plt.show()
Exemple #8
0
def plot_stock(data):
    symbol = data["Symbol"][0]
    data['Date'] = data.index
    data['Date2'] = data['Date'].apply(lambda d: mdates.date2num(d.to_pydatetime()))
    tuples = [tuple(x) for x in data[['Date2', 'Open', 'High', 'Low', 'Adj_Close']].values]
    fig, ax = plt.subplots()
    ax.grid(True)
    ax.xaxis_date()
    ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d"))
    plt.xticks(rotation=45)
    plt.xlabel("Date")
    plt.ylabel("Price")
    plt.title("data for stock: " + symbol)
    candlestick_ohlc(ax, tuples, width=.6, colorup='g', alpha=.4)
    ax.plot(data["Date2"], data["ema_17"])
    ax.plot(data["Date2"], data["ema_43"])
    ax2 = ax.twinx()
    ax2.set_ylabel('Volume', color='r')
    ax2.set_ylim(ymax=data["Volume"].max()*5)
    ax2.bar(data["Date2"], data["Volume"])
    xmax = data.Date2.max() + 21
    xmin = data.Date2.min() - 21
    ax2.set_xlim([xmin, xmax])
    plt.close()
    return fig
 def plot_finance(self):
 # (Year, month, day) tuples suffice as args for quotes_historical_yahoo
     date1 = (2014, 1, 1)
     date2 = (2014, 1, 2) 
 
 
     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_ohlc('INTC', date1, date2)
     quotes = self.get_stock('3057', 12)
     if len(quotes) == 0:
         raise SystemExit
     print quotes
 
     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_ohlc(ax, quotes, width=0.6)
 
     ax.xaxis_date()
     ax.autoscale_view()
     plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
 
     plt.show()
Exemple #10
0
    def plot(self, file_name):
        figure, axes = mplot.subplots(nrows=2, ncols=1)
        figure.subplots_adjust(bottom=0.2)

        #candle stick
        k_ax = axes[0]
        k_ax.set_xticks(range(0, len(self.__datas), self.__xstep))
        k_ax.set_xticklabels([self.__datas[index]['date'] for index in k_ax.get_xticks()])
        mfinance.candlestick_ohlc(k_ax, self.__convert_k_datas(), width=0.6, colorup='r', colordown='g') 
        k_ax.xaxis_date()
        k_ax.autoscale_view()
        mplot.setp(mplot.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

        k_ax.grid(True)
        #mplot.title(self.__stock_code)

        #asset curve
        asset_ax = axes[1]
        asset_ax.set_xticks(range(0, len(self.__datas), self.__xstep))
        asset_ax.set_xticklabels([self.__datas[index]['date'] for index in asset_ax.get_xticks()])

        ind = np.arange(len(self.__datas))
        share_ax = asset_ax.twinx()
        asset_ax.plot(ind, self.__get_asset_datas(), '-', color='blue', label='asset')
        asset_ax.set_ylabel('total asset')

        share_ax.plot(ind, self.__get_shares_datas(), '-', color='magenta', label='shares')
        share_ax.set_ylabel('total share')
        asset_ax.xaxis_date()
        asset_ax.autoscale_view()
        mplot.setp(mplot.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
        asset_ax.grid(True)

        mplot.savefig(file_name)
def plotKBarsFromPrices(prices, pvList):
    dataList = []
    i = 1
    for price in prices:
        bar = (i, price[3], price[0], price[1], price[2])
        dataList.append(bar)
        i += 1

    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)    
    #ax.xaxis_date()
    ax.autoscale_view()    
    plt.xticks(rotation=45)
    plt.yticks()
    plt.title("K bars")
    plt.xlabel("seq")
    plt.ylabel("price point")
    mpf.candlestick_ohlc(ax,dataList,width=0.5,colorup='r',colordown='green')

    if pvList is not None:
        x = range(1, len(pvList) + 1)        
        plt.plot(x, pvList)

    plt.grid()
    plt.show()
Exemple #12
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)        
Exemple #13
0
 def drawCandle(self,ax,quotes, width=0.6,colorup='b', colordown='r',alpha=0.5,bDrawText = False): 
     '''
     ax.xaxis.set_major_locator(mpd.WeekdayLocator(mpd.MONDAY))  # major ticks on the mondays
     ax.xaxis.set_major_formatter(mpd.DateFormatter('%Y%m%d'))  
     
     ax.xaxis.set_major_locator(mpd.MonthLocator())  # major ticks on the mondays
     ax.xaxis.set_major_formatter(mpd.DateFormatter('%Y%m'))     
     
     
     ax.xaxis.set_minor_locator(mpd.DayLocator() )               # minor ticks on the days
     ax.xaxis.set_minor_formatter(mpd.DateFormatter('%d') )
     
     ax.xaxis.set_minor_locator(mpd.WeekdayLocator(mpd.MONDAY))               # minor ticks on the days
     ax.xaxis.set_minor_formatter(mpd.DateFormatter('%d') )     
     '''
     mpf.candlestick_ohlc(ax, quotes, width,colorup, colordown,alpha)
     ax.grid(True)
     ax.xaxis_date()
     ax.autoscale_view()
     if(bDrawText):
         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)    
Exemple #14
0
def drawCandleStick(curStock,dateStrInput,interval=10):
    mpl.rcParams['font.sans-serif'] = ['SimHei'] 

    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays
    alldays    = DayLocator()              # minor ticks on the days
    weekFormatter = DateFormatter('%Y-%m-%d')  # e.g., Jan 12
    dayFormatter = DateFormatter('%d')      # e.g., 12

    #starting from dates expressed as strings...
    #...you convert them in float numbers....
    indexDate=Ccomfunc.getIndexByStrDate(curStock,dateStrInput)
    Prices=[]
    for i in range(indexDate-interval,indexDate+interval):
        mplDate = date2num(datetime.strptime(curStock.dayStrList[i], "%Y/%m/%d"))
    #so redefining the Prices list of tuples... date open high lowest close
        openPrice=curStock.dayPriceOpenFList[i]
        highestPrice=curStock.dayPriceHighestFList[i]
        lowestPrice=curStock.dayPriceLowestFList[i]
        closePrice=curStock.dayPriceClosedFList[i]
        tradeVolume=curStock.dayTradeVolumeFList[i]
        Prices.append([mplDate,openPrice,highestPrice, lowestPrice, closePrice,tradeVolume])
    
    PricesArray=np.array(Prices)
    #and then following the official example. 
    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_ohlc(ax, PricesArray, width=0.5,colorup='r', colordown='g')

    ax.yaxis.grid(True)
    ## add notation
    Xmark=matplotlib.dates.date2num(datetime.strptime(curStock.dayStrList[indexDate], "%Y/%m/%d"))
    Ymark=curStock.dayPriceClosedFList[indexDate]*0.5+curStock.dayPriceOpenFList[indexDate]*0.5
    ax.annotate("$", (Xmark,Ymark), xytext=(-2, 0), textcoords='offset points' )

    ax.xaxis_date()
    ax.autoscale_view()

    axVol = ax.twinx()
##
    dates = PricesArray[:,0]
    dates = np.asarray(dates)
    volume = PricesArray[:,5]
    volume = np.asarray(volume)

    # make bar plots and color differently depending on up/down for the day
    pos = PricesArray[:,1]-PricesArray[:,4]<0
    neg = PricesArray[:,1]-PricesArray[:,4]>0
    axVol.bar(dates[pos],volume[pos],color='red',width=0.5,align='center')
    axVol.bar(dates[neg],volume[neg],color='green',width=0.5,align='center')
    axVol.set_position(matplotlib.transforms.Bbox([[0.125,0.05],[0.9,0.2]]))

    plt.setp( plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
    plt.title(u"{} {} 20日K".format(curStock.stockID,dateStrInput),color='r')


    plt.show()
def plot_stock_date(symbol, start_date, end_date, tweet_volume):
	# Get the quote data from the symbol and unpack it
	quotes = pltf.quotes_historical_yahoo_ohlc(symbol, start_date, end_date)
	ds, open, highs, lows,close,  volumes = zip(*quotes)
	# Scale the labels with the amount of quotes
	if len(quotes) < 31:
		locator = DayLocator()
		weekFormatter = DateFormatter('%b %d')
	elif len(quotes) >=31 and len(quotes) < 500:
		locator = MonthLocator()
		weekFormatter = DateFormatter('%y %b')
	elif len(quotes) >= 500 and len(quotes) < 600:
		locator = MonthLocator()
		weekFormatter = DateFormatter('%b')
	else:
		locator = YearLocator()
		weekFormatter = DateFormatter('%y')
	alldays = WeekdayLocator()
	# Create the figure, axis, and locators
	fig = plt.figure(1)
	ax = plt.subplot(311)
	ax2 = plt.subplot(312)
	ax3 = plt.subplot(313)
	fig.subplots_adjust(bottom=0.2)
	ax.xaxis.set_major_locator(locator)
	ax.xaxis.set_minor_locator(alldays)
	ax.xaxis.set_major_formatter(weekFormatter)
	# Plot candlestick
	pltf.candlestick_ohlc(ax, quotes, width=0.6, colorup='g')
	# Set date and autoscale
	ax.xaxis_date()
	ax.autoscale_view()
	plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
	ax2.xaxis_date()
	ax2.autoscale_view()
	ax3.xaxis_date()
	ax3.autoscale_view()
	# Extract the volume and calculate the color for each bar
	vol = [v for v in volumes]
	vol = np.asarray(vol)
	dates = [d for d in ds]
	op = [o for o in open]
	cl = [c for c in close]
	cols = []
	for x in range(0, len(op)):
		if op[x] - cl[x] < 0:
			cols.append('g')
		else:
			cols.append('r')
	# Plot volume as red and green bars
	ax2.bar(dates, vol, width=1.0,align='center', color=cols)
	# Plot tweet volume
	tweet_volume = np.asarray(tweet_volume)
	dates = []
	for x in range(0, len(tweet_volume)):
		dates.append(ds[0] + x)
	ax3.bar(dates, tweet_volume, width=1.0, align='center')
	# Show figure
	plt.show()
def graph_data(stock):

	fig = plt.figure()
	#ax1 = plt.subplot2grid((1,1), (0,0))
	ax1 = plt.subplot2grid((6,1), (0,0),rowspan=1,colspan=1)
	plt.title(stock)
	ax2 = plt.subplot2grid((6,1), (1,0),rowspan=4,colspan=1)
	plt.xlabel('Date')
	plt.ylabel('Price')
	ax3 = plt.subplot2grid((6,1), (5,0),rowspan=1,colspan=1)

	stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
	source_code = urllib.request.urlopen(stock_price_url).read().decode()
	stock_data = []
	split_source = source_code.split('\n')
	for line in split_source:
		split_line = line.split(',')
		if len(split_line) == 6:
			if 'values' not in line and 'labels' not in line:
				stock_data.append(line)


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

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

	while x < y:
		append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
		ohlc.append(append_me)
		x+=1
	
	ma1 = moving_average(closep,MA1)
	ma2 = moving_average(closep,MA2)
	start = len(date[MA2-1:])
		
	h_l = list(map(high_minus_low,highp,lowp))
	ax1.plot_date(date,h_l,'-')

	candlestick_ohlc(ax2, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
	
	for label in ax2.xaxis.get_ticklabels():
		label.set_rotation(45)
	
	ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
	ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
	ax2.grid(True)
	
	bbox_props = dict(boxstyle='round',fc='w',ec='k',lw=1)

	ax2.annotate(str(closep[-1]),(date[-1],closep[-1]),xytext=(date[-1]+4, closep[-1]),bbox=bbox_props)
	print(len(date), len(ma1)) 
	ax3.plot(date[-start:],ma1[-start:])
	ax3.plot(date[-start:],ma2[-start:])
	
	plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
	plt.show()
Exemple #17
0
def _candlestick_ax(df, ax):
    """
    # Alternatively: (but hard to get dates set up properly)
    plt.xticks(range(len(df.index)), df.index, rotation=45)
    fplt.candlestick2_ohlc(ax, df.loc[:, 'Open'].values, df.loc[:, 'High'].values, 
            df.loc[:, 'Low'].values, df.loc[:, 'Close'].values, width=0.2)
    """
    quotes = df.reset_index()
    quotes.loc[:, 'Date'] = mdates.date2num(quotes.loc[:, 'Date'].astype(dt.date))
    fplt.candlestick_ohlc(ax, quotes.values)
 def candlePlot(self,ax,quotes, width=0.6,colorup='r', colordown='g',alpha=0.5): 
     mpf.candlestick_ohlc(ax, quotes, 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)          
Exemple #19
0
    def draw(self, number, length = CANDLE_FIG_LENGTH):

        reader = Reader(number)
        series = [[] for x in xrange(7)]

        # Candle Stick
        candle_sticks = []

        idx = -1
        while True:
            idx +=1 
            row = reader.getInput()
            if row == None: break
            for i in [1, 3, 4, 5, 6]:
                series[i].append(float(row[i]))
                # matplotlib 的 candlestick_ohlc 依序放入 [編號, 收盤, 最高, 最低, 開盤] 會畫出 K 線圖
            candle_sticks.append((
                idx,
                float(row[6]),
                float(row[4]),
                float(row[5]),
                float(row[3])
            ))            
            
        bool_up_series, ma_series, bool_down_series = self._getBooleanBand(series[6])
        
        # Draw Figure
        line_width = CANDLE_FIG_LINE_WIDTH
        
        fig, axarr = plt.subplots(2, sharex=True)

        candlestick_ohlc(axarr[0], candle_sticks[-length:], width=CANDLE_STICK_WIDTH)
        
        x_axis = range(len(series[6]))
        # set zorder 讓 candlestick 可以在上面
        axarr[0].plot(x_axis[-length:], ma_series[-length:], c='#00ff00', ls='-', lw=line_width, zorder=-5)
        axarr[0].plot(x_axis[-length:], bool_up_series[-length:], c='#ff0000', ls='-', lw=line_width, zorder=-4)
        axarr[0].plot(x_axis[-length:], bool_down_series[-length:], c='#0000ff', ls='-', lw=line_width, zorder=-3)
        axarr[0].plot(x_axis[-length:], series[4][-length:], c='#ff3399', ls='-', lw=line_width, zorder=-2)
        axarr[0].plot(x_axis[-length:], series[5][-length:], c='#0099ff', ls='-', lw=line_width, zorder=-1)
        
        axarr[0].set_title(self._getFigTitle(number))
        
        axarr[1].plot(x_axis[-length:], series[1][-length:], c='#000000', ls='-', lw=line_width)
        
        # set figure arguments
        fig.set_size_inches(FIGURE_WIDTH, FIGURE_HEIGHT)

        # output figure
        
        fig.savefig(CANDLE_FIG_PATH+'/'+number+'.png', dpi=FIGURE_DPI)

        plt.clf()
        plt.close('all')
        
def Acct_mkt_candle(dealArr = [],AcctAmtArr=[],BuildPriceArr=[]):
    from matplotlib.finance import candlestick_ohlc
    datenumArr = []
    openp = []
    highp = []
    lowp=[]
    closep=[]
    volume=[]
    font = FontProperties(fname=r"c:\windows\fonts\mingliu.ttc", size=12)
    
    for a in dealArr:
        datenumArr.append(mdates.date2num(a.TradeDate))
        openp.append(a.OpenPrice)
        highp.append(a.HighPrice)
        lowp.append(a.LowPrice)
        closep.append(a.ClosePrice)
        volume.append(a.DealAmt)
        x = 0
        y = len(datenumArr)
        
    newAr = []
    while x < y:
        appendLine = datenumArr[x],openp[x],highp[x],lowp[x],closep[x],volume[x]
        newAr.append(appendLine)
        x+=1
        
        
    fig = plt.figure(facecolor='#07000d')
    ax1 = plt.subplot2grid((3,2), (1,0), rowspan=4, colspan=4, axisbg='#07000d')
    fig.set_size_inches(18.5, 10.5)
    candlestick_ohlc(ax1,newAr[:],width=.6,colorup='#ff1717',colordown='#53c156')
    plt.scatter(datenumArr,BuildPriceArr,s=50,marker='^',color = 'white')
    plt.xticks()
    par1 = ax1.twinx()    
    par1.plot(datenumArr[:],AcctAmtArr[:],color = "red",linewidth=1)    
    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")
    par1.yaxis.label.set_color("w")
    par1.spines['right'].set_color("#5998ff")
    par1.spines['bottom'].set_color("#5998ff")
    par1.spines['top'].set_color("#5998ff")
    par1.spines['left'].set_color("#5998ff")
    ax1.tick_params(axis='y', colors='w')
    par1.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')
    extent = ax1.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
    plt.title(u"Test", fontproperties=font)
    plt.xlabel("Time")
    plt.ylabel("Hits/hour")
    plt.sca(par1)
    plt.savefig(u"test.png", format="png",bbox_inches=extent.expanded(1.1, 1.2))
Exemple #21
0
 def drawCandle(self,ax,quotes, width=0.6,colorup='b', colordown='r',alpha=0.5,bDrawText=False): 
     mpf.candlestick_ohlc(ax, quotes, width,colorup, colordown,alpha)
     ax.grid(True)
     ax.xaxis_date()
     ax.autoscale_view()
     if(bDrawText):
         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)    
Exemple #22
0
 def candle(self, ticker, field='Adj Close'):
     week_formatter = DateFormatter('%b %d')
     mondays = WeekdayLocator(MONDAY)
     data = self.DataReader(ticker)
     z = data.reset_index()
     fig, ax = plt.subplots()
     ax.xaxis.set_major_locator(mondays)
     ax.xaxis.set_major_formatter(week_formatter)
     z['date_num']=z['Date'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
     subset = [tuple(x) for x in z[['date_num', 'Open', 'High', 'Low', 'Close']].values]
     candlestick_ohlc(ax, subset, width=0.6, colorup='g', colordown='r')
Exemple #23
0
    def __draw_chart(self,ohlc_full,lines_full):

        ## ちょうどいい感じの幅にする
        stx=0
        edx=len(ohlc_full)
        for i in range(0,len(lines_full[0])):

            if(not np.isnan(lines_full[0][i])):
                stx=i
                break
        for i in range(len(lines_full[-1])-1,0,-1):
            if(not np.isnan(lines_full[-1][i] )):
                edx=i
                break

        MARGIN=30
        if stx-MARGIN > 0 :
            stx=stx-MARGIN
        if edx+MARGIN < len(ohlc_full):
            edx=edx+MARGIN
        ohlc=ohlc_full[stx:edx]
        for i in range(0,len(ohlc)):
            ohlc[i][0]=i
        lines=[]
        for l in lines_full:
            lines.append(l[stx:edx])


        close=np.asarray(ohlc)[:,4]
        step=int(len(ohlc)/5)
        fdate=np.asarray(range(0,edx-stx))
        ddate=np.asarray(ohlc)[:,6]

        plt.figure(self.figure)
        self.figure=self.figure+1
        # graph上のfloat型の日付と、表示文字列を紐付けている
        plt.xticks(fdate[::step],[x.strftime('%Y-%m-%d') for x in ddate][::step])

        ax = plt.subplot()
        candlestick_ohlc(ax,ohlc)

        # trendline
        for line in lines:
            plt.plot(line)

        plt.xlabel('Date')
        plt.ylabel('Price')
        plt.title("title")
        #ax.legend().set_visible(False)
        plt.legend()
        #plt.show()
        filename=self.stockCode+"_"+str(ohlc[0][6].strftime('%Y-%m-%d'))+".png"
        print(filename)
        plt.savefig("images/"+filename)
def representacionGrafica(accion):

	'''DISTRIBUCION DE LOS GRAFICOS'''
	ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
	ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1)
	ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1)

	'''EXTRACCION DE DATOS'''
	urlAVisitar = 'http://chartapi.finance.yahoo.com/instrument/1.0/' +accion+ '/chartdata;type=quote;range=10y/csv'
	
	codigoFuente = urllib2.urlopen(urlAVisitar).read()

	datosAccion = []
	separarCodigoFuente = codigoFuente.split('\n')

	for linea in separarCodigoFuente:
		separarLineas = linea.split(',')
		if len(separarLineas) == 6:
			if 'values' not in linea and 'labels' not in linea:
				datosAccion.append(linea)


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

	'''VELAS JAPONESAS'''
	x = 0
	y = len(date)
	ohlc = []

	while x < y:
		agregar = date[x],closep[x],highp[x],lowp[x],openp[x],volume[x]
		ohlc.append(agregar)
		x +=1
	candlestick_ohlc(ax2, ohlc, width=0.4, colorup='g', colordown='r')

	'''DISTANCIAS ENTRE MAXIMOS Y MINIMOS'''
	distMinMax = list(map(distanciasMaximosMinimos, highp, lowp))
	ax1.plot_date(date,distMinMax,'-')

	'''VOLUMEN'''
	ax3.fill_between(date,volume, facecolor='#0079a3', alpha=0.4)
	ax3.plot(date,volume)


	'''REPRESENTACION GRAFICA'''

	plt.xlabel('Numeros en X')
	plt.ylabel('Variable importante en Y')
	plt.title('Titulo del grafico\n subtitulo aqui')

	plt.legend()
	plt.show()
def plotKBarsFromChart(chart, row, col):    
    dataList = []    
    for i in range(0, col):
        (last, high, low, open, close) = (0, 0, 0, 0, 0)        
        for j in range(0, row):
            if chart[j][i] == 1:
                if last == 0:
                    high = row - j
                    close = row - j                
                elif last == 2:
                    close = row - j
                    open = row - j
                else:
                    open = row - j
                    low = row - j
            elif chart[j][i] == 2:
                if last == 0:
                    high = row - j
                else:
                    low = row - j
            elif chart[j][i] == -1:
                if last == 0:
                    high = row - j
                    open = row - j
                    low = row - j
                elif last == -2:
                    open = row - j
                    close = row - j                
                else:
                    low = row - j
                    close = row - j
            elif chart[j][i] == -2:
                if last == 0:
                    high = row - j
                else:
                    low = row - j
            last = chart[j][i]
        bar = (i+1, open, high, low, close)
        dataList.append(bar)
    
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)    
    #ax.xaxis_date()
    ax.autoscale_view()    
    plt.xticks(rotation=45)
    plt.yticks()
    plt.title("K bars")
    plt.xlabel("seq")
    plt.ylabel("price point")
    mpf.candlestick_ohlc(ax,dataList,width=0.5,colorup='r',colordown='green')
    plt.grid()
    plt.show()
Exemple #26
0
    def chart(self,stockCode):
        cursor=self.connection.cursor()
        cursor.execute("select date,oprice,high,low,cprice,volume from ST_priceHistAdj where stockCode=%s and date>=%s and date<=%s",[stockCode,self.fromDate,self.toDate])
        result = cursor.fetchall()

        ohlc=[]
        fdate=[]  # float
        ddate=[]  # datetime
        adr=1
        for row in result:
            tmp=adr
            ohlc.append((adr,row[1],row[2],row[3],row[4],row[5]))
            ddate.append(row[0])
            fdate.append(adr)
            adr=adr+1
        cursor.close()
        open=np.asarray(ohlc)[:,1]
        high=np.asarray(ohlc)[:,2]
        low=np.asarray(ohlc)[:,3]
        close=np.asarray(ohlc)[:,4]
        step=int(len(close)/5)
        # graph上のfloat型の日付と、表示文字列を紐付けている
        plt.xticks(fdate[::step],[x.strftime('%Y-%m-%d') for x in ddate][::step])

        ax = plt.subplot()
        candlestick_ohlc(ax,ohlc)

        # 5 日単純移動平均を求める
        #sma5 = ta.SMA(close, timeperiod=5)
        #plt.plot(sma5,label="SMA5")

        # trendline
        line=self.interpolation(100,200,3000,3500,len(close))
        plt.plot(line,label="line")

        # zigzag
        #pivots = peak_valley_pivots(open,high,low,close, 0.1, -0.1)
        pivots = calc_peakbottom(open,high,low,close,10)

        #plt.plot(pivots)
        print(pivots)
        ts_pivots = pd.Series(close)
        ts_pivots = ts_pivots[pivots != 0]
        plt.plot(ts_pivots,label="test")
        print (ts_pivots)

        plt.xlabel('Date')
        plt.ylabel('Price')
        plt.title("title")
        plt.legend()
        plt.show()
def graph_data(stock):

	fig = plt.figure()
	ax1 = plt.subplot2grid((1,1), (0,0))

	stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1m/csv'
	source_code = urllib.request.urlopen(stock_price_url).read().decode()
	stock_data = []
	split_source = source_code.split('\n')
	for line in split_source:
		split_line = line.split(',')
		if len(split_line) == 6:
			if 'values' not in line and 'labels' not in line:
				stock_data.append(line)


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

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

	while x < y:
		append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
		ohlc.append(append_me)
		x+=1
	
	
	candlestick_ohlc(ax1, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
	
	for label in ax1.xaxis.get_ticklabels():
		label.set_rotation(45)
	
	ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
	ax1.xaxis.set_major_locator(mticker.MaxNLocator(10))
	ax1.grid(True)
	bbox_props = dict(boxstyle='larrow',fc='w',ec='k',lw=1)
	ax1.annotate(str(closep[-1]), (date[-1],closep[-1]),xytext = (date[-1]+3,closep[-1]),bbox=bbox_props)
# annotation with arrow	
#	ax1.annotate('Bad News!',(date[11],highp[11]),xytext=(0.8,0.9), textcoords='axes fraction',arrowprops = dict(facecolor='grey',color='grey'))
# font_dict example	
#	font_dict = {'family':'serif','color':'darkred','size':15}
# font dict example
#	ax1.text(date[10],closep[1],'Text example',fontdict=font_dict)
	
	plt.xlabel('Date')
	plt.ylabel('Price')
	plt.title(stock)
	#plt.legend()
	plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
	plt.show()
Exemple #28
0
def plotresu(candlegraf,analysetab):
    #print entrybar
    import matplotlib.pyplot as ml

#   from matplotlib.finance import candlestick
    from matplotlib.finance import candlestick_ohlc
    import matplotlib.pyplot as plt
    
    lafig = plt.figure()
    ax1 = plt.subplot(1,1,1)
    #ax2 = plt.subplot(2,1,2)


    tabplot=[]
    X=[]
    Y=[]


    #print tabplot
    #candlestick open high low close
    candlestick_ohlc(ax1,candlegraf, width=.75, colorup='r', colordown='g')
    #yscale = ax1.get_ybound()  #renvoie le min et max de l'afficahge
    #print yscale

    for i in range(len(analysetab)):
        if analysetab[i][0]==1 :
            indx = analysetab[i][1]
            X.append(candlegraf[indx][0]) #-1 = dennier indice de la liste dateheure : minute
            #on ajoute a y le doublet yscale multiplie par 1 (=lui meme) ou 0 (vide) 
            #c'est pas ce que je voulais faire , je voulais multipler chaque point de y (des 1) par une valeur
            #mais bon ca marche un peu. il va falloir passer tout ca en traiteent listes/matrices sinon c'est moche
            Y.append([candlegraf[indx][1],candlegraf[indx][2],candlegraf[indx][3],candlegraf[indx][4]])  

    print len(X), len(Y)

    ax1.plot(X,Y,'bo')

    X=[]
    Y=[]
    for i in range(len(analysetab)):
        if analysetab[i][0]==-1 :
            indx = analysetab[i][1]    
           # X.append(candlegraf[indx][0][-1])#on ajoute a y le doublet yscale multiplie par 1 (=lui meme) ou 0 (vide) 
            X.append(candlegraf[indx][0])#on ajoute a y le doublet yscale multiplie par 1 (=lui meme) ou 0 (vide) 
            #c'est pas ce que je voulais faire , je voulais multipler chaque point de y (des 1) par une valeur
            #mais bon ca marche un peu. il va falloir passer tout ca en traiteent listes/matrices sinon c'est moche
            Y.append([candlegraf[indx][1],candlegraf[indx][2],candlegraf[indx][3],candlegraf[indx][4]])  

    ax1.plot(X,Y,'yo')

    plt.show()
	def plot_candlestick(self):
		#change datetime objects to date2num for candlestick
		marks = np.arange(0, self.SHAPE + self.STEP_SIZE, step=self.STEP_SIZE)
		marks = [math.floor(x) for x in marks]
		date_marks = []
		for i in marks:
			datetime = list(self.dataframe['Datetime'])[i]
			date_marks.append(datetime.strftime('%m/%d %H:00'))
		self.dataframe['Datetime'] = np.arange(0, self.SHAPE + 1)
		tupled = [tuple(x) for x in self.dataframe.values]
		fig, ax = plt.subplots()
		candlestick_ohlc(ax, tupled, width= .4, colorup='g', alpha=.4)
		ax.set_xlim([0,self.SHAPE +1])
		ax.set_xticklabels(date_marks, rotation = 45)
		print ('Plotting Candlestick')
Exemple #30
0
def chart_dates(symbol, date1 = None, date2 = None, db_name = '../db/kyandoru.db', show = 1):
	""" Creates a candle chart for a given stock and dates
	symbol is the ticker symbol of the stock e.g. "AAON".
	(optional) date1 and date2 must be provided together and
		will restrict the search to after date1 and before date2
		should be in the format YYYY-MM-DD
		or if None is passed for either they will be ignored
	(optional) db_name is the name of the database to get data from
	(optional) show is a boolean that determines whether to display the graph at the end
	returns a matplotlib pyplot object
	"""
	con = None
	con = sql.connect(db_name)
	cur = con.cursor()

	if(date1 == None or date2 == None):
		cur.execute('SELECT * FROM eods WHERE symbol = '+symbol)
	else:
		cur.execute('SELECT * FROM eods WHERE symbol = \"'+symbol+'\" and date > \"'+date1+'\" and date < \"'+date2+'\"')
	
	# fetch the rows selected in our sql statement
	rows = cur.fetchall()

	ohlc = []
	for row in rows:
		date = matplotlib.dates.datestr2num(row[1])
		open = row[2]
		high = row[3]
		low = row[4]
		close = row[5]
		volume = row[6]
		append_me = (date, open, high, low, close, volume) 
		ohlc.append(append_me)
	fig = plt.figure()
	ax1 = plt.subplot2grid((1,1), (0,0))

	candlestick_ohlc(ax1, ohlc)

	plt.xlabel('Date')
	plt.ylabel('Price')
	plt.title('stock')
	plt.legend()
	plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
	
	if(show == 1):
		plt.show()

	return plt
Exemple #31
0
def animate(i):
    global refreshRate
    global DatCounter

    ##################################
    ##################################
    def computeMACD(x, slow=26, fast=12, location="bottom"):
        """
        compute the MACD (Moving Average Convergence/Divergence) using a fast and slow exponential moving avg'
        return value is emaslow, emafast, macd which are len(x) arrays
        """
        values = {'key': 1, 'prices': x}

        url = "http://seaofbtc.com/api/indicator/macd"
        data = urllib.parse.urlencode(values)
        data = data.encode('utf-8')
        req = urllib.request.Request(url, data)
        resp = urllib.request.urlopen(req)
        respData = resp.read()
        newData = str(respData).replace("b", "").replace('[', '').replace(']', '').replace("'", '')

        # print(newData)

        split = newData.split('::')

        macd = split[0]
        ema9 = split[1]
        hist = split[2]

        macd = macd.split(", ")
        ema9 = ema9.split(", ")
        hist = hist.split(", ")

        try:
            macd = [float(i) for i in macd]
        except Exception as e:
            print(str(e) + "  macd")
        try:
            ema9 = [float(i) for i in ema9]
        except Exception as e:
            print(str(e) + "  ema9")
        try:
            hist = [float(i) for i in hist]
        except Exception as e:
            print(str(e) + "  hist")

        print("call!!!")

        if location == "top":
            try:
                a0.plot(OHLC['MPLDates'][fast:], macd[fast:], color=darkColor, lw=2)
                a0.plot(OHLC['MPLDates'][fast:], ema9[fast:], color=lightColor, lw=1)
                a0.fill_between(OHLC['MPLDates'][fast:], hist[fast:], 0, alpha=0.5, facecolor=darkColor,
                                edgecolor=darkColor)
                datLabel = "MACD"
                a0.set_ylabel(datLabel)
            except Exception as e:
                print(str(e))
                topIndicator = "none"


        elif location == "bottom":
            try:
                a3.plot(OHLC['MPLDates'][fast:], macd[fast:], color=darkColor, lw=2)
                a3.plot(OHLC['MPLDates'][fast:], ema9[fast:], color=lightColor, lw=1)
                a3.fill_between(OHLC['MPLDates'][fast:], hist[fast:], 0, alpha=0.5, facecolor=darkColor,
                                edgecolor=darkColor)
                datLabel = "MACD"
                a3.set_ylabel(datLabel)
            except Exception as e:
                print(str(e))
                bottomIndicator = "none"

                ##################################
                ##################################

    def rsiIndicator(priceData, location="top"):

        if location == "top":
            values = {'key': 1, 'prices': priceData, 'periods': topIndicator[1]}

        elif location == "bottom":
            values = {'key': 1, 'prices': priceData, 'periods': bottomIndicator[1]}

        url = "http://seaofbtc.com/api/indicator/rsi"
        data = urllib.parse.urlencode(values)
        data = data.encode('utf-8')
        req = urllib.request.Request(url, data)
        resp = urllib.request.urlopen(req)
        respData = resp.read()
        newData = str(respData).replace("b", "").replace('[', '').replace(']', '').replace("'", '')
        priceList = newData.split(', ')
        rsiData = [float(i) for i in priceList]

        print("call!!!")

        if location == "top":
            a0.plot_date(OHLC['MPLDates'], rsiData, lightColor, label="RSI")
            datLabel = "RSI(" + str(topIndicator[1]) + ")"
            a0.set_ylabel(datLabel)

        elif location == "bottom":
            a3.plot_date(OHLC['MPLDates'], rsiData, lightColor, label="RSI")
            datLabel = "RSI(" + str(bottomIndicator[1]) + ")"
            a3.set_ylabel(datLabel)

    def moving_average(x, n, type='simple'):

        x = np.asarray(x)
        if type == 'simple':
            weights = np.ones(n)
        else:
            weights = np.exp(np.linspace(-1, 0, n))

        weights /= weights.sum()

        a = np.convolve(x, weights, mode='full')[:len(x)]
        return a

    if chartLoad:
        if paneCount == 1:
            if DataPace == "tick":
                try:
                    if exchange == "BTC-e":
                        a = plt.subplot2grid((6, 4), (0, 0), rowspan=5, colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0), rowspan=1, colspan=4, sharex=a)

                        dataLink = 'https://btc-e.com/api/3/trades/btc_usd?limit=2000'
                        data = urllib.request.urlopen(dataLink)
                        data = data.readall().decode('utf-8')
                        data = json.loads(data)
                        data = data["btc_usd"]
                        data = pd.DataFrame(data)

                        data["datestamp"] = np.array(data['timestamp']).astype('datetime64[s]')
                        allDates = data["datestamp"].tolist()

                        buys = data[(data['type'] == 'bid')]
                        buyDates = (buys["datestamp"]).tolist()

                        sells = data[(data['type'] == 'ask')]
                        sellDates = (sells["datestamp"]).tolist()

                        volume = data["amount"]

                        a.clear()

                        a.plot_date(buyDates, buys["price"], lightColor, label="buys")

                        a.plot_date(sellDates, sells["price"], darkColor, label="sells")

                        a2.fill_between(allDates, 0, volume, facecolor='#183A54')

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
                        plt.setp(a.get_xticklabels(), visible=False)

                        a.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                                 ncol=2, borderaxespad=0.)

                        title = 'Last Price: ' + str(data["price"][1999])
                        a.set_title(title)

                    if exchange == 'Bitstamp':
                        a = plt.subplot2grid((6, 4), (0, 0), rowspan=5, colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0), rowspan=1, colspan=4, sharex=a)

                        dataLink = 'https://www.bitstamp.net/api/transactions/'
                        data = urllib.request.urlopen(dataLink)
                        data = data.readall().decode('utf-8')
                        data = json.loads(data)
                        data = pd.DataFrame(data)
                        data["datestamp"] = np.array(data['date'].apply(int)).astype('datetime64[s]')
                        datestamps = data["datestamp"].tolist()
                        volume = data["amount"].apply(float).tolist()

                        a.clear()

                        a.plot_date(datestamps, data["price"], '#183A54')

                        a2.fill_between(datestamps, 0, volume, facecolor='#183A54')

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
                        plt.setp(a.get_xticklabels(), visible=False)

                        title = exchange + ' Tick Data\nLast Price: ' + str(data["price"][0])
                        a.set_title(title)
                        priceData = data["price"].apply(float).tolist()

                    if exchange == 'Bitfinex':
                        a = plt.subplot2grid((6, 4), (0, 0), rowspan=5, colspan=4)
                        a2 = plt.subplot2grid((6, 4), (5, 0), rowspan=1, colspan=4, sharex=a)

                        dataLink = 'https://api.bitfinex.com/v1/trades/btcusd?limit=2000'

                        data = urllib.request.urlopen(dataLink)
                        data = data.readall().decode('utf-8')
                        data = json.loads(data)
                        data = pd.DataFrame(data)

                        volume = data["amount"].apply(float).tolist()

                        data["datestamp"] = np.array(data['timestamp']).astype('datetime64[s]')
                        allDates = data["datestamp"].tolist()

                        buys = data[(data['type'] == 'buy')]
                        buyDates = (buys["datestamp"]).tolist()

                        sells = data[(data['type'] == 'sell')]
                        sellDates = (sells["datestamp"]).tolist()

                        a.clear()

                        a.plot_date(buyDates, buys["price"], lightColor, label="buys")
                        a.plot_date(sellDates, sells["price"], darkColor, label="sells")
                        a2.fill_between(allDates, 0, volume, facecolor='#183A54')

                        a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                        a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))
                        plt.setp(a.get_xticklabels(), visible=False)
                        a.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                                 ncol=2, borderaxespad=0.)

                        title = exchange + ' Tick Data\nLast Price: ' + str(data["price"][0])
                        a.set_title(title)
                        priceData = data["price"].apply(float).tolist()

                    if exchange == 'Huobi':
                        try:
                            a = plt.subplot2grid((6, 4), (0, 0), rowspan=6, colspan=4)

                            data = urllib.request.urlopen(
                                'http://seaofbtc.com/api/basic/price?key=1&tf=1d&exchange=' + programName).read()

                            data = str(data).replace('b', '').replace("'", '')
                            data = json.loads(data)

                            dateStamp = np.array(data[0]).astype('datetime64[s]')
                            dateStamp = dateStamp.tolist()
                            print('here')

                            df = pd.DataFrame({'Datetime': dateStamp})

                            df['Price'] = data[1]

                            df['Volume'] = data[2]
                            df['Symbol'] = "BTCUSD"
                            df['MPLDate'] = df['Datetime'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
                            df = df.set_index('Datetime')
                            lastPrice = df['Price'][-1]

                            a.plot_date(df['MPLDate'][-4500:], df['Price'][-4500:], lightColor, label="price")

                            a.xaxis.set_major_locator(mticker.MaxNLocator(5))
                            a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))

                            title = exchange + ' Tick Data\nLast Price: ' + str(lastPrice)
                            a.set_title(title)
                            priceData = df['Price'].apply(float).tolist()
                        except Exception as e:
                            print(str(e))




                except Exception as e:
                    print("failed", str(e))
                    DatCounter = 9000


                    ##### ALL OTHER, NON-TICK, DATA. ##################################
            else:
                if DatCounter > 12:
                    try:
                        if exchange == 'Huobi':
                            if topIndicator != "none":

                                a = plt.subplot2grid((6, 4), (1, 0), rowspan=5, colspan=4)
                                a0 = plt.subplot2grid((6, 4), (0, 0), sharex=a, rowspan=1, colspan=4)
                            else:
                                a = plt.subplot2grid((6, 4), (0, 0), rowspan=6, colspan=4)

                        else:
                            if topIndicator != "none" and bottomIndicator != "none":
                                # actual price chart.
                                a = plt.subplot2grid((6, 4), (1, 0), rowspan=3, colspan=4)
                                # volume!
                                a2 = plt.subplot2grid((6, 4), (4, 0), sharex=a, rowspan=1, colspan=4)
                                # top indicator
                                a0 = plt.subplot2grid((6, 4), (0, 0), sharex=a, rowspan=1, colspan=4)
                                # bottom indicator
                                a3 = plt.subplot2grid((6, 4), (5, 0), sharex=a, rowspan=1, colspan=4)

                            elif topIndicator != "none":
                                a = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4)
                                a2 = plt.subplot2grid((6, 4), (5, 0), sharex=a, rowspan=1, colspan=4)
                                a0 = plt.subplot2grid((6, 4), (0, 0), sharex=a, rowspan=1, colspan=4)
                            elif bottomIndicator != "none":
                                a = plt.subplot2grid((6, 4), (0, 0), rowspan=4, colspan=4)
                                a2 = plt.subplot2grid((6, 4), (4, 0), sharex=a, rowspan=1, colspan=4)
                                # a0 = plt.subplot2grid((6,4), (0,0), sharex=a, rowspan=1, colspan=4)
                                a3 = plt.subplot2grid((6, 4), (5, 0), sharex=a, rowspan=1, colspan=4)

                            else:
                                a = plt.subplot2grid((6, 4), (0, 0), rowspan=5, colspan=4)
                                a2 = plt.subplot2grid((6, 4), (5, 0), sharex=a, rowspan=1, colspan=4)

                        print('http://seaofbtc.com/api/basic/price?key=1&tf=' + DataPace + '&exchange=' + programName)
                        data = urllib.request.urlopen(
                            'http://seaofbtc.com/api/basic/price?key=1&tf=' + DataPace + '&exchange=' + programName).read()

                        data = str(data).replace('b', '').replace("'", '')
                        data = json.loads(data)

                        dateStamp = np.array(data[0]).astype('datetime64[s]')
                        dateStamp = dateStamp.tolist()

                        df = pd.DataFrame({'Datetime': dateStamp})
                        df['Price'] = data[1]
                        df['Volume'] = data[2]
                        df['Symbol'] = "BTCUSD"
                        df['MPLDate'] = df['Datetime'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
                        df = df.set_index('Datetime')

                        OHLC = df['Price'].resample(resampleSize, how='ohlc')
                        OHLC = OHLC.dropna()

                        volumeData = df['Volume'].resample(resampleSize, how={'volume': 'sum'})

                        OHLC['dateCopy'] = OHLC.index
                        OHLC['MPLDates'] = OHLC['dateCopy'].apply(lambda date: mdates.date2num(date.to_pydatetime()))
                        del OHLC['dateCopy']

                        volumeData['dateCopy'] = volumeData.index
                        volumeData['MPLDates'] = volumeData['dateCopy'].apply(
                            lambda date: mdates.date2num(date.to_pydatetime()))
                        del volumeData['dateCopy']

                        priceData = OHLC['close'].apply(float).tolist()

                        a.clear()
                        if middleIndicator != "none":
                            for eachMA in middleIndicator:
                                ewma = pd.stats.moments.ewma

                                if eachMA[0] == "sma":
                                    sma = pd.rolling_mean(OHLC["close"], eachMA[1])
                                    label = str(eachMA[1]) + " SMA"
                                    a.plot(OHLC['MPLDates'], sma, label=label)
                                if eachMA[0] == "ema":
                                    ewma = pd.stats.moments.ewma
                                    label = str(eachMA[1]) + " EMA"
                                    a.plot(OHLC['MPLDates'], ewma(OHLC["close"], eachMA[1]), label=label)

                            a.legend(loc=0)

                        if topIndicator[0] == "rsi":
                            rsiIndicator(priceData, "top")
                        elif topIndicator == "macd":
                            try:
                                computeMACD(priceData, location="top")
                            except:
                                print("failed macd")

                        if bottomIndicator[0] == "rsi":
                            rsiIndicator(priceData, "bottom")
                        elif bottomIndicator == "macd":
                            try:
                                computeMACD(priceData, location="bottom")
                            except:
                                print("failed macd")

                        csticks = candlestick_ohlc(a, OHLC[['MPLDates', 'open', 'high', 'low', 'close']].values,
                                                   width=candleWidth, colorup=lightColor, colordown=darkColor)
                        a.set_ylabel("price")
                        if exchange != 'Huobi':
                            a2.fill_between(volumeData['MPLDates'], 0, volumeData['volume'],
                                            facecolor='#183A54')  # , alpha=.4)
                            a2.set_ylabel("volume")

                        a.xaxis.set_major_locator(mticker.MaxNLocator(3))
                        a.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H:%M'))

                        plt.setp(a.get_xticklabels(), visible=False)

                        if topIndicator != "none":
                            plt.setp(a0.get_xticklabels(), visible=False)

                        if bottomIndicator != "none":
                            plt.setp(a2.get_xticklabels(), visible=False)

                        x = (len(OHLC['close'])) - 1

                        if DataPace == '1d':
                            title = exchange + ' 1 Day Data with ' + resampleSize + ' Bars\nLast Price: ' + str(
                                OHLC['close'][x])
                        if DataPace == '3d':
                            title = exchange + ' 3 Day Data with ' + resampleSize + ' Bars\nLast Price: ' + str(
                                OHLC['close'][x])
                        if DataPace == '7d':
                            title = exchange + ' 7 Day Data with ' + resampleSize + ' Bars\nLast Price: ' + str(
                                OHLC['close'][x])

                        if topIndicator != "none":
                            a0.set_title(title)
                        else:
                            a.set_title(title)
                        print('NewGraph!')

                        DatCounter = 0









                    except Exception as e:
                        print(str(e), "main animate non tick")
                        DatCounter = 9000

                else:
                    DatCounter += 1
Exemple #32
0
will make a new data frame .resample() is the call with interval as arg .mean() is average .rolling()
will make a moving average
"""

df_ohlc = df['Adj Close'].resample('10D').ohlc()
df_volume = df['Volume'].resample('10D').sum()

df_ohlc.reset_index(
    inplace=True)  # allows for the date col to be an actual col

df_ohlc['Date'] = df_ohlc['Date'].map(
    mdates.date2num)  # changes the date to a number in matplotlib

ax1 = mp.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)
ax2 = mp.subplot2grid((6, 1), (5, 0), rowspan=5, colspan=1, sharex=ax1)
ax1.xaxis_date()  # takes the mdates2num and makes them as dates in graph

candlestick_ohlc(ax1, df_ohlc.values, width=3,
                 colorup='g')  # takes axis, data, and width for thickness,
# colorup=color,
ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values,
                 0)  # fill from x where x is m dates to y
# where is values so 0 to y

# ax1.plot(df.index, df['Adj Close'], 'tab:blue')
ax1.plot(df.index, df['100ma'], 'tab:cyan')
# ax2.plot(df.index, df['Volume'], 'tab:cyan')

mp.show()
# print(df.tail(10))
Exemple #33
0
def mlrun():
    yesterday = date.today() - timedelta(1)
    #################################################################################
    # TODO - Download images locally
    yesterday = datetime.datetime.now() - timedelta(days=60)
    bull = False
    bear = False
    tightening = False
    inconclusive = True
    states = " "

    def get_change(a, b):
        # print(abs(100 * (b - a) / a))
        return abs(100 * (b - a) / a)

    def check_init_low(coinid, x, set, states, currentHigh, currentLow):
        print(
            str("check_init_low " + str(currentLow) + " = low, " +
                str(currentHigh) + "= high"))
        close = []
        lows = []
        highs = []
        srlines = []

        while x > 0:
            close.append(set['Close'][x])
            lows.append(set['Low'][x])
            highs.append(set['High'][x])
            x -= 1

        print(close)
        print(highs)
        print(lows)
        dupes = close

        for s in close:
            for i in dupes:
                if get_change(s, i) < 5.0:
                    srlines.append(i)

        dupes = highs
        for s in highs:
            for i in dupes:
                if get_change(s, i) < 5.0:
                    srlines.append(i)

        dupes = lows
        for s in lows:
            for i in dupes:
                if get_change(s, i) < 5.0:
                    srlines.append(i)

        resi = set['High'][59]
        support = set['Low'][59]
        resis = []
        supports = []
        public_client = bitstamp.client.Public()

        prices = set['Close'][0]
        print(float(prices))
        for s in srlines:
            if s < float(prices):
                # print(" Support = " + str(s))
                supports.append(s)
            if s > float(prices):
                # print(" Resistance = " + str(s))
                resis.append(s)

        resis = sorted(resis)
        supports = sorted(supports)

        resi = resis[0]
        support = supports[0]

        for r in resis:
            if r < resi:
                resi = r
        for s in supports:
            if s > support:
                support = s

        resi2 = resis[1]
        support2 = supports[1]

        print("Resi 1 = " + str(resi))
        print("Resi 2 = " + str(resi2))
        print("Support 1 = " + str(support))
        print("Support 2 = " + str(support2))

        if support < float(prices) < resi:
            states = "tightening"

        if support > float(prices):
            states = "bear"

        if resi < float(prices):
            states = "bull"

        now = datetime.datetime.now()
        dynamodb = boto3.resource('dynamodb')
        dynamoTable = dynamodb.Table('crypto_predictions')

        dynamoTable.put_item(
            Item={
                'coin_id': str(coinid),
                'trend': str(states),
                'resi': Decimal(str(resi)),
                'support': Decimal(str(support)),
                'resi2': Decimal(str(resi2)),
                'support2': Decimal(str(support2))
            })

        return states

    def check_candle(x, set):
        print("in check candle")
        if set['Open'][x] > set['Close'][x]:
            if not is_doji(x, set):
                print("red")
                return 'red'
            else:
                print("doji")
                return 'doji'
        else:
            if not is_doji(x, set):
                print("green")
                return 'green'

    def check_candle(x, set):
        print("in check candle")
        if set['Open'][x] > set['Close'][x]:
            if not is_doji(x, set):
                print("red")
                return 'red'
            else:
                print("doji")
                return 'doji'
        else:
            if not is_doji(x, set):
                print("green")
                return 'green'

    def is_doji(x, set):
        print(" in is doji ")
        middle = abs(set['Open'][x] - set['Close'][x])
        print(" Middle bit = " + str(middle))
        if set['Open'][x] < set['Close'][x]:
            top_spike = set['High'][x] - set['Close'][x]
            bottom_spike = set['Low'][x] - set['Open'][x]
            print(" First case")
            print(" top bit = " + str(top_spike))
            print(" bottom bit = " + str(bottom_spike))
        else:
            top_spike = set['High'][x] - set['Open'][x]
            bottom_spike = set['Close'][x] - set['Low'][x]
            print(" Second case")
            print(" top bit = " + str(top_spike))
            print(" bottom bit = " + str(bottom_spike))

        if top_spike + bottom_spike > middle:
            return True
        else:
            return False

    bitcoin_market_info = pd.read_html(
        "https://coinmarketcap.com/currencies/bitcoin/historical-data/?start="
        + yesterday.strftime('%Y%m%d') + "&end=" + time.strftime("%Y%m%d"),
        flavor='html5lib',
        parse_dates=True,
        index_col=0)[0]
    bitcoin_market_info['Volume'] = bitcoin_market_info['Volume'].astype(
        'int64')
    print(bitcoin_market_info.head())

    bitcoin_market_info['100ma'] = bitcoin_market_info['Close'].rolling(
        window=100, min_periods=0).mean()
    # resampling
    btc_ohlc = bitcoin_market_info['Close'].resample('7D').ohlc()
    btc_df_volume = bitcoin_market_info['Volume'].resample('1D').sum()
    btc_ohlc.reset_index(inplace=True)
    bitcoin_market_info.reset_index(inplace=True)
    btc_ohlc['Date'] = btc_ohlc['Date'].map(dates.date2num)
    bitcoin_market_info['Date'] = bitcoin_market_info['Date'].map(
        dates.date2num)
    ax1 = plt.subplot2grid((6, 1), (0, 0),
                           rowspan=5,
                           colspan=5,
                           facecolor='#00004d')
    ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
    ax1.xaxis_date()
    candlestick_ohlc(ax1, bitcoin_market_info.values, width=0.8, colorup='g')
    ax2.fill_between(btc_df_volume.index.map(dates.date2num),
                     btc_df_volume.values, 0)
    btc_lows = bitcoin_market_info['Low']
    btc_highs = bitcoin_market_info['High']
    current_btc_Low = btc_lows[29]
    currentLow = current_btc_Low
    current_btc_High = btc_highs[29]
    currentHigh = current_btc_High
    print(
        check_init_low('btc', 59, bitcoin_market_info, " ", currentHigh,
                       currentLow))
    print(states)
    global btc_chart
    btc_chart = btc_ohlc.to_json(orient='records', lines=True)
    figBtc = plt.gcf()
    canvasBtc = figBtc.canvas
    bufBtc, sizeBtc = canvasBtc.print_to_buffer()
    imageBtc = Image.frombuffer('RGBA', sizeBtc, bufBtc, 'raw', 'RGBA', 0, 1)
    buffer = io.BytesIO()
    imageBtc.save(buffer, 'PNG')
    graphicBtc = buffer.getvalue()
    graphicBtc = base64.b64encode(graphicBtc)
    buffer.close()
    imgdata = base64.b64decode(graphicBtc)
    filename = 'images/BtcChart.png'
    with open(filename, 'wb') as f:
        f.write(imgdata)
    f.close()

    eth_market_info = pd.read_html(
        "https://coinmarketcap.com/currencies/ethereum/historical-data/?start="
        + yesterday.strftime('%Y%m%d') + "&end=" + time.strftime("%Y%m%d"),
        flavor='html5lib',
        parse_dates=True,
        index_col=0)[0]
    eth_market_info['Volume'] = eth_market_info['Volume'].astype('int64')
    print(eth_market_info.head())

    eth_market_info['100ma'] = eth_market_info['Close'].rolling(
        window=100, min_periods=0).mean()
    # resampling
    eth_ohlc = eth_market_info['Close'].resample('7D').ohlc()
    eth_df_volume = eth_market_info['Volume'].resample('1D').sum()
    eth_ohlc.reset_index(inplace=True)
    eth_market_info.reset_index(inplace=True)
    eth_ohlc['Date'] = eth_ohlc['Date'].map(dates.date2num)
    eth_market_info['Date'] = eth_market_info['Date'].map(dates.date2num)
    ax1 = plt.subplot2grid((6, 1), (0, 0),
                           rowspan=5,
                           colspan=5,
                           facecolor='#00004d')
    ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
    ax1.xaxis_date()
    candlestick_ohlc(ax1, eth_market_info.values, width=0.8, colorup='g')
    ax2.fill_between(eth_df_volume.index.map(dates.date2num),
                     eth_df_volume.values, 0)
    eth_lows = eth_market_info['Low']
    eth_highs = eth_market_info['High']
    current_eth_Low = eth_lows[29]
    currentLow = current_eth_Low
    current_eth_High = eth_highs[29]
    currentHigh = current_eth_High
    print(
        check_init_low('eth', 59, eth_market_info, " ", currentHigh,
                       currentLow))
    print(states)
    global eth_chart
    eth_chart = eth_ohlc.to_json(orient='records', lines=True)
    figEth = plt.gcf()
    canvasEth = figEth.canvas
    bufEth, sizeEth = canvasEth.print_to_buffer()
    imageEth = Image.frombuffer('RGBA', sizeEth, bufEth, 'raw', 'RGBA', 0, 1)
    buffer = io.BytesIO()
    imageEth.save(buffer, 'PNG')
    graphicEth = buffer.getvalue()
    graphicEth = base64.b64encode(graphicEth)
    buffer.close()
    imgdata = base64.b64decode(graphicEth)
    filename = 'images/EthChart.png'
    with open(filename, 'wb') as f:
        f.write(imgdata)
    f.close()

    ltc_market_info = pd.read_html(
        "https://coinmarketcap.com/currencies/litecoin/historical-data/?start="
        + yesterday.strftime('%Y%m%d') + "&end=" + time.strftime("%Y%m%d"),
        flavor='html5lib',
        parse_dates=True,
        index_col=0)[0]
    ltc_market_info['Volume'] = ltc_market_info['Volume'].astype('int64')
    print(ltc_market_info.head())

    ltc_market_info['100ma'] = ltc_market_info['Close'].rolling(
        window=100, min_periods=0).mean()
    # resampling
    ltc_ohlc = ltc_market_info['Close'].resample('1D').ohlc()
    ltc_df_volume = ltc_market_info['Volume'].resample('1D').sum()
    ltc_ohlc.reset_index(inplace=True)
    ltc_market_info.reset_index(inplace=True)
    ltc_ohlc['Date'] = ltc_ohlc['Date'].map(dates.date2num)
    ltc_market_info['Date'] = ltc_market_info['Date'].map(dates.date2num)
    print(pd.json.dumps(ltc_market_info.head()))
    ax1 = plt.subplot2grid((6, 1), (0, 0),
                           rowspan=5,
                           colspan=5,
                           facecolor='#00004d')
    ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
    ax1.xaxis_date()
    candlestick_ohlc(ax1, ltc_market_info.values, width=0.8, colorup='g')
    ax2.fill_between(ltc_df_volume.index.map(dates.date2num),
                     ltc_df_volume.values, 0)
    ltc_lows = ltc_market_info['Low']
    ltc_highs = ltc_market_info['High']
    current_ltc_Low = ltc_lows[29]
    currentLow = current_ltc_Low
    current_ltc_High = ltc_highs[29]
    currentHigh = current_ltc_High
    print(
        check_init_low('ltc', 59, ltc_market_info, " ", currentHigh,
                       currentLow))
    print(states)
    global ltc_chart
    ltc_chart = ltc_ohlc.to_json(orient='records', lines=True)
    figLtc = plt.gcf()
    #plt.show()

    canvasLtc = figLtc.canvas
    bufLtc, sizeLtc = canvasLtc.print_to_buffer()
    imageLtc = Image.frombuffer('RGBA', sizeLtc, bufLtc, 'raw', 'RGBA', 0, 1)

    buffer = io.BytesIO()
    imageLtc.save(buffer, 'PNG')
    graphicLtc = buffer.getvalue()
    graphicLtc = base64.b64encode(graphicLtc)
    buffer.close()

    imgdata = base64.b64decode(graphicLtc)
    filename = 'images/LtcChart.png'
    with open(filename, 'wb') as f:
        f.write(imgdata)
    f.close()

    os.system(
        'aws s3 sync /home/ubuntu/images s3://braikoutpredictions/Images --grants read=uri=http://acs.amazonaws.com/groups/global/AllUsers'
    )
fecha1 = (2014, 10, 13)
fecha2 = (2014, 11, 13)

# Vamos a la web y nos traemos la información de la cotización
valores = quotes_historical_yahoo_ohlc('AAPL', fecha1, fecha2)
if len(valores) == 0:
    raise SystemExit

# Definimos el aspecto de la gráfica
fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)

# Ponemos marcas mayores para los lunes
lunes = WeekdayLocator(MONDAY)
ax.xaxis.set_major_locator(lunes)

# Ponemos marcas menores para el resto de días
resto_dias = DayLocator()
ax.xaxis.set_minor_locator(resto_dias)

# Damos formato a los días
formato_semana = DateFormatter('%b %d')  # e.g., Ene 12
ax.xaxis.set_major_formatter(formato_semana)
ax.xaxis_date()

candlestick_ohlc(ax, valores, width=0.6)

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

plt.show()
Exemple #35
0
def graph_data(stock):

    fig = plt.figure()

    ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=1, colspan=1)
    plt.ylabel('H-L')
    ax2 = plt.subplot2grid((6, 1), (1, 0), rowspan=4, colspan=1, sharex=ax1)
    plt.ylabel('Price')
    ax3 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
    plt.ylabel('MAvgs')

    print('Currently pulling:', stock)
    url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=6m/csv'
    print(url)
    source_code = urllib.request.urlopen(url).read().decode()
    stock_data = []
    split_source = source_code.split('\n')

    for each_line in split_source:
        split_line = each_line.split(',')
        if len(split_line) == 6:
            if 'values' not in each_line:
                stock_data.append(each_line)

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

    ma1 = moving_average(closep, MA1)
    ma2 = moving_average(closep, MA2)
    start = len(date[MA2 - 1:])
    print(start)

    x = 0
    y = len(date)

    new_list = []
    while x < y:
        append_line = date[x], openp[x], highp[x], lowp[x], closep[x], volume[
            x]
        new_list.append(append_line)
        x += 1

    h_l = list(map(high_minus_low, highp, lowp))

    ax1.plot_date(date[-start:], h_l[-start:], '-')
    plt.setp(ax1.get_xticklabels(), visible=False)
    ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='lower'))

    candlestick_ohlc(ax2,
                     new_list[-start:],
                     width=.6,
                     colorup='#41ad49',
                     colordown='#ff1717')
    ax2.grid(True)  #, color = 'g', linestyle='-', linewidth=3)
    plt.setp(ax2.get_xticklabels(), visible=False)
    ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))
    bbox_props = dict(boxstyle='round4, pad=0.3', fc="#c5cbdf", ec='k', lw=2)
    ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
                 xytext=(date[-1] + 8, closep[-1]),
                 bbox=bbox_props)

    ax3.plot(date[-start:], ma1[-start:], linewidth=1)
    ax3.plot(date[-start:], ma2[-start:], linewidth=1)
    ax3.fill_between(date[-start:],
                     ma2[-start:],
                     ma1[-start:],
                     where=(ma2[-start:] >= ma1[-start:]),
                     facecolor='r',
                     edgecolor='r',
                     alpha=0.5)
    ax3.fill_between(date[-start:],
                     ma2[-start:],
                     ma1[-start:],
                     where=(ma2[-start:] <= ma1[-start:]),
                     facecolor='g',
                     edgecolor='g',
                     alpha=0.5)
    for label in ax3.xaxis.get_ticklabels():
        label.set_rotation(45)
    ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax3.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5, prune='upper'))

    plt.subplots_adjust(left=.11,
                        bottom=.16,
                        right=.90,
                        top=.95,
                        wspace=.2,
                        hspace=.0)
    plt.show()
# Converting date to pandas datetime format
df['Date'] = pd.to_datetime(df['Date'])
df["Date"] = df["Date"].apply(mdates.date2num)

# Creating required data in new DataFrame OHLC
ohlc= df[['Date', 'Open Price', 'High Price', 'Low Price','Close Price']].copy()
# In case you want to check for shorter timespan
# ohlc =ohlc.tail(60)
ohlc['SMA50'] = ohlc["Close Price"].rolling(50).mean()


f1, ax = plt.subplots(figsize = (10,5))

# plot the candlesticks
candlestick_ohlc(ax, ohlc.values, width=.6, colorup='green', colordown='red')
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m'))

# Creating SMA columns
ohlc['SMA5'] = ohlc["Close Price"].rolling(5).mean()
ohlc['SMA10'] = ohlc["Close Price"].rolling(10).mean()
ohlc['SMA20'] = ohlc["Close Price"].rolling(20).mean()
ohlc['SMA50'] = ohlc["Close Price"].rolling(50).mean()
ohlc['SMA100'] = ohlc["Close Price"].rolling(100).mean()
ohlc['SMA200'] = ohlc["Close Price"].rolling(200).mean()

#Plotting SMA columns
# ax.plot(ohlc['Date'], ohlc['SMA5'], color = 'blue', label = 'SMA5')
# ax.plot(ohlc['Date'], ohlc['SMA10'], color = 'blue', label = 'SMA10')
# ax.plot(ohlc['Date'], ohlc['SMA20'], color = 'blue', label = 'SMA20')
ax.plot(ohlc['Date'], ohlc['SMA50'], color = 'green', label = 'SMA50')
def graph_data(stock):

	fig = plt.figure()
	#ax1 = plt.subplot2grid((1,1), (0,0))
	ax1 = plt.subplot2grid((6,1), (0,0),rowspan=1,colspan=1)
	plt.title(stock)
	plt.ylabel('H-L')
	ax2 = plt.subplot2grid((6,1), (1,0),rowspan=4,colspan=1)
	#plt.xlabel('Date')
	plt.ylabel('Price')
	ax3 = plt.subplot2grid((6,1), (5,0),rowspan=1,colspan=1)
	plt.ylabel('MAvgs')
	
	stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
	source_code = urllib.request.urlopen(stock_price_url).read().decode()
	stock_data = []
	split_source = source_code.split('\n')
	for line in split_source:
		split_line = line.split(',')
		if len(split_line) == 6:
			if 'values' not in line and 'labels' not in line:
				stock_data.append(line)


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

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

	while x < y:
		append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
		ohlc.append(append_me)
		x+=1
	
	ma1 = moving_average(closep,MA1)
	ma2 = moving_average(closep,MA2)
	start = len(date[MA2-1:])
		
	h_l = list(map(high_minus_low,highp,lowp))
	ax1.plot_date(date,h_l,'-')
	ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=5,prune='lower'))

	candlestick_ohlc(ax2, ohlc, width=0.4, colorup='#77d879', colordown='#db3f3f')
	
	
	ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
	ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
	ax2.grid(True)
	
	bbox_props = dict(boxstyle='round',fc='w',ec='k',lw=1)

	ax2.annotate(str(closep[-1]),(date[-1],closep[-1]),xytext=(date[-1]+4, closep[-1]),bbox=bbox_props)
	#print(len(date), len(ma1)) 
	ax3.plot(date[-start:],ma1[-start:],linewidth=1)
	ax3.plot(date[-start:],ma2[-start:],linewidth=1)
	ax3.fill_between(date[-start:],ma2[-start:], ma1[-start:],
					where=(ma1[-start:] < ma2[-start:]),
					facecolor='r',edgecolor='r',alpha=0.5)
	
	ax3.fill_between(date[-start:],ma2[-start:], ma1[-start:],
					where=(ma1[-start:] > ma2[-start:]),
					facecolor='g',edgecolor='g',alpha=0.5)

	ax3.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
	ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
	for label in ax3.xaxis.get_ticklabels():
		label.set_rotation(45)

	
	plt.setp(ax1.get_xticklabels(), visible=False)
	plt.setp(ax2.get_xticklabels(), visible=False)
	plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
	plt.show()
Exemple #38
0
filepath = os.path.join(hqdatadir, (code + '.txt'))
# if not os.path.exists(filepath):
#     logger.critical("filepath %s does not exist", filepath)
#     raise RuntimeError, 'filepath does not exist'

rnames = ['d', 't', 'open', 'high', 'low', 'close', 'volume', 'amt']
df5mKline = pd.read_table(filepath,
                          engine='python',
                          sep=',',
                          encoding='gbk',
                          names=rnames,
                          parse_dates={'time': ['d', 't']},
                          index_col='time',
                          skiprows=2,
                          skipfooter=1)

# ma60_ = ta.SMA(df5mKline['close'].values, 60)
# df5mKline['ma60'] = ma60_
df5mKline.fillna(0.)

fig, ax = plt.subplots()
fig.subplots_adjust(bottom=0.2)
candlestick_ohlc(ax, df5mKline, width=0.6)

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

plt.show()

fig, axes = plt.subplots(2, 3)
Exemple #39
0
    clop = np.float64(Data[time][4])
    volm = np.float64(Data[time][5])

    appendLine = date, open, high, lowp, clop, volm
    newAr.append(appendLine)
    dt_x.append(raw_x)
    y.append(int(Data[time][4]))
x = [mdates.date2num(i) for i in dt_x]

yMa_20 = movingaverage(y, 20)  #day ma
yMa_10 = movingaverage(y, 10)
yMa_60 = movingaverage(y, 60)
yMa_120 = movingaverage(y, 120)

ax = plt.subplot2grid((6, 4), (1, 0), rowspan=4, colspan=4, axisbg='#07000d')

ax.xaxis.set_major_locator(mticker.MaxNLocator(10))  #set x locator interva
ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
candlestick_ohlc(ax, newAr, width=.6, colorup='#53c156', colordown='#ff1717')

ax.plot_date(x, y, 'r-')

fig.autofmt_xdate()

ax.plot(x[:-(len(x) - len(yMa_10))], yMa_10)
ax.plot(x[:-(len(x) - len(yMa_20))], yMa_20)
ax.plot(x[:-(len(x) - len(yMa_60))], yMa_60, 'w-')
ax.plot(x[:-(len(x) - len(yMa_120))], yMa_120)

plt.show()
Exemple #40
0
def graph_data(stock):

    fig = plt.figure()
    ax1 = plt.subplot2grid((6,1), (0,0), rowspan=1, colspan=1)
    plt.title(stock)
    plt.ylabel('H-L')
    ax2 = plt.subplot2grid((6,1), (1,0), rowspan=4, colspan=1, sharex=ax1)
    plt.ylabel('Price')
    ax2v = ax2.twinx()
    
    ax3 = plt.subplot2grid((6,1), (5,0), rowspan=1, colspan=1, sharex=ax1)
    plt.ylabel('MAvgs')
    
    
    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=1y/csv'
    source_code = urllib.request.urlopen(stock_price_url).read().decode()
    stock_data = []
    split_source = source_code.split('\n')
    for line in split_source:
        split_line = line.split(',')
        if len(split_line) == 6:
            if 'values' not in line and 'labels' not in line:
                stock_data.append(line)

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

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

    while x < y:
        append_me = date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
        ohlc.append(append_me)
        x+=1

    ma1 = moving_average(closep,MA1)
    ma2 = moving_average(closep,MA2)
    start = len(date[MA2-1:])

    h_l = list(map(high_minus_low, highp, lowp))
    

    ax1.plot_date(date[-start:],h_l[-start:],'-')
    ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='lower'))


    candlestick_ohlc(ax2, ohlc[-start:], width=0.4, colorup='#77d879', colordown='#db3f3f')
  
    

    ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=7, prune='upper'))
    ax2.grid(True)
    
    bbox_props = dict(boxstyle='round',fc='w', ec='k',lw=1)
    
    ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
                 xytext = (date[-1]+5, closep[-1]), bbox=bbox_props)

##    # Annotation example with arrow
##    ax2.annotate('Bad News!',(date[11],highp[11]),
##                 xytext=(0.8, 0.9), textcoords='axes fraction',
##                 arrowprops = dict(facecolor='grey',color='grey'))
##
##    
##    # Font dict example
##    font_dict = {'family':'serif',
##                 'color':'darkred',
##                 'size':15}
##    # Hard coded text 
##    ax2.text(date[10], closep[1],'Text Example', fontdict=font_dict)
    
    ax2v.fill_between(date[-start:],0, volume[-start:], facecolor='#0079a3', alpha=0.4)
    ax2v.axes.yaxis.set_ticklabels([])
    ax2v.grid(False)
    ax2v.set_ylim(0, 3*volume.max())



    ax3.plot(date[-start:], ma1[-start:], linewidth=1)
    ax3.plot(date[-start:], ma2[-start:], linewidth=1)
    
    ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
                     where=(ma1[-start:] < ma2[-start:]),
                     facecolor='r', edgecolor='r', alpha=0.5)

    ax3.fill_between(date[-start:], ma2[-start:], ma1[-start:],
                     where=(ma1[-start:] > ma2[-start:]),
                     facecolor='g', edgecolor='g', alpha=0.5)
    
    ax3.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
    ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='upper'))

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



    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.setp(ax2.get_xticklabels(), visible=False)
    plt.subplots_adjust(left=0.11, bottom=0.24, right=0.90, top=0.90, wspace=0.2, hspace=0)
    plt.show()
Exemple #41
0
d = loaddict("./", "pickle")
data_list = []

for block in d:
    dt = datetime.datetime.utcfromtimestamp(
        block['id']) + datetime.timedelta(hours=8)
    # mpf库中要求的顺序是:时间、开盘价、最高价、最低价、收盘价
    data_list.append((date2num(dt), block['open'], block['high'], block['low'],
                      block['close']))

fig, ax = plt.subplots()
ax.xaxis_date()
ax.set_title('BTC/USDT')
mpf.candlestick_ohlc(ax,
                     data_list,
                     colorup='green',
                     colordown='r',
                     width=0.005)
plt.grid()
plt.show()
'''
fig, ax = plt.subplots(figsize=(15,5))
mpf.plot_day_summary_oclh(ax, data_list,colorup='g', colordown='r')
plt.grid(True)
ax.xaxis_date()
plt.title('wandayuanxian 17')
plt.ylabel('Price')
plt.grid()
plt.show()
'''
if __name__ == "__main__":
    mpl.rcParams['font.sans-serif'] = [u'SimHei']
    mpl.rcParams['axes.unicode_minus'] = False

    np.set_printoptions(suppress=True, linewidth=100, edgeitems=5)
    data = np.loadtxt('SH600000.txt',
                      dtype=np.float,
                      delimiter='\t',
                      skiprows=2,
                      usecols=(1, 2, 3, 4))
    data = data[:50]
    N = len(data)

    t = np.arange(1, N + 1).reshape((-1, 1))
    data = np.hstack((t, data))

    fig, ax = plt.subplots(facecolor='w')
    fig.subplots_adjust(bottom=0.2)
    candlestick_ohlc(ax,
                     data,
                     width=0.8,
                     colorup='r',
                     colordown='g',
                     alpha=0.9)
    plt.xlim((0, N + 1))
    plt.grid(b=True)
    plt.title(u'股票K线图', fontsize=18)
    plt.tight_layout(2)
    plt.show()
Exemple #43
0
from matplotlib.pylab import date2num

quotes = []
stock = pd.read_csv('data/stock_daily_inversed/SH/600000.csv', index_col=0)

for row in range(70):
    if row == 0:
        sdate = str(stock.loc[row, 'trade_date'])  # 注意:loc返回数值,iloc返回dataframe
        sdate_change_format = sdate[0:4] + '-' + sdate[4:6] + '-' + sdate[6:]
        sdate_num = date2num(datetime.datetime.strptime(sdate_change_format, '%Y-%m-%d'))  # 日期需要特定形式,这里进行转换
        sdate_plt = sdate_num
    else:
        sdate_plt = sdate_num + row

    sopen = stock.loc[row, 'open']
    shigh = stock.loc[row, 'high']
    slow = stock.loc[row, 'low']
    sclose = stock.loc[row, 'close']
    datas = (sdate_plt, sopen, shigh, slow, sclose)  # 按照 candlestick_ohlc 要求的数据结构准备数据
    quotes.append(datas)

fig, ax = plt.subplots(facecolor=(0, 0.3, 0.5), figsize=(12, 8))
fig.subplots_adjust(bottom=0.1)
ax.xaxis_date()
plt.xticks(rotation=45)  # 日期显示的旋转角度
plt.title('600000')
plt.xlabel('time')
plt.ylabel('price')
mpf.candlestick_ohlc(ax, quotes, width=0.7, colorup='r', colordown='green')  # 上涨为红色K线,下跌为绿色,K线宽度为0.7
plt.grid(True)
            color='green',
            s=50,
            marker="^")
axe.scatter(AssetCopy.loc[AssetCopy['ShortSignal'] == 1,
                          'IndexToNumber'].values,
            AssetCopy.loc[AssetCopy['ShortSignal'] == 1,
                          'EntryPriceUnitOne'].values,
            label='skitscat',
            color='red',
            s=50,
            marker="v")

#Plot the DF values with the figure, object
candlestick_ohlc(axe,
                 AssetCopy.values,
                 width=.6,
                 colorup='green',
                 colordown='red')
axe.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))

#For ATR
figure2, axe2 = plt.subplots(figsize=(10, 2))
#Labels
plt.ylabel(string + ' ATR')
plt.xlabel('Date')
#ATR line graphs and rolling min/max
axe2.plot(AssetCopy['IndexToNumber'],
          AssetCopy['4wkATRPercent'],
          color='black',
          label='4wkATRPercent')
axe2.plot(AssetCopy['IndexToNumber'],
def candleLinePlots(candleData, candleTitle='a', **kwargs):
    Date = [date2num(date) for date in candleData.index]
    candleData.loc[:, 'Date'] = Date
    listData = []
    for i in range(len(candleData)):
        a = [candleData.Date[i],\
            candleData.Open[i],candleData.High[i],\
            candleData.Low[i],candleData.Close[i]]
        listData.append(a)
    # 如 果 不 定 長 參 數 無 取 值 , 只 畫 蠟 燭 圖
    ax = plt.subplot()
    # 如 果 不 定 長 參 數 有 值 , 則 分 成 兩 個 子 圖
    flag = 0
    if kwargs:
        if kwargs['splitFigures']:
            ax = plt.subplot(211)
            ax2 = plt.subplot(212)
            flag = 1
        for key in kwargs:
            if key == 'title':
                ax2.set_title(kwargs[key])
            if key == 'ylabel':
                ax2.set_ylabel(kwargs[key])
            if key == 'grid':
                ax2.grid(kwargs[key])
            if key == 'Data':
                plt.sca(ax)
                if flag:
                    plt.sca(ax2)
                #一維數據
                if kwargs[key].ndim == 1:
                    plt.plot(kwargs[key],\
                             color='k',\
                             label=kwargs[key].name)
                    plt.legend(loc='best')
                #二維數據有兩個columns
                elif all([kwargs[key].ndim==2,\
                          len(kwargs[key].columns)==2]):
                    plt.plot(kwargs[key].iloc[:, 0],
                             color='k',
                             label=kwargs[key].iloc[:, 0].name)
                    plt.plot(kwargs[key].iloc[:,1],\
                             linestyle='dashed',\
                             label=kwargs[key].iloc[:,1].name)
                    plt.legend(loc='best')
                #二維數據有3個columns
                elif all([kwargs[key].ndim==2,\
                          len(kwargs[key].columns)==3]):
                    plt.plot(kwargs[key].iloc[:, 0],
                             color='k',
                             label=kwargs[key].iloc[:, 0].name)
                    plt.plot(kwargs[key].iloc[:, 1],
                             linestyle='dashed',
                             label=kwargs[key].iloc[:, 1].name)
                    plt.bar(left=kwargs[key].iloc[:, 2].index,
                            height=kwargs[key].iloc[:, 2],
                            color='r',
                            label=kwargs[key].iloc[:, 2].name)
                    plt.legend(loc='best')
    mondays = WeekdayLocator(MONDAY)
    weekFormatter = DateFormatter('%y %b %d')
    ax.xaxis.set_major_locator(mondays)
    ax.xaxis.set_minor_locator(DayLocator())
    ax.xaxis.set_major_formatter(weekFormatter)
    plt.sca(ax)

    candlestick_ohlc(ax,listData, width=0.7,\
                     colorup='r',colordown='g')
    ax.set_title(candleTitle)
    plt.setp(ax.get_xticklabels(),\
             rotation=20,\
             horizontalalignment='center')
    ax.autoscale_view()

    return (plt.show())
        data_list_center.append(datas)
        
# plot raw_data
# set the start date and end date
# format : (yyy,mmm,ddd)
date1 = (2014, 9, 24)  
date2 = (2017, 5, 12)  
# transform the data from TuShare to a available format of candlestick_ohlc()
data_list_raw = []
for dates, row in stock_data.iterrows():
    # transform datetime into string
    dates = str(row[0])
    date_time = datetime.datetime.strptime(dates, '%Y-%m-%d')
    t = date2num(date_time)
    open, close, high, low = row[1:5]
    datas = (t, open, high, low, close)
    data_list_raw.append(datas)
# create a subplot
fig, ax = plt.subplots(facecolor=(0.5, 0.5, 0.5))
fig.subplots_adjust(bottom=0.2)

ax.xaxis_date()
plt.xticks(rotation=45)
plt.title("Stock code:000001")
plt.xlabel("date")
plt.ylabel("price(yuan)")
mpf.candlestick_ohlc(ax, data_list_raw, width=2, colorup='r', colordown='g')
# mpf.candlestick_ohlc(ax, data_list_center, width=2, colorup='black', colordown='blue')
plt.grid(True)
plt.show()
def graph_data(stock):

   fig=plt.figure()
   ax1=plt.subplot2grid((6,1),(0,0),rowspan=1,colspan=1)
   ax2=plt.subplot2grid((6,1),(1,0),rowspan=4,colspan=1)
   
   
   plt.ylabel('Price')

   ax3=plt.subplot2grid((6,1),(5,0),rowspan=1,colspan=1)

   print('Currently pulling',stock)
   url='http://chartapi.finance.yahoo.com/instrument/1.0/'+stock+'/chartdata;type=quote;range=3m/csv'
   print(url)
   source_code=urllib.request.urlopen(url).read().decode()
   stock_data=[]
   split_source=source_code.split('\n')

   for each_line in split_source:
       split_line=each_line.split(',')
       if len(split_line)==6:
           if 'values' not in each_line:
               stock_data.append(each_line)

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

   ma1=moving_average(closep,MA1)
   ma2=moving_average(closep,MA2)
   
   start=len(date[MA2-1:])
   print(start)

   

   x=0
   y=len(date)
   new_list=[]
   while x<y:
       append_line=date[x], openp[x], highp[x], lowp[x], closep[x], volume[x]
       new_list.append(append_line)
       x+=1
   h_1=list(map(high_minus_low,highp,lowp))
   ax1.plot_date(date,h_1,'-')
   plt.setp(ax1.get_xticklabels(),visible=False)
   
   
   
       



   candlestick_ohlc(ax2,new_list,width=.6,colorup='r',colordown='g')
   ax2.grid(True)    
   for label in ax2.xaxis.get_ticklabels():
       label.set_rotation(45)

   ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
   ax2.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
##   ax1.annotate('Oil Spill!!',(date[24],closep[24]),xytext=(0.8,0.9),textcoords='axes fraction',arrowprops=dict(facecolor="#585858",color="#585858"))
##

   #want to actually annotate
   #last price
   bbox_props=dict(boxstyle='larrow,pad=0.3',fc="#f2f1f1",ec='k',lw=2)
   bbox=bbox_props
   ax2.annotate(str(closep[-1]), (date[-1],closep[-1]),xytext=(date[-1]+5,closep[-1]),bbox=bbox_props)

   plt.setp(ax2.get_xticklabels(),visible=False)
   print(len(date))
   print(len(ma1))
   ax3.plot(date[-start:],ma1[-start:],linewidth=1)
   ax3.plot(date[-start:],ma2[-start:],linewidth=1)
   ax3.fill_between(date[-start:],ma2[-start:],ma1[-start:],where=(ma2[-start]>=ma1[-start:]),facecolor='r',edgecolor='r',alpha=0.5)
   ax3.fill_between(date[-start:],ma2[-start:],ma1[-start:],where=(ma2[-start]<=ma1[-start:]),facecolor='g',edgecolor='g',alpha=0.5)


   plt.ylabel('Price')
   plt.xlabel('Date')
       

   
   #ax1.grid(True,color='g',linestyle='-',linewidth=3)
   ax2.grid(True)
   plt.subplots_adjust(left=.09, bottom=.16,right=.94,top=.95,wspace=.2,hspace=0)
   plt.show()
Exemple #48
0
def chart(context, prices, analysis, results):
    results.portfolio_value.plot()

    # Data for matplotlib finance plot
    dates = date2num(prices.index.to_pydatetime())

    # Create the Open High Low Close Tuple
    prices_ohlc = [
        tuple([
            dates[i], prices.open[i], prices.high[i], prices.low[i],
            prices.close[i]
        ]) for i in range(len(dates))
    ]

    fig = plt.figure(figsize=(14, 18))

    # Draw the candle sticks
    ax1 = fig.add_subplot(411)
    ax1.set_ylabel(context.ASSET_NAME, size=20)
    candlestick_ohlc(ax1, prices_ohlc, width=0.4, colorup='g', colordown='r')

    # Draw Moving Averages
    analysis.sma_f.plot(ax=ax1, c='r')
    analysis.sma_s.plot(ax=ax1, c='g')

    # RSI
    ax2 = fig.add_subplot(412)
    ax2.set_ylabel('RSI', size=12)
    analysis.rsi.plot(ax=ax2,
                      c='g',
                      label='Period: ' + str(context.RSI_PERIOD))
    analysis.sma_r.plot(ax=ax2,
                        c='r',
                        label='MA: ' + str(context.RSI_AVG_PERIOD))
    ax2.axhline(y=30, c='b')
    ax2.axhline(y=50, c='black')
    ax2.axhline(y=70, c='b')
    ax2.set_ylim([0, 100])
    handles, labels = ax2.get_legend_handles_labels()
    ax2.legend(handles, labels)

    # Draw MACD computed with Talib
    ax3 = fig.add_subplot(413)
    ax3.set_ylabel('MACD: ' + str(context.MACD_FAST) + ', ' +
                   str(context.MACD_SLOW) + ', ' + str(context.MACD_SIGNAL),
                   size=12)
    analysis.macd.plot(ax=ax3, color='b', label='Macd')
    analysis.macdSignal.plot(ax=ax3, color='g', label='Signal')
    analysis.macdHist.plot(ax=ax3, color='r', label='Hist')
    ax3.axhline(0, lw=2, color='0')
    handles, labels = ax3.get_legend_handles_labels()
    ax3.legend(handles, labels)

    # Stochastic plot
    ax4 = fig.add_subplot(414)
    ax4.set_ylabel('Stoch (k,d)', size=12)
    analysis.stoch_k.plot(ax=ax4,
                          label='stoch_k:' + str(context.STOCH_K),
                          color='r')
    analysis.stoch_d.plot(ax=ax4,
                          label='stoch_d:' + str(context.STOCH_D),
                          color='g')
    handles, labels = ax4.get_legend_handles_labels()
    ax4.legend(handles, labels)
    ax4.axhline(y=20, c='b')
    ax4.axhline(y=50, c='black')
    ax4.axhline(y=80, c='b')

    plt.show()
Exemple #49
0
floc = '/Users/JohnHanlon/Desktop/Python/Sentdex Tutorials/Python ' \
       'Programming for Finance [Sentdex]/Data Examples/'
ftype = '.csv'
security = 'TSLA'

start = dt.datetime(2000, 1, 1)
end = dt.datetime(2016, 12, 31)

# df = web.DataReader(security, 'yahoo', start, end)
# df.to_csv('{}{}{}'.format(floc, security, ftype))
# df.head()

df = pd.read_csv('{}{}{}'.format(floc, security, ftype),
                 parse_dates=True,
                 index_col=0)

df_ohlc = df['Adj Close'].resample('10D').ohlc()
df_volume = df['Volume'].resample('10D').sum()

df_ohlc.reset_index(inplace=True)
df_ohlc['Date'] = df_ohlc['Date'].map(mdates.date2num)

ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=5, colspan=1)
ax2 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
ax1.xaxis_date()

candlestick_ohlc(ax1, df_ohlc.values, width=2, colorup='g')
ax2.fill_between(df_volume.index.map(mdates.date2num), df_volume.values, 0)

plt.show()
Exemple #50
0
def create_candles(interval=30, type='ask'):
    tickers = Ticker.select().order_by(Ticker.timestamp.desc())
    print(len(tickers))
    print(tickers[0].timestamp.timestamp())
    print(tickers[-1].timestamp.timestamp())

    origin = tickers[0].timestamp.timestamp()

    times = []
    candles = []
    group = []

    for t in tickers:
        if origin >= t.timestamp.timestamp() > origin - interval:
            group.append(t.ask if type == 'ask' else t.bid)
        else:
            if 0 < len(group):
                times.append(origin)
                # candles.append((datetime.datetime.fromtimestamp(origin), group[-1], max(group), min(group),  group[0]))
                candles.append((origin, group[-1], max(group), min(group),  group[0]))

            group = []

            origin -= interval

    t = [x for x in reversed(times)]
    cdl = [x for x in reversed(candles)]

    [print(c) for c in candles]

    # 描画
    # d = [x[0] for x in candles]
    # o = [x[1] for x in candles]
    # h = [x[2] for x in candles]
    # l = [x[3] for x in candles]
    # c = [x[4] for x in candles]

    # x = d, o, h, l, c
    # ohlc = []
    # ohlc.append(x)


    fig, ax = plt.subplots()
    # candlestick_ohlc(ax, cdl, width=(1.0 / 24 / 60 * interval), colorup='b', colordown='r')
    candlestick_ohlc(ax, cdl)

    xdate = [datetime.datetime.fromtimestamp(i) for i in t]
    # ax.xaxis.set_major_locator(ticker.MaxNLocator(1))

    def mydate(x, pos):
        try:
            return xdate[int(x)]
        except IndexError:
            return ''

    ax.xaxis.set_major_formatter(ticker.FuncFormatter(mydate))

    fig.autofmt_xdate()
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.subplots_adjust(left=0.09, bottom=0.20, right=0.94, top=0.90, wspace=0.2, hspace=0)
    plt.show()
Exemple #51
0
        def draw_line(t, o, h, l, c, v, *args, **kargs):
            '''
            绘制K线图,并叠加额外曲线于其上
            输入:
                时间序列:t, 要求:dt.datetime对应的时间戳序列
                开盘价序列:o
                最高价序列:h
                最低价序列:l
                收盘价序列:c
                成交量序列:v
                额外数据序列:args【可选】, 可以有多组数据序列,比如:有5组数据序列
            参数:
                额外数据序列对应的参数:kargs【可选】,只支持如下参数:
                    names 额外数据命名。比如['aa','bb','cc','dd','ee']表示额外的5条曲线对应的名字
                    colors 额外数据绘制颜色。 比如['r','b','g','r','b']表示额外的5条曲线对应的颜色
                    widths 额外数据绘制线宽。 比如['2','2','2','1','1']表示额外的5条曲线对应的线宽
                    fill_pairs 曲线间填充颜色。比如[(3,4,'y')]表示第3和4两条曲线间填充黄色
            '''

            # 准备K线数据
            t_i = np.arange(len(t))
            quotes = zip(t_i, o, h, l, c)

            # 绘制K线
            fig = plt.figure(figsize=(20, 10))
            ax1 = plt.subplot2grid((10, 4), (0, 0), rowspan=5, colspan=4)
            candlestick_ohlc(ax1,
                             quotes,
                             width=0.5,
                             colorup='r',
                             colordown='g')

            if len(args) > 0:
                # 绘制额外曲线
                names = kargs.get("names", None)
                colors = kargs.get("colors", None)
                widths = kargs.get("widths", None)
                fill_pairs = kargs.get("fill_pairs", None)
                for _i in np.arange(len(args)):
                    data = args[_i]
                    name_str = ""
                    if names:
                        name_str = ", label=\"$%s$\"" % names[_i]
                    color_str = ""
                    if colors:
                        color_str = ", \"%s\"" % colors[_i]
                    width_str = ""
                    if widths:
                        width_str = ", linewidth=%s" % widths[_i]
                    # 为exec的执行定义3个局部变量
                    scope = {'_t_i': t_i, '_ax1': ax1, "_data": data}
                    stm = "ax1.plot(t_i, data%s%s%s)" % (color_str, width_str,
                                                         name_str)
                    exec(stm) in scope
                if fill_pairs:
                    for _pair in fill_pairs:
                        _i = _pair[0]
                        _j = _pair[1]
                        _c = _pair[2]
                        a = args[_i].astype(np.float)
                        b = args[_j].astype(np.float)
                        ax1.fill_between(t_i,
                                         a,
                                         b,
                                         alpha=0.5,
                                         facecolor=_c,
                                         edgecolor=_c)
            ax1.legend()

            # 绘制成交量
            ax2 = plt.subplot2grid((10, 4), (5, 0),
                                   rowspan=2,
                                   colspan=4,
                                   sharex=ax1)
            barlist = ax2.bar(t_i, v)
            for i in t_i:
                if o[i] < c[i]:
                    barlist[i].set_color('r')
                else:
                    barlist[i].set_color('g')

            # 手工设置刻度显示【可以避免candlestick_ohlc用时间作为刻度出现的跳空问题】
            plt.xlim(0, len(t) - 1)

            def t_formatter(_i, pos):
                i = int(_i)
                if i > len(t) - 1:
                    i = len(t) - 1
                elif i < 0:
                    i = 0
                if t[i] == 0:
                    return ""
                d = dt.date.fromtimestamp(t[i])
                return d.strftime('$%Y-%m-%d$')

            ax1.xaxis.set_major_formatter(tk.FuncFormatter(t_formatter))

            # result_path = kargs.get('result_path')
            # result_name = kargs.get('result_name')
            # plt.savefig(result_path+result_name)
            # 显示
            plt.show()

            draw_line(
                _t,
                _o,
                _h,
                _l,
                _c,
                _v,
                _tenkan,
                _kijun,
                _chinkou,
                _senkoua,
                _senkoub,
                names=['TENKAN', 'KIJUN', 'CHINKOU', 'SENKOUA', 'SENKOUB'],
                colors=['r', 'b', 'g', 'r', 'b'],
                widths=[2, 2, 2, 1, 1],
                fill_pairs=[(3, 4, 'y')])
Exemple #52
0
def graph_data(stock):

    fig = plt.figure(facecolor='#f0f0f0')
    # first tuple is the shape of the grid
    # the second tuple is the start point of this plot
    ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=1, colspan=1)
    plt.title(stock)
    plt.ylabel('H-L')
    ax2 = plt.subplot2grid((6, 1), (1, 0), rowspan=4, colspan=1, sharex=ax1)
    plt.ylabel('Price')
    ax2v = ax2.twinx()
    ax3 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
    plt.ylabel('M-AVGs')

    # in order to test it using unix time, change the parameter '10y' to '10d'
    stock_price_url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=10y/csv'
    source_code = urllib.request.urlopen(stock_price_url).read().decode()
    stock_data = []
    split_source = source_code.split('\n')

    for line in split_source:
        split_line = line.split(',')
        if len(split_line) == 6:
            if 'values' not in line:
                stock_data.append(line)

    date, close_price, high_price, low_price, open_price, volume = np.loadtxt(
        stock_data,
        delimiter=',',
        unpack=True,
        converters={0: bytespdate2num('%Y%m%d')})

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

    while x < y:
        append_me = date[x], open_price[x], high_price[x], low_price[
            x], close_price[x], volume[x]
        ohlc.append(append_me)
        x += 1

    ma1 = moving_average(close_price, MA1)
    ma2 = moving_average(close_price, MA2)
    start = len(date[MA2 - 1:])

    h_1 = list(map(high_minus_low, high_price, low_price))

    ax1.plot_date(date[-start:], h_1[-start:], '-', label='H-L')
    # nbins = it will dictate how many labels we have
    ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='lower'))

    candlestick_ohlc(ax2,
                     ohlc[-start:],
                     width=0.6,
                     colorup='#77d879',
                     colordown='#db3f3f')

    ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=7, prune='upper'))
    ax2.grid(True)

    bbox_props = dict(boxstyle='round', fc='w', ec='k', lw=1)

    ax2.annotate(str(close_price[-1]), (date[-1], close_price[-1]),
                 xytext=(date[-1] + 4, close_price[-1]),
                 bbox=bbox_props)

    # 'False data', because we can put a label when using 'fill_between'
    ax2v.plot([], [], color='#0079a3', alpha=0.4, label='Volume')
    ax2v.fill_between(date[-start:],
                      0,
                      volume[-start:],
                      facecolor='#0079a3',
                      alpha=0.4)
    ax2v.axes.yaxis.set_ticklabels([])
    ax2v.grid(False)
    # set the limits of this yaxis
    ax2v.set_ylim(0, 3 * volume.max())

    ax3.plot(date[-start:], ma1[-start:], linewidth=1, label=(str(MA1) + 'MA'))
    ax3.plot(date[-start:], ma2[-start:], linewidth=1, label=(str(MA2) + 'MA'))
    ax3.fill_between(date[-start:],
                     ma2[-start:],
                     ma1[-start:],
                     where=(ma1[-start:] < ma2[-start:]),
                     facecolor='r',
                     edgecolor='r',
                     alpha=0.5)

    ax3.fill_between(date[-start:],
                     ma2[-start:],
                     ma1[-start:],
                     where=(ma1[-start:] > ma2[-start:]),
                     facecolor='g',
                     edgecolor='g',
                     alpha=0.5)

    # converting the date using DateFormatter
    ax3.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m/%d'))
    # set a custom locator (x-axis "labels")
    ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='upper'))

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

    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.setp(ax2.get_xticklabels(), visible=False)
    # wspace and hspace correspond to padding between figures
    plt.subplots_adjust(left=0.09,
                        bottom=0.20,
                        right=0.94,
                        top=0.88,
                        wspace=0.2,
                        hspace=0)

    ax1.legend()
    leg = ax1.legend(loc=9, ncol=2, prop={'size': 11})
    leg.get_frame().set_alpha(0.4)

    ax2v.legend()
    leg = ax2v.legend(loc=9, ncol=2, prop={'size': 11})
    leg.get_frame().set_alpha(0.4)

    ax3.legend()
    leg = ax3.legend(loc=9, ncol=2, prop={'size': 11})
    leg.get_frame().set_alpha(0.4)

    plt.show()
    fig.savefig(
        'C:/Users/rodri/OneDrive/Documentos/python/data/stockchart.png',
        facecolor=fig.get_facecolor())
Exemple #53
0
def graph_data(stock):

    fig = plt.figure()

    ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=1, colspan=1)
    ax2 = plt.subplot2grid((6, 1), (1, 0), rowspan=4, colspan=1)
    plt.ylabel('Preis')
    ax3 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1)

    print('Currently pulling:', stock)
    url = 'http://chartpi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=3m/csv'
    print(url)
    source_code = urllib.request.urlopen(url).read().decode()
    stock_data = []
    split_source = source_code.split('\n')

    for each_line in split_source:
        split_line = each_line.split(',')
        if len(split_line) == 6:
            if 'value' not in each_line:
                stock_data.append(each_line)

    date, closep, highp, lowp, openp, volume = np.loadtxt(
        stock_data,
        delimeter=',',
        unpack=True,
        converter={0: bytespdate2num('%Y%m%d')})

    ma1 = moving_average(closep, MA1)
    ma2 = moving_average(closep, MA2)
    start = len(date[MA2 - 1:])
    print(start)

    x = 0
    y = len(date)

    new_list = []
    while x < y:
        append_line = date[x], openp[x], highp[x], lowp[x], closep[x], volume[
            x]
        new_list.append(append_line)
        x += 1

    candlestick_ohlc(ax2,
                     new_list,
                     width=.6,
                     colorup='#41ad49',
                     colordown='#ff1717')
    ax2.grid(True)
    for label in ax2.xaxis.get_ticklabels():
        label.set_rotation(45)
    ax2.xaxis.set_major_locator(mticker.MaxNLocator(10))
    ax2.xaxis.set_major_formater(mdates.DateFormatter('%Y%m%d'))

    bbox_props = dict(boxstyle='round4, pad=0.3', fc="y", ec='k', lw=2)
    ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
                 xytext=(date[-1] + 8, closep[-1]),
                 bbox=bbox_props)

    print(len(date))
    print(len(ma1))
    ax3.plot(date[-start:], ma1[-start:])
    ax3.plot(date[-start:], ma2[-start:])

    plt.subplots_adjust(left=.11,
                        bottom=.16,
                        right=.90,
                        top=.95,
                        wspace=.2,
                        hspace=.2)
    plt.show()
Exemple #54
0
     DayLocator, MONDAY
from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc

# (Year, month, day) tuples suffice as args for quotes_historical_yahoo
date1 = (2015, 2, 1)
date2 = (2015, 5, 22)

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_ohlc('600000.SS', 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_ohlc(ax, quotes, width=0.6)

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

plt.show()
Exemple #55
0
    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
    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)

    #Another way of getting stock data.
    quotes = quotes_historical_yahoo_ohlc(
        tickers[ticIdx], startDate, today
    )  # output format is: [datenum, open,high,low,close,volume] one date per row.

    candlestick_ohlc(ax, quotes[-daysBack:-1], width=0.5)
    ax.plot(finData.index[-daysBack:-1],
            finData.close[-daysBack:-1],
            'b',
            label='Close')
    ax.plot(finData.index[-daysBack:-1],
            ma50[-daysBack:-1],
            'k',
            label='50 day MA')
    ax.set_title(tickers[ticIdx] + ' Last Date:' +
                 finData.index[-1].strftime('%Y-%m-%d'))
    ax.legend(loc='best', fontsize=fs)
    ax.grid('on')
    ax.tick_params(labelsize=fs)
    ax.xaxis.label.set_fontsize(fs)
    plt.savefig(pwd + '/' + tickers[ticIdx] +
def pandas_candlestick_ohlc(dat, stick="day", otherseries=None):
    """
    :param dat: pandas DataFrame object with datetime64 index, and float columns "Open", "High", "Low", and "Close", likely created via DataReader from "yahoo"
    :param stick: A string or number indicating the period of time covered by a single candlestick. Valid string inputs include "day", "week", "month", and "year", ("day" default), and any numeric input indicates the number of trading days included in a period
    :param otherseries: An iterable that will be coerced into a list, containing the columns of dat that hold other series to be plotted as lines
 
    This will show a Japanese candlestick plot for stock data stored in dat, also plotting other series if passed.
    """
    mondays = WeekdayLocator(MONDAY)  # major ticks on the mondays
    alldays = DayLocator()  # minor ticks on the days
    dayFormatter = DateFormatter('%d')  # e.g., 12

    # Create a new DataFrame which includes OHLC data for each period specified by stick input
    transdat = dat.loc[:, ["Open", "High", "Low", "Close"]]
    if (type(stick) == str):
        if stick == "day":
            plotdat = transdat
            stick = 1  # Used for plotting
        elif stick in ["week", "month", "year"]:
            if stick == "week":
                transdat["week"] = pd.to_datetime(transdat.index).map(
                    lambda x: x.isocalendar()[1])  # Identify weeks
            elif stick == "month":
                transdat["month"] = pd.to_datetime(transdat.index).map(
                    lambda x: x.month)  # Identify months
            transdat["year"] = pd.to_datetime(transdat.index).map(
                lambda x: x.isocalendar()[0])  # Identify years
            grouped = transdat.groupby(list(set(
                ["year",
                 stick])))  # Group by year and other appropriate variable
            plotdat = pd.DataFrame({
                "Open": [],
                "High": [],
                "Low": [],
                "Close": []
            })  # Create empty data frame containing what will be plotted
            for name, group in grouped:
                plotdat = plotdat.append(
                    pd.DataFrame(
                        {
                            "Open": group.iloc[0, 0],
                            "High": max(group.High),
                            "Low": min(group.Low),
                            "Close": group.iloc[-1, 3]
                        },
                        index=[group.index[0]]))
            if stick == "week": stick = 5
            elif stick == "month": stick = 30
            elif stick == "year": stick = 365

    elif (type(stick) == int and stick >= 1):
        transdat["stick"] = [
            np.floor(i / stick) for i in range(len(transdat.index))
        ]
        grouped = transdat.groupby("stick")
        plotdat = pd.DataFrame({
            "Open": [],
            "High": [],
            "Low": [],
            "Close": []
        })  # Create empty data frame containing what will be plotted
        for name, group in grouped:
            plotdat = plotdat.append(
                pd.DataFrame(
                    {
                        "Open": group.iloc[0, 0],
                        "High": max(group.High),
                        "Low": min(group.Low),
                        "Close": group.iloc[-1, 3]
                    },
                    index=[group.index[0]]))

    else:
        raise ValueError(
            'Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer'
        )

    # Set plot parameters, including the axis object ax used for plotting
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('730 days'):
        weekFormatter = DateFormatter('%b %d')  # e.g., Jan 12
        ax.xaxis.set_major_locator(mondays)
        ax.xaxis.set_minor_locator(alldays)
    else:
        weekFormatter = DateFormatter('%b %d, %Y')
    ax.xaxis.set_major_formatter(weekFormatter)

    ax.grid(True)

    # Create the candelstick chart
    candlestick_ohlc(ax,
                     list(
                         zip(list(date2num(plotdat.index.tolist())),
                             plotdat["Open"].tolist(),
                             plotdat["High"].tolist(), plotdat["Low"].tolist(),
                             plotdat["Close"].tolist())),
                     colorup="black",
                     colordown="red",
                     width=stick * .4)

    # Plot other series (such as moving averages) as lines
    if otherseries != None:
        if type(otherseries) != list:
            otherseries = [otherseries]
        dat.loc[:, otherseries].plot(ax=ax, lw=1.3, grid=True)

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

    plt.show()
Exemple #57
0
###
# CandleStick chart for Ford in January 2012
###
from matplotlib.finance import candlestick_ohlc
from matplotlib.dates import DateFormatter, date2num, WeekdayLocator, DayLocator, MONDAY

# Rest the index to get a column of January Dates
ford_reset = ford.loc['2012-01':'2012-01'].reset_index()

# Create a new column of numerical "date" values for matplotlib to use
ford_reset['date_ax'] = ford_reset['Date'].apply(lambda date: date2num(date))
ford_values = [
    tuple(vals)
    for vals in ford_reset[['date_ax', 'Open', 'High', 'Low', 'Close']].values
]

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

#Plot it
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_ohlc(ax, ford_values, width=0.6, colorup='g', colordown='r')
plt.show()
Exemple #58
0
def DrawChart(df, tblname, StockHis, outputpath, ChartLen=240):
    fig = plt.figure(figsize=(12, 6))
    ax1 = plt.subplot2grid((6, 3), (0, 0), colspan=3, rowspan=3)
    sellType = {'DongDa': 'k*', 'WDa': 'b*', 'SAR': 'r*', 'KeyKbar': 'g*'}
    ohlc = []
    SellList = {}
    BuyList = []
    dropLen = len(df)
    RS = Resistance_Support(df)
    df['P_60'] = TAI.MA(df['Close'], 60)
    df['P_120'] = TAI.MA(df['Close'], 120)
    df['P_240'] = TAI.MA(df['Close'], 240)
    df['P_20'] = TAI.MA(df['Close'], 20)
    df['P_10'] = TAI.MA(df['Close'], 10)
    df['P_5'] = TAI.MA(df['Close'], 5)
    df['V_5'] = TAI.MA(df['Volume'] / 1000, 5)
    df['V_10'] = TAI.MA(df['Volume'] / 1000, 10)
    df['V_20'] = TAI.MA(df['Volume'] / 1000, 20)
    df = TAI.VMACD(df, 12, 26, nsig=9)
    if dropLen > ChartLen:
        dropLen -= ChartLen
        df = df.drop(df.index[0:dropLen])
        df.reset_index(inplace=True, drop=True)
    x = 0
    y = len(df)

    while x < y:
        append_me = x, df['Open'][x], df['High'][x], df['Low'][x], df['Close'][
            x], df['Volume'][x]
        ohlc.append(append_me)
        if df['TradeDate'][x] in StockHis['Buy']:
            BuyList.append([x, df['Low'][x] * 0.99])
        if df['TradeDate'][x] in StockHis['Sell']:
            modepercent = 0.99
            for method in StockHis['Sell'][df['TradeDate'][x]]:
                if method not in SellList:
                    SellList[method] = []
                SellList[method].append([x, df['Low'][x] * modepercent])
                modepercent -= 0.01
        x += 1
    limitY = [np.nanmin(df['P_5'].values), np.nanmax(df['Close'].values)]

    BuyList = zip(*BuyList)

    for rs in zip(*RS):
        x = rs[0] - dropLen
        if rs[1] >= df['Low'][y - 1]:
            ax1.plot([x, y], [rs[1], rs[1]], 'r-', linewidth=0.8)
        else:
            ax1.plot([x, y], [rs[1], rs[1]], 'b-', linewidth=0.5)

    candlestick_ohlc(ax1,
                     ohlc,
                     width=0.4,
                     colorup='#db3f3f',
                     colordown='#77d879')
    X = [i for i in range(y)]
    ax1.plot(X, df['P_60'], 'c-', linewidth=1)
    ax1.plot(X, df['P_120'], 'm-', linewidth=1)
    ax1.plot(X, df['P_240'], 'y-', linewidth=1)
    ax1.plot(X, df['P_20'], 'k-', linewidth=1)
    ax1.plot(X, df['P_10'], 'k-', linewidth=1)
    ax1.plot(X, df['P_5'], 'k-', linewidth=1)
    MSP = [[], []]
    for i in [5, 10, 20, 60, 120]:
        try:
            MSP[1].append(df['Close'][y - i])
            MSP[0].append(y - i)
        except:
            print y, i

    ax1.plot(MSP[0], MSP[1], "k.")
    if BuyList:
        ax1.plot(BuyList[0], BuyList[1], 'b*')
    if SellList:
        for method in SellList:
            data = zip(*SellList[method])
            ax1.plot(data[0], data[1], sellType[method])

    ax1.grid(True)
    pad = 0.25
    ax1.set_ylim(limitY[0] - (limitY[1] - limitY[0]) * pad, limitY[1] * 1.05)
    ax2 = ax1.twinx()
    ax2.bar(X,
            df['Volume'] / 1000,
            color='green',
            width=1,
            align='center',
            linewidth=1)
    ax2.plot(X, df['V_5'], 'b-', linewidth=1)
    ax2.plot(X, df['V_10'], 'm-', linewidth=1)
    ax2.plot(X, df['V_20'], 'y-', linewidth=1)
    plt.title(tblname, loc='left')
    yticks = ax2.get_yticks()
    ax2.set_yticks(yticks[::3])
    ax2.yaxis.set_label_position("right")
    ax2.set_ylim(0, ax2.get_ylim()[1] * 4)
    ax3 = plt.subplot2grid((6, 3), (3, 0), colspan=3, sharex=ax1)
    ##    ax3.bar(X,df['D_K_9']-df['D_D_9'],color='k',width=1,align='center', linewidth=1)
    ##    ax4 = ax3.twinx()
    ax3.plot(X, df['D_K_9'], 'b-', linewidth=2)
    ylimit = max([abs(ax3.get_ylim()[0]), abs(ax3.get_ylim()[1])])
    ax3.set_ylim(-ylimit, ylimit)
    [Support, Resistance] = TurnJoint(df['D_K_9'], 7, [0, 95])
    for i in range(1, len(Support[1])):
        if Support[1][i] > Support[1][i - 1]:
            y = (Support[1][i] -
                 Support[1][i - 1]) / (Support[0][i] - Support[0][i - 1]) * (
                     Support[0][i + 1] - Support[0][i - 1]) + Support[1][i - 1]
            ax3.plot([Support[0][i - 1], Support[0][i + 1]],
                     [Support[1][i - 1], y],
                     'r-',
                     linewidth=1)
            ax3.plot([Support[0][i - 1], Support[0][i]],
                     [Support[1][i - 1], Support[1][i]],
                     'r.',
                     linewidth=1)
    for i in range(1, len(Resistance[1])):
        if Resistance[1][i] < Resistance[1][i - 1]:
            y = (Resistance[1][i] - Resistance[1][i - 1]) / (
                Resistance[0][i] - Resistance[0][i - 1]) * (Resistance[0][
                    i + 1] - Resistance[0][i - 1]) + Resistance[1][i - 1]
            ax3.plot([Resistance[0][i - 1], Resistance[0][i + 1]],
                     [Resistance[1][i - 1], y],
                     'g-',
                     linewidth=1)
            ax3.plot([Resistance[0][i - 1], Resistance[0][i]],
                     [Resistance[1][i - 1], Resistance[1][i]],
                     'g.',
                     linewidth=1)
##    ax4.plot(X, TAI.MA(df['D_K_9'], 5).diff(5),'m-',linewidth=1)

    plt.ylabel('P KD', fontsize=8)
    ax3.set_ylim(0, 100)

    ax5 = plt.subplot2grid((6, 3), (4, 0), colspan=3, sharex=ax1)
    ax5.bar(X,
            df["D_DIFF_12_26"] - df["D_MACD_9"],
            color='k',
            width=1,
            align='center',
            linewidth=1)

    ax5.plot(X, df["D_DIFF_12_26"], 'b-', linewidth=2)
    [Support, Resistance] = TurnJoint(df["D_DIFF_12_26"], 5)
    ax5.set_ylim(ax5.get_ylim()[0], ax5.get_ylim()[1])
    for i in range(1, len(Support[1])):
        if Support[1][i] > Support[1][i - 1]:
            y = (Support[1][i] -
                 Support[1][i - 1]) / (Support[0][i] - Support[0][i - 1]) * (
                     Support[0][i + 1] - Support[0][i - 1]) + Support[1][i - 1]
            ax5.plot([Support[0][i - 1], Support[0][i + 1]],
                     [Support[1][i - 1], y],
                     'r-',
                     linewidth=1)
            ax5.plot([Support[0][i - 1], Support[0][i]],
                     [Support[1][i - 1], Support[1][i]],
                     'r.',
                     linewidth=1)
    for i in range(1, len(Resistance[1])):
        if Resistance[1][i] < Resistance[1][i - 1]:
            y = (Resistance[1][i] - Resistance[1][i - 1]) / (
                Resistance[0][i] - Resistance[0][i - 1]) * (Resistance[0][
                    i + 1] - Resistance[0][i - 1]) + Resistance[1][i - 1]
            ax5.plot([Resistance[0][i - 1], Resistance[0][i + 1]],
                     [Resistance[1][i - 1], y],
                     'g-',
                     linewidth=1)
            ax5.plot([Resistance[0][i - 1], Resistance[0][i]],
                     [Resistance[1][i - 1], Resistance[1][i]],
                     'g.',
                     linewidth=1)
    plt.ylabel('P MACD', fontsize=8)

    ax7 = plt.subplot2grid((6, 3), (5, 0), colspan=3, sharex=ax1)
    ax7.bar(X, df['VOSC'], color='k', width=1, align='center', linewidth=1)
    ax7.plot(X, df['VDIFF'], 'b-', linewidth=2)
    ##    ylimit= max([abs(ax7.get_ylim()[0]),abs(ax7.get_ylim()[1])])
    ax7.set_ylim(ax7.get_ylim()[0], ax7.get_ylim()[1])
    [Support, Resistance] = TurnJoint(df['VDIFF'], 5)
    for i in range(1, len(Support[1])):
        if Support[1][i] > Support[1][i - 1]:
            y = (Support[1][i] -
                 Support[1][i - 1]) / (Support[0][i] - Support[0][i - 1]) * (
                     Support[0][i + 1] - Support[0][i - 1]) + Support[1][i - 1]
            ax7.plot([Support[0][i - 1], Support[0][i + 1]],
                     [Support[1][i - 1], y],
                     'r-',
                     linewidth=1)
            ax7.plot([Support[0][i - 1], Support[0][i]],
                     [Support[1][i - 1], Support[1][i]],
                     'r.',
                     linewidth=1)
    for i in range(1, len(Resistance[1])):
        if Resistance[1][i] < Resistance[1][i - 1]:
            y = (Resistance[1][i] - Resistance[1][i - 1]) / (
                Resistance[0][i] - Resistance[0][i - 1]) * (Resistance[0][
                    i + 1] - Resistance[0][i - 1]) + Resistance[1][i - 1]
            ax7.plot([Resistance[0][i - 1], Resistance[0][i + 1]],
                     [Resistance[1][i - 1], y],
                     'g-',
                     linewidth=1)
            ax7.plot([Resistance[0][i - 1], Resistance[0][i]],
                     [Resistance[1][i - 1], Resistance[1][i]],
                     'g.',
                     linewidth=1)

    plt.ylabel('V MACD', fontsize=8)

    ax1.set_xlim(X[0], X[-1] + 2)
    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.setp(ax3.get_xticklabels(), visible=False)
    plt.setp(ax5.get_xticklabels(), visible=False)

    plt.tight_layout()
    plt.savefig(os.path.join(outputpath, tblname + '.jpg'))
    plt.close()
def animate(i):
    global refreshRate
    global DatCounter

    if chartLoad:
        if paneCount == 1:
            if DataPace == "tick":
                try:

                    if exchange == "Bitfinex":

                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        #say full grid size (as tuple), then starting point(as tuple), then dimensions
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)
                        #sharex aligns the 2 plots if you zoom or move around

                        dataLink = 'https://api.bitfinex.com/v1/trades/BTCUSD?limit=2000'
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        data = pd.DataFrame(data)

                        data["datestamp"] = np.array(data["timestamp"]).astype(
                            "datetime64[s]")  #converting datatypes
                        allDates = data["datestamp"].tolist()

                        buys = data[(data['type'] == "buy")]
                        ##                    buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
                        buyDates = (buys["datestamp"]).tolist()

                        sells = data[(data['type'] == "sell")]  #same for sells
                        ##                    sells["datestamp"] = np.array(sells["timestamp"]).astype("datetime64[s]")
                        sellDates = (sells["datestamp"]).tolist()

                        volume = data["amount"].apply(float).tolist()

                        a.clear()
                        a.plot_date(buyDates,
                                    buys["price"],
                                    lightColor,
                                    label="buys")
                        a.plot_date(sellDates,
                                    sells["price"],
                                    darkColor,
                                    label="sells")

                        a2.fill_between(
                            allDates, 0, volume,
                            facecolor=darkColor)  #adding a volume plot

                        a.xaxis.set_major_locator(
                            mticker.MaxNLocator(5)
                        )  #sets the maximum amount of marks on the x axis (major gridlines)
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        plt.setp(a.get_xticklabels(), visible=False
                                 )  #Removes x axis labels from top plot

                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)

                        title = "Bitfinex BTCUSD Prices\nLast Price: " + str(
                            data["price"][0])
                        a.set_title(title)
                        priceData = data["price"].apply(float).tolist()

                    if exchange == "Bitstamp":

                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=5,
                                             colspan=4)
                        #say full grid size (as tuple), then starting point(as tuple), then dimensions
                        a2 = plt.subplot2grid((6, 4), (5, 0),
                                              rowspan=1,
                                              colspan=4,
                                              sharex=a)
                        #sharex aligns the 2 plots if you zoom or move around

                        dataLink = 'https://www.bitstamp.net/api/transactions/'
                        data = urllib.request.urlopen(dataLink)
                        data = data.read().decode("utf-8")
                        data = json.loads(data)

                        data = pd.DataFrame(data)

                        data["datestamp"] = np.array(
                            data["date"].apply(int)).astype(
                                "datetime64[s]")  #converting datatypes
                        dateStamps = data["datestamp"].tolist()
                        ##                        allDates = data["datestamp"].tolist()

                        ##                        buys = data[(data['type']=="buy")]
                        ##    ##                    buys["datestamp"] = np.array(buys["timestamp"]).astype("datetime64[s]")
                        ##                        buyDates = (buys["datestamp"]).tolist()
                        ##
                        ##                        sells = data[(data['type']=="sell")] #same for sells
                        ##    ##                    sells["datestamp"] = np.array(sells["timestamp"]).astype("datetime64[s]")
                        ##                        sellDates = (sells["datestamp"]).tolist()

                        volume = data["amount"].apply(float).tolist()

                        a.clear()
                        a.plot_date(dateStamps,
                                    data["price"],
                                    lightColor,
                                    label="buys")

                        a2.fill_between(
                            dateStamps, 0, volume,
                            facecolor=darkColor)  #adding a volume plot

                        a.xaxis.set_major_locator(
                            mticker.MaxNLocator(5)
                        )  #sets the maximum amount of marks on the x axis (major gridlines)
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
                        plt.setp(a.get_xticklabels(), visible=False
                                 )  #Removes x axis labels from top plot

                        a.legend(bbox_to_anchor=(0, 1.02, 1, .102),
                                 loc=3,
                                 ncol=2,
                                 borderaxespad=0)

                        title = "Bitstamp BTCUSD Prices\nLast Price: " + str(
                            data["price"][0])
                        a.set_title(title)
                        priceData = data["price"].apply(float).tolist()

                    if exchange == "Huobi":

                        a = plt.subplot2grid((6, 4), (0, 0),
                                             rowspan=6,
                                             colspan=4)
                        data = urllib.request.urlopen(
                            'http://seaofbtc.com/api/basic/price?key=1&tf=1d&exchange='
                            + programName).read()
                        data = data.decode()

                        data = json.loads(data)

                        dateStamp = np.array(data[0]).astype("datetime64[s]")
                        dateStamp = dateStamp.tolist()

                        df = pd.DataFrame({"Datetime": dateStamp})
                        df['Price'] = data[1]
                        df['Volume'] = data[2]
                        df['Symbol'] = "BTCUSD"

                        df['MPLDate'] = df["Datetime"].apply(
                            lambda date: mdates.date2num(date.to_pydatetime()))

                        df = df.set_index("Datetime")

                        lastPrice = df["Price"][-1]

                        a.plot_date(df["MPLDate"][-4500:],
                                    df["Price"][-4500:],
                                    lightColor,
                                    label="Price")

                        a.xaxis.set_major_locator(
                            mticker.MaxNLocator(5)
                        )  #sets the maximum amount of marks on the x axis (major gridlines)
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))

                        title = "Huobi BTCUSD Prices\nLast Price: " + str(
                            lastPrice)
                        a.set_title(title)

                        priceData = df["price"].apply(float).tolist()

                except Exception as e:  #Saves the exception text to e
                    print("Failed because of:", e)

            else:
                if DatCounter > 12:  # 12 is some magic number
                    try:
                        #Setting up the subplots for the non-tick data
                        if exchange == "Huobi":
                            if topIndicator != "none":
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=5,
                                                     colspan=4)
                                a2 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            else:
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=5,
                                                     colspan=4)

                        else:
                            if topIndicator != "none" & bottomIndicator != "none":

                                #Main Graph
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=3,
                                                     colspan=4)

                                #Volume
                                a2 = plt.subplot2grid((6, 4), (4, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                                #Bottom Indicator
                                a3 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                                #Top Indicator
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            elif topIndicator != "none":  #We know there will be no bottom indicator if this is true, following the above if statement being false

                                #Main Graph
                                a = plt.subplot2grid((6, 4), (1, 0),
                                                     rowspan=4,
                                                     colspan=4)

                                #Volume
                                a2 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                                #Top Indicator
                                a0 = plt.subplot2grid((6, 4), (0, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            elif bottomIndicator != "none":

                                #Main Graph
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=4,
                                                     colspan=4)

                                #Volume
                                a2 = plt.subplot2grid((6, 4), (4, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                                #Bottom Indicator
                                a3 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                            else:

                                #Main Graph
                                a = plt.subplot2grid((6, 4), (0, 0),
                                                     rowspan=5,
                                                     colspan=4)

                                #Volume
                                a2 = plt.subplot2grid((6, 4), (5, 0),
                                                      sharex=a,
                                                      rowspan=1,
                                                      colspan=4)

                        data = urllib.request.urlopen(
                            "http://seaofbtc.com/api/basic/price?key=1&tf=" +
                            str(DataPace) + "&exchange=" +
                            str(programName)).read()
                        data = data.decode()
                        data = json.loads(data)

                        dateStamp = np.array(data[0]).astype(
                            "datetime64[s]"
                        )  #taking the 0th list withing the array "data" (list within a list)
                        dateStamp = dateStamp.tolist()

                        df = pd.DataFrame({"Datetime": dateStamp})
                        #defining the columns of the dataframe
                        df["Price"] = data[1]
                        df["Volume"] = data[2]
                        df["Symbol"] = "BTCUSD"
                        df["MPLDate"] = df["Datetime"].apply(
                            lambda date: mdates.date2num(date.to_pydatetime()))
                        df = df.set_index("Datetime")

                        OHLC = df["Price"].resample(
                            resampleSize, how="ohlc"
                        )  #resampling is built into pandas. Can resample based on criteria you want
                        #resampleSize is defined by us at the top. OHLC is built in to Pandas

                        OHLC = OHLC.dropna()  #gets rid of NaN elements

                        volumeData = df["Volume"].resample(
                            resampleSize, how={"volume": "sum"})
                        #adds all the volume data together

                        OHLC["dateCopy"] = OHLC.index
                        OHLC["MPLDates"] = OHLC["dateCopy"].apply(
                            lambda date: mdates.date2num(date.to_pydatetime()))

                        del OHLC["dateCopy"]

                        volumeData["dateCopy"] = volumeData.index
                        volumeData["MPLDates"] = volumeData["dateCopy"].apply(
                            lambda date: mdates.date2num(date.to_pydatetime()))

                        del volumeData["dateCopy"]

                        priceData = OHLC["close"].apply(float).tolist()

                        a.clear()

                        if middleIndicator != "none":
                            for eachMA in middleIndicator:
                                #ewma = pd.stats.moments.ewma
                                if eachMA[0] == "sma":
                                    sma = pd.rolling_mean(
                                        OHLC["close"], eachMA[1]
                                    )  #The middleIndicator list has several smaller lists with 0th element = ema/sma and the 1st element equal a number
                                    label = str(eachMA[1]) + " SMA"
                                    a.plot(OHLC["MPLDates"], sma, label=label)

                                if eachMA[0] == "ema":
                                    ewma = pd.stats.moments.ewma
                                    label = str(eachMA[1]) + " EMA"
                                    a.plot(OHLC["MPLDates"],
                                           ewma(OHLC["close"], eachMA[1]),
                                           label=label)

                            a.legend(loc=0)

                        if topIndicator[0] == "rsi":
                            rsiIndicator(priceData, "top")

                        elif topIndicator == "macd":
                            try:
                                computeMACD(priceData, location="top")

                            except Exception as e:
                                print(str(e))

                        if topIndicator[0] == "rsi":
                            rsiIndicator(priceData, "bottom")

                        elif bottomIndicator == "macd":
                            try:
                                computeMACD(priceData, location="bottom")

                            except Exception as e:
                                print(str(e))

                        csticks = candlestick_ohlc(
                            a,
                            OHLC[["MPLDates", "open", "high", "low",
                                  "close"]].values,
                            width=candleWidth,
                            colorup=lightColor,
                            colordown=darkColor)
                        a.set_ylabel("Price")
                        if exchange != "Huobi":  #Huobi doesn't give volume data
                            a2.fill_between(volumeData["MPLDates"],
                                            0,
                                            volumeData["volume"],
                                            faceColor=darkColor)
                            a2.set_ylabel("Volume")

                        a.xaxis.set_major_locator(mticker.MaxNLocator(3))
                        a.xaxis.set_major_formatter(
                            mdates.DateFormatter("%Y-%m-%d %H:%M"))

                        if exchange != "Huobi":
                            plt.setp(a.get_xticklabels(), visible=False)

                        if topIndicator != "none":
                            plt.setp(a0.get_xticklabels(), visible=False)

                        if bottomIndicator != "none":
                            plt.setp(a2.get_xticklabels(), visible=False)

                        x = (
                            len(OHLC['close'])
                        ) - 1  #x is the element ID of the alst element in the list

                        if DataPace == "1d":
                            title = exchange + " 1 Day Data with " + resampleSize + " Bars\nLast Price: " + str(
                                OHLC["close"][x])
                        if DataPace == "3d":
                            title = exchange + " 3 Day Data with " + resampleSize + " Bars\nLast Price: " + str(
                                OHLC["close"][x])
                        if DataPace == "7d":
                            title = exchange + " 7 Day Data with " + resampleSize + " Bars\nLast Price: " + str(
                                OHLC["close"][x])

                        if topIndicator != "none":
                            a0.set_title(title)
                        else:
                            a.set_title(title)

                        print("New Graph!")

                        DatCounter = 0

                    except Exception as e:
                        print('Failed in the non-tick animate:' + str(e))
                        DatCounter = 9000

                else:
                    DatCounter += 1
def graph_data(stock):

    fig = plt.figure(facecolor='#f0f0f0')

    ax1 = plt.subplot2grid((6, 1), (0, 0), rowspan=1, colspan=1)
    plt.title(stock)
    plt.ylabel('H-L')
    ax2 = plt.subplot2grid((6, 1), (1, 0), rowspan=4, colspan=1, sharex=ax1)
    plt.ylabel('Price')
    ax2v = ax2.twinx()
    ax3 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1, sharex=ax1)
    plt.xlabel('Date')
    plt.ylabel('MAvgs')

    url = 'http://chartapi.finance.yahoo.com/instrument/1.0/' + stock + '/chartdata;type=quote;range=1y/csv'
    request = urllib.request.urlopen(url).read().decode()
    stock_data = []
    split_source = request.split('\n')
    for line in split_source:
        split_line = line.split(',')
        if len(split_line) == 6:
            if 'values' not in line:
                stock_data.append(line)

    # unix time converter
    '''            
    date, closep, highp, lowp, openp, volume = np.loadtxt(stock_data,
                                                          delimiter=',',
                                                          unpack=True)
     
    dateconv = np.vectorize(dt.datetime.fromtimestamp)
    date = dateconv(date)
    '''

    date, closep, highp, lowp, openp, volume = np.loadtxt(
        stock_data,
        delimiter=',',
        unpack=True,
        # %Y = full year 2016
        # %y = partial year 16
        # %m = number month
        # %d = number day
        # %H = hours
        # %M = minutes
        # %S = seconds
        # 12-06-2014
        # %m-%d-%Y
        converters={0: bytespdate2num('%Y%m%d')})

    ma1 = moving_average(closep, MA1)
    ma2 = moving_average(closep, MA2)
    start = len(date[MA2 - 1:])

    h_l = list(map(high_minus_low, highp, lowp))

    ax1.plot_date(date[-start:],
                  h_l[-start:],
                  '-',
                  c='#0000C6',
                  linewidth=2,
                  label='H-L')
    ax1.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='lower'))

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

    candlestick_ohlc(ax2,
                     ohlc[-start:],
                     width=0.4,
                     colorup='r',
                     colordown='#3bfb10')

    ax2.yaxis.set_major_locator(mticker.MaxNLocator(nbins=7, prune='upper'))

    bbox_props = dict(boxstyle='round', fc='w', ec='k', lw=1)
    ax2.annotate(str(closep[-1]), (date[-1], closep[-1]),
                 xytext=(date[-1] + 4, closep[-1]),
                 bbox=bbox_props)

    ax2v.fill_between(date[-start:],
                      0,
                      volume[-start:],
                      facecolor='#0079a3',
                      alpha=0.4)
    ax2v.axes.yaxis.set_ticklabels([])
    ax2v.grid(False)
    ax2v.set_ylim(0, 2 * volume.max())
    ax2v.plot([], [], color='#0079a3', alpha=0.4, label='Volume')

    #Annotation example
    '''
    ax1.annotate('Annotate Test!',
                 (date[9], lowp[9]),
                 xytext = (0.8, 0.9),
                 textcoords = 'axes fraction',
                 arrowprops = dict(color = 'gray'))
    '''

    #Text and fontdict example
    '''
    font_dict = {'family':'serif',
                 'color':'darkred',
                 'size':15}
    ax1.text(date[10], closep[1], 'Text Example', fontdict = font_dict)
    '''

    #     ax1.plot_date(date, closep, '-', label = 'Price')
    #     ax1.fill_between(date, closep, closep[0], where = (closep > closep[0]), facecolor = 'r', alpha = 0.5, label = 'gain')
    #     ax1.fill_between(date, closep, closep[0], where = (closep < closep[0]), facecolor = 'g', alpha = 0.5, label = 'loss')
    #
    #     #表格邊框
    #     ax1.spines['left'].set_color('r')
    #     ax1.spines['top'].set_visible(False)
    #     ax1.spines['right'].set_visible(False)
    #
    #     #X/Y軸數字參數
    #     ax1.tick_params(axis = 'x', colors = '#A02992')
    #
    #     ax1.axhline(closep[0], color = 'k', linewidth = 3)
    #
    #     for label in ax1.xaxis.get_ticklabels():
    #         label.set_rotation(45)
    #     ax1.grid(True)
    #     ax1.xaxis.label.set_color('r')
    #     ax1.yaxis.label.set_color('g')

    ax3.plot(date[-start:], ma1[-start:], linewidth=1, label=str(MA1) + 'MA')
    ax3.plot(date[-start:], ma2[-start:], linewidth=1, label=str(MA2) + 'MA')

    ax3.yaxis.set_major_locator(mticker.MaxNLocator(nbins=4, prune='upper'))

    ax3.fill_between(date[-start:],
                     ma2[-start:],
                     ma1[-start:],
                     where=(ma1[-start:] > ma2[-start:]),
                     facecolor='g',
                     edgecolor='g',
                     alpha=0.5)
    ax3.fill_between(date[-start:],
                     ma2[-start:],
                     ma1[-start:],
                     where=(ma1[-start:] < ma2[-start:]),
                     facecolor='r',
                     edgecolor='r',
                     alpha=0.5)

    for label in ax3.xaxis.get_ticklabels():
        label.set_rotation(45)
    ax3.xaxis.set_major_formatter(mdates.DateFormatter('%y-%m-%d'))
    ax3.xaxis.set_major_locator(mticker.MaxNLocator(10))

    plt.setp(ax1.get_xticklabels(), visible=False)
    plt.setp(ax2.get_xticklabels(), visible=False)
    plt.grid(True)
    ax1.legend()
    leg = ax1.legend(loc=9, ncol=1, prop={'size': 11})
    leg.get_frame().set_alpha(0.4)
    ax2v.legend(loc=9, ncol=1, prop={'size': 11}).get_frame().set_alpha(0.4)
    ax3.legend(loc=9, ncol=2, prop={'size': 11}).get_frame().set_alpha(0.4)
    plt.subplots_adjust(right=0.87, left=0.1, bottom=0.2, top=0.95)
    plt.show()
    fig.savefig(stock, facecolor=fig.get_facecolor())