def __init__(self): company = "GOOG" startDate = (1992, 1, 1) endDate = (2014, 10, 17) # First chart data quotes = quotes_historical_yahoo_ohlc(company, startDate, endDate) if len(quotes) == 0: raise SystemExit # Second chart data dates = ValuesParser.getValues(quotes, "date") openValues = ValuesParser.getValues(quotes, "open") closeValues = ValuesParser.getValues(quotes, "close") highValues = ValuesParser.getValues(quotes, "high") lowValues = ValuesParser.getValues(quotes, "low") volumeValues = ValuesParser.getValues(quotes, "volume") predictedOpenValues = AutoRegression.calculateEstimation(openValues, AutoRegression.calculateARCoefficients(openValues, 5)) predictedCloseValues = AutoRegression.calculateEstimation(openValues, AutoRegression.calculateARCoefficients(closeValues, 5)) predictedHighValues = AutoRegression.calculateEstimation(openValues, AutoRegression.calculateARCoefficients(highValues, 5)) predictedLowValues = AutoRegression.calculateEstimation(openValues, AutoRegression.calculateARCoefficients(lowValues, 5)) predictedVolumeValues = AutoRegression.calculateEstimation(openValues, AutoRegression.calculateARCoefficients(volumeValues, 5)) predictedQuotes = ValuesParser.getQuotes(dates, predictedOpenValues, predictedCloseValues, predictedHighValues, predictedLowValues, predictedVolumeValues) """ L'algorithme utilisant les 5 premières valeurs pour en déduire les 5 suivantes, les 5 premières valeurs des prévisions sont fatalement nulles. Pour ne pas avoir le même résultat que le screenshot du mail, (l'échelle changeante à cause des valeurs nulles) j'ai copié les premières valeurs pour avoir une meilleure lisibilité """ predictedQuotes[0:5] = quotes[0:5] # Charts CandleStickChart("Cotations", quotes) CandleStickChart("Prévisions", predictedQuotes)
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()
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()
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 ret_f(ticker, begdate, enddate): p = quotes_historical_yahoo_ohlc(ticker, begdate, enddate, asobject=True, adjusted=True) return ((p.open[1:] - p.open[:-1]) / p.open[1:])
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()
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 ret_annual(ticker,begtime,endtime): x = quotes_historical_yahoo_ohlc(ticker,begtime,endtime,asobject=True,adjusted=True) logret = np.log(x.aclose[1:]/x.aclose[:-1]) date = [] for i in np.arange(len(x)-1): date.append(x.date[i+1].strftime("%Y")) #wrong: date=date.append() ret = pd.DataFrame(logret,date,columns=[ticker]) return np.exp(ret.groupby(ret.index).sum())-1
def redraw(self): self._axes.clear() if self._instrument != None: try: fh = finance.quotes_historical_yahoo_ohlc( self._instrument, self._startingTimestamp, self._endTimestamp) prices = fh finance.candlestick_ohlc(self._axes, prices, width=0.6) self._canvas.draw() except Exception: print("Couldn't find symbol")
def read(self, stock_name): start = (2011, 12, 1) end = (2016, 12, 1) try: quotes = quotes_historical_yahoo_ohlc(stock_name, start, end) if len(quotes) == 0: raise SystemExit except: quotes = [] for i in range(0, len(quotes)): self.insert(quotes[i][0], quotes[i][1], quotes[i][2], quotes[i][3], quotes[i][4], quotes[i][5])
def month_ret(ticker, begtime, endtime): prices = quotes_historical_yahoo_ohlc(ticker, begtime, endtime, asobject=True, adjusted=True) log_ret = np.log(prices.aclose[1:] / prices.aclose[:-1]) month_date = [] for i in np.arange(len(log_ret)): month_date.append(prices.date[i + 1].strftime('%Y%m')) log_ret_df = pd.DataFrame(data=log_ret, index=month_date, columns=[ticker]) return np.exp(log_ret_df.groupby(log_ret_df.index).sum()) - 1
def monthly_ret(ticker, begtime, endtime): p = quotes_historical_yahoo_ohlc(ticker, begtime, endtime, asobject=True, adjusted=True) date = [] for i in np.arange(len(p.date) - 1): date.append(p.date[i + 1].strftime("%Y%m")) logret = np.log(p.aclose[1:] / p.aclose[:-1]) ret = pd.DataFrame(logret, date, columns=[ticker]) return np.exp(ret.groupby(ret.index).sum()) - 1
def matplot_finance(): start = (2014, 5, 1) end = (2014, 6, 30) pdb.set_trace() quotes = mpf.quotes_historical_yahoo_ohlc('DIA', start, end) fig, ax = plt.subplots(figsize=(8, 5)) fig.subplots_adjust(bottom=0.2) mpf.candlestick_ohlc(ax, quotes, width=0.6, colorup='b', colordown='r') plt.grid(True) ax.xaxis_date() ax.autoscale_view() # Rotate labels by 30 degrees plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.savefig(PATH + 'candle.png', dpi=300) plt.close() fig, ax = plt.subplots(figsize=(8, 5)) mpf.plot_day_summary_ohlc(ax, quotes, colorup='b', colordown='r') plt.grid(True) ax.xaxis_date() plt.title('DAX Index') plt.ylabel('index level') plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.savefig(PATH + 'plot_day_sum.png', dpi=300) plt.close() quotes = np.array(mpf.quotes_historical_yahoo_ohlc('YHOO', start, end)) fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(8, 6)) mpf.candlestick_ohlc(ax1, quotes, width=0.6, colorup='b', colordown='r') ax1.set_title('Yahoo Inc.') ax1.set_ylabel('Index Level') ax1.grid(True) ax1.xaxis_date() plt.bar(quotes[:, 0] - 0.25, quotes[:, 5], width=0.5) ax2.set_ylabel('volume') ax2.grid(True) ax2.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=30) plt.savefig(PATH + 'candle2plot.png', dpi=300) plt.close()
def LPSD(ticker,begtime,endtime): p=quotes_historical_yahoo_ohlc(ticker,begtime,endtime,asobject=True, adjusted=True) ff=pd.read_pickle('ffDaily.pickle') ret=(p.aclose[1:]-p.aclose[:-1])/p.aclose[1:] print(ff) print(ret) print(p.date[1:]) x=pd.DataFrame(ret,p.date[1:],columns=['ret']) print(x) final=pd.merge(x,ff,left_index=True,right_index=True) print(final) k=final.ret-final.Rf k1=k[k>0] return np.std(k1)*np.sqrt(252)
def out_put(stock, str1, str2): data = quotes_historical_yahoo_ohlc(stock, str2date(str1), str2date(str2)) if len(data) == 0: raise SystemExit print len(data) output = list() for item in data: temp = str(num2date(item[0])) temp2 = temp[:-6] o = list() o.append(temp2) for i in range(1, len(item)-1): o.append(item[i]) output.append(o) return output
def pltPoly(symbol = 'DISH'): today = date.today() start = (today.year - 1, today.month, today.day) month_formatter = DateFormatter("%b %Y") alldays = DayLocator() months = MonthLocator() quotes = quotes_historical_yahoo_ohlc(symbol, start, today) fig = plt.figure() ax = fig.add_subplot(111) ax = plt.subplot(111) ax.xaxis.set_major_locator(months) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(month_formatter) candlestick_ohlc(ax, quotes) fig.autofmt_xdate() plt.show()
def myplot_candlestick(ticker, weeks): start = datetime.date.today() + datetime.timedelta(days=-weeks*7) quotes = quotes_historical_yahoo_ohlc(ticker, start, datetime.date.today()) fig = plt.figure() ax = plt.axes() candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y/%m')) fig.autofmt_xdate() ax.set_title(ticker) sht = xw.Book.caller().sheets.active sht.pictures.add(fig, name='52W', update=True, left=sht.range('B5').left, top=sht.range('B5').top) return str(int(weeks))+'W Candlestick Plot'
def plotStockHist(stockCode, startDate, endDate): # startDate, endDate required as tuples in format (Year, month, day) to work with quotes_historical_yahoo 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(stockCode, startDate, endDate) if len(quotes) != 0: #do stuff 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.ylabel('Stock Price') startDateStr = str(startDate[2]) + "/" + str(startDate[1]) + "/" + str( startDate[0]) endDateStr = str(endDate[2]) + "/" + str(endDate[1]) + "/" + str( endDate[0]) plt.xlabel("period " + startDateStr + " to " + endDateStr) plt.title("Stock Code:" + stockCode) plt.savefig("candleStickChart.png") #plt.show() else: #error, exit gracefully. print("no history found, no chart plotted.")
def pandas_simple_candlestick_ohlc(): # 开始时间 start = datetime.datetime(2017, 1, 1) # 结束时间 end = datetime.date.today() # 沪市 ticker_ss = '600000.ss' # 深市 ticker_sz = '000001.sz' # 港股 ticker_hk = '0700.hk' # 获取数据 quotes = quotes_historical_yahoo_ohlc(ticker_sz, start, end) fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) # 设置主要刻度的显示格式 weekFormatter = DateFormatter('%m-%d-%Y') ax.xaxis.set_major_formatter(weekFormatter) # 设置主要刻度Locator,将major ticks设在星期一 mondays = WeekdayLocator(MONDAY) ax.xaxis.set_major_locator(mondays) # 设置次要刻度Locator,将minor ticks设在每日 alldays = DayLocator() ax.xaxis.set_minor_locator(alldays) # 注意,ohlc代表o开盘价、h最高价、l最低价、c收盘价 candlestick_ohlc(ax, quotes, width=0.6, colorup='r', colordown='g') ax.grid(True) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right') plt.show()
from matplotlib.finance import quotes_historical_yahoo_ohlc import sys from datetime import date import matplotlib.pyplot as plt import numpy as np # (1) 下载一年以来的数据: today = date.today() start = (today.year - 1, today.month, today.day) symbol = 'DISH' if len(sys.argv) == 2: symbol = sys.argv[1] quotes = quotes_historical_yahoo_ohlc(symbol, start, today) # (2) 上一步得到的股价数据存储在Python列表中。将其转化为NumPy数组并提取出收盘价数据: quotes = np.array(quotes) close = quotes.T[4] # (3) 指定合理数量的柱形,绘制分布直方图: plt.hist(close, np.sqrt(len(close))) plt.show()
# -*- coding: utf-8 -*- """ Created on Mon Jul 11 22:04:18 2016 @author: Administrator """ from matplotlib.finance import quotes_historical_yahoo_ohlc from datetime import date import pandas as pd today=date.today(); start=(today.year-1,today.month,today.day) quotes=quotes_historical_yahoo_ohlc('AAPL',start,today) df=pd.DataFrame(quotes) print df
from matplotlib.colors import colorConverter from matplotlib.lines import Line2D, TICKLEFT, TICKRIGHT from matplotlib.patches import Rectangle from matplotlib.transforms import Affine2D if __name__ == '__main__': starttime = dt.date(2015,1,1) endtime = dt.date.today() ticker = 'SPY' fh = mpf.fetch_historical_yahoo(ticker, starttime, endtime) r = mlab.csv2rec(fh); fh.close() r.sort() df = pd.DataFrame.from_records(r) quotes = mpf.quotes_historical_yahoo_ohlc(ticker, starttime, endtime) fig, (ax1, ax2) = plt.subplots(2, sharex=True) tdf = df.set_index('date') cdf = tdf['close'] cdf.plot(label = "close price", ax=ax1) pd.rolling_mean(cdf, window=30, min_periods=1).plot(label = "30-day moving averages", ax=ax1) pd.rolling_mean(cdf, window=10, min_periods=1).plot(label = "10-day moving averages", ax=ax1) ax1.set_xlabel(r'Date') ax1.set_ylabel(r'Price') ax1.grid(True) props = font_manager.FontProperties(size=10) leg = ax1.legend(loc='lower right', shadow=True, fancybox=True, prop=props) leg.get_frame().set_alpha(0.5) ax1.set_title('%s Daily' % ticker, fontsize=14) mpf.candlestick_ohlc(ax2, quotes, width=0.6) ax2.set_ylabel(r'Price')
label.set_rotation(45) plt.setp(plt_sh.get_xticklabels(),visible = True) fig.autofmt_xdate() plt.title(u'sh000001') plt.show() ## get data from yahoo ticker = '600028' # 600028 是"中国石化"的股票代码 ticker += '.ss' # .ss 表示上证 .sz表示深证 date1 = (2015, 8, 1) # 起始日期,格式:(年,月,日)元组 date2 = (2016, 1, 1) # 结束日期,格式:(年,月,日)元组 quotes = mfinance.quotes_historical_yahoo_ohlc(ticker, date1, date2) ## 蜡烛图 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))
import numpy as np import matplotlib.pylab as plt import matplotlib.finance as mpf import pandas from sklearn.linear_model import LinearRegression start = (2013, 1, 1) end = (2016, 1, 1) # ohcl = open, high, low, close quotes = mpf.quotes_historical_yahoo_ohlc('GOOG', start, end) tickerClose = [close[3] for close in quotes] deltaClose = pandas.Series(np.gradient(tickerClose)) #googleDrift = np.polyfit(np.arange(len(tickerClose))/365., np.log10(tickerClose),1) #print googleDrift #plt.plot(np.arange(len(tickerClose)),np.log10(tickerClose)) print tickerClose[0], tickerClose[-1], sum(deltaClose) plt.plot(pandas.rolling_mean(deltaClose, 90)) plt.plot(deltaClose) plt.show()
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator,\ DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc # (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = (2004, 2, 1) date2 = (2004, 4, 12) stockCode = 'INTC' 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(stockCode, 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.xticks(rotation=45) plt.yticks() plt.title("股票代码:601558两年K线图") plt.xlabel("时间") plt.ylabel("股价(元)") mpf.candlestick_ohlc(ax,data_list,width=1.5,colorup='r',colordown='green') plt.grid() ''' import numpy as np import matplotlib as mpl import matplotlib.pyplot as plt import matplotlib.finance as mpf start = (2014, 5, 1) end = (2014, 6, 30) quotes = mpf.quotes_historical_yahoo_ohlc('^GDAXI', start, end) #quotes = mpf.quotes_historical_yahoo(‘^GDAXI’, start, end) quotes[:2] fig, ax = plt.subplots(figsize=(8, 5)) fig.subplots_adjust(bottom=0.2) print "Hello" #use Line2d #mpf.plot_day_summary_oclh(ax, quotes, ticksize=3, colorup=’k’, colordown=’r’)# mpf.candlestick_ohlc(ax, quotes, width=0.6, colorup='b', colordown='r') #mpf.candlestick(ax, quotes, width=0.6, colorup=’b’, colordown=’r’) plt.grid(True) ax.xaxis_date() # dates on the x-axis ax.autoscale_view()
weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 pyplot.style.use('ggplot') fig, ax = pyplot.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) finance.candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() pyplot.setp(pyplot.gca().get_xticklabels(), rotation=45, horizontalalignment='right') pyplot.show() if __name__ == '__main__': # (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = datetime(2004, 2, 1) date2 = datetime(2004, 4, 12) quotes = finance.quotes_historical_yahoo_ohlc('INTC', date1, date2) if len(quotes) == 0: raise SystemExit plot_ohlc(quotes)
""" Crear una gráfica de caja y bigotes para la cotización de un valor en bolsa """ import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator,\ DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc # Extraemos las cotizaciones para las fechas siguientes 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
from matplotlib.dates import DateFormatter, WeekdayLocator,\ 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()
import numpy as np import matplotlib.colors as colors import matplotlib.finance as finance import matplotlib.dates as mdates import matplotlib.ticker as mticker import matplotlib.mlab as mlab import matplotlib.pyplot as plt import matplotlib.font_manager as font_manager startdate = datetime.date(2016, 1, 1) today = enddate = datetime.date.today() ticker = '601231.SS' fh = finance.fetch_historical_yahoo(ticker, startdate, enddate) quotes = finance.quotes_historical_yahoo_ohlc(ticker, startdate, enddate) # a numpy record array with fields: date, open, high, low, close, volume, adj_close) r = mlab.csv2rec(fh) print(quotes[0]) print(r[0]) fh.close() r.sort() def moving_average(x, n, type='simple'): """ compute an n period moving average.
for label in plt_sh.xaxis.get_ticklabels(): label.set_rotation(45) plt.setp(plt_sh.get_xticklabels(), visible=True) fig.autofmt_xdate() plt.title(u"sh000001") plt.show() ## get data from yahoo ticker = "600028" # 600028 是"中国石化"的股票代码 ticker += ".ss" # .ss 表示上证 .sz表示深证 date1 = (2015, 8, 1) # 起始日期,格式:(年,月,日)元组 date2 = (2016, 1, 1) # 结束日期,格式:(年,月,日)元组 quotes = mfinance.quotes_historical_yahoo_ohlc(ticker, date1, date2) ## 蜡烛图 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))
__author__ = 'harsshal' from matplotlib.finance import quotes_historical_yahoo_ohlc date1 = (2010, 12, 31) date2 = (2015, 12, 31) price = quotes_historical_yahoo_ohlc('MSFT', date1, date2) print("hi")
from matplotlib.dates import DateFormatter, WeekdayLocator,\ DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc, plot_day_summary_ohlc %matplotlib inline # (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = (2015, 2, 1) date2 = (2015, 3, 1) 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('GOOG', 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_ohlc(ax, quotes, ticksize=3, colorup=u'g', colordown=u'r') #candlestick_ohlc(ax, quotes, width=0.2, colorup=u'k', colordown=u'r', alpha=1.0) candlestick_ohlc(ax, quotes, width=0.6, colorup=u'g') ax.xaxis_date()
matplotlib.use('TkAgg') import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator,\ DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc # (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = (2016, 2, 1) date2 = (2017, 1, 5) 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('^KS11', 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, colorup='red', colordown='blue') ax.xaxis_date() ax.autoscale_view()
""" Create a candlestick chart for a stock """ import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator,\ DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc # Grab the stock data between these dates date1 = (2014, 10, 13) date2 = (2014, 11, 13) # Go to the web and pull the stock info quotes = quotes_historical_yahoo_ohlc('AAPL', date1, date2) if len(quotes) == 0: raise SystemExit # Set up the graph fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) # Major ticks on Mondays mondays = WeekdayLocator(MONDAY) ax.xaxis.set_major_locator(mondays) # Minor ticks on all days alldays = DayLocator() ax.xaxis.set_minor_locator(alldays) # Format the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12
def finance(data, parameters, output): #data # (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = (2016, 8, 1) date2 = (2016, 9, 9) sticker = '' with open(data) as f: f_csv = csv.reader(f) headers = next(f_csv) for row in f_csv: sticker = row[0] date1 = literal_eval(row[1]) date2 = literal_eval(row[2]) #parameters param = "" figsize = (8, 6) param1 = "" if 'figsize' in parameters.keys(): figsize = eval(parameters['figsize']) fig, ax = plt.subplots(figsize=(11, 5)) if 'title' in parameters.keys(): ax.set_title(parameters['title']) if 'witdth' in parameters.keys(): param = param + ",width=" + str(parameters['width']) if 'colorup' in parameters.keys(): param = param + ",colorup='" + parameters['colorup'] + "'" if 'colordown' in parameters.keys(): param = param + ",colordown='" + parameters['colordown'] + "'" if 'rotation' in parameters.keys(): param1 = param1 + ",rotation=" + str(parameters['rotation']) if 'horizontalalignment' in parameters.keys(): param1 = param1 + ",horizontalalignment='" + parameters[ 'horizontalalignment'] + "'" 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(sticker, date1, date2) if len(quotes) == 0: raise SystemExit 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) exec("candlestick_ohlc(ax, quotes, width=0.6" + param + ")") ax.xaxis_date() ax.autoscale_view() exec("plt.setp(plt.gca().get_xticklabels()" + param1 + ")") # adding horizontal grid lines plt.grid(True, linestyle='--', linewidth=0.5) savefig(output, format='svg')
line.set_data(x, y) return line anim=animation.FuncAnimation(fig, animate, init_func=init, frames=10000, interval=5000) plt.show() # 导入需要的库 import tushare as ts import matplotlib.pyplot as plt import matplotlib.finance as mpf # 设置历史数据区间 date1 = (2014, 12, 1) # 起始日期,格式:(年,月,日)元组 date2 = (2016, 12, 1) # 结束日期,格式:(年,月,日)元组 # 从雅虎财经中获取股票代码601558的历史行情 quotes = mpf.quotes_historical_yahoo_ohlc('601558.ss', date1, date2) # 创建一个子图 fig, ax = plt.subplots(facecolor=(0.5, 0.5, 0.5)) fig.subplots_adjust(bottom=0.2) # 设置X轴刻度为日期时间 ax.xaxis_date() # X轴刻度文字倾斜45度 plt.xticks(rotation=45) plt.title("股票代码:601558两年K线图") plt.xlabel("时间") plt.ylabel("股价(元)") mpf.candlestick_ohlc(ax, quotes, width=1.2, colorup='r', colordown='green') plt.grid(True)
# Now we plot only the X last days daysBack = 20 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')
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc # (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = (2004, 2, 1) date2 = (2004, 4, 12) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 quotes = quotes_historical_yahoo_ohlc('INTC', date1, date2) if len(quotes) == 0: raise SystemExit fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view()
ticker = '600028' # 600028 是"中国石化"的股票代码 ticker += '.ss' # .ss 表示上证 .sz表示深证 date1 = (2015, 8, 1) # 起始日期,格式:(年,月,日)元组 date2 = (2016, 1, 1) # 结束日期,格式:(年,月,日)元组 mondays = WeekdayLocator(MONDAY) # 主要刻度 alldays = DayLocator() # 次要刻度 #weekFormatter = DateFormatter('%b %d') # 如:Jan 12 mondayFormatter = DateFormatter('%m-%d-%Y') # 如:2-29-2015 dayFormatter = DateFormatter('%d') # 如:12 quotes = quotes_historical_yahoo_ohlc(ticker, 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(mondayFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6, colorup='r', colordown='g') ax.xaxis_date()
def getQuote(symbol, startDate=None, endDate=None): if(startDate == None): startDate = datetime(1900, 1, 1) if(endDate == None): endDate = datetime.today() #endDate = datetime(2012,12,12) try: conn = sqlite3.connect("./db/" + symbol + ".db") c = conn.cursor() r = c.execute('''SELECT count(*) FROM sqlite_master WHERE type=\'table\' AND name=\'prices\' ''') tableExists = r.fetchone()[0] > 0 if tableExists: # Calculate the start date for continuing the history data result = c.execute("SELECT min(date), max(date) FROM prices") if result: firstDate, lastDate = result.fetchone() if(firstDate != None and lastDate != None): # print "Table exists, starting at " + date2str(firstDate) + \ # ", ending at " + date2str(lastDate) startDateEpochs = lastDate + 1 dt = datetime.fromordinal(startDateEpochs-1721425) startDate = datetime(dt.year, dt.month, dt.day, 00, 00) else: # No table existing => create one c.execute('''CREATE TABLE prices( date integer, o real, h real, l real, c real, v real )''') # print "startDate=" + str(startDate) # print "endDate=" + str(endDate) # print "difference=" + str(endDate-startDate) difference = endDate - startDate #print "startDate=" + str(startDate) #print "endDate=" + str(endDate) if difference.days > 0: # print "=> " + str(difference.days) + " days" try: #print "mf.quotes_historical_yahoo(" + str(urllib.quote(symbol)) + \ #", " + str(startDate) + ", " + str(endDate) + ")" quotes = mf.quotes_historical_yahoo_ohlc(symbol, startDate, endDate) if quotes: for q in quotes: c.execute("INSERT INTO prices VALUES(" + str(1721425 + q[0]) # date + ", " + str(q[1]) # open + ", " + str(q[2]) # high + ", " + str(q[3]) # low + ", " + str(q[4]) # close + ", " + str(q[5]) # volume + ")") print "Added " + str(len(quotes)) + " items for " + symbol else: print "No new data available." conn.commit() except KeyboardInterrupt: raise KeyboardInterrupt except: print "Error:", sys.exc_info()[0] else: print "=> nothing to do." conn.close() except KeyboardInterrupt: raise KeyboardInterrupt except: print "Error:", sys.exc_info()[0]
import numpy as np import matplotlib.finance as mpf import matplotlib.pyplot as plt import matplotlib start = (2015, 4, 1) end = (2016, 4, 28) quotes = mpf.quotes_historical_yahoo_ohlc('INGN', start, end) print quotes
import pandas as pd import numpy as np import statsmodels.api as sm from matplotlib.finance import quotes_historical_yahoo_ohlc ff = pd.read_csv( 'https://raw.githubusercontent.com/alexpetralia/fama_french/master/FF_monthly.CSV', index_col='Date') begtime = (2008, 10, 1) endtime = (2013, 11, 30) price = quotes_historical_yahoo_ohlc('IBM', begtime, endtime, asobject=True, adjusted=True) logret = np.log(price.aclose[1:] / price.aclose[:-1]) month = [] for i in price.date: month.append(int(i.strftime("%Y%m"))) ret = pd.DataFrame(data=logret, index=month[1:], columns=['ret']) ret = np.exp(ret.groupby(ret.index).sum()) - 1 final = pd.merge(ff, ret, right_index=True, left_index=True) y = final.ret x = final[['Mkt-RF', 'SMB', 'HML']] x = sm.add_constant(x) results = sm.OLS(y, x).fit() print(results.params)
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc print ts.__version__ date1 = (2004, 2, 1) date2 = (2004, 4, 12) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter("%b %d") # e.g., Jan 12 dayFormatter = DateFormatter("%d") # e.g., 12 quotes = quotes_historical_yahoo_ohlc("MSFT", date1, date2) if len(quotes) == 0: raise SystemExit print str(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)
import matplotlib.pyplot as plt from matplotlib.dates import DateFormatter, WeekdayLocator, DayLocator, MONDAY from matplotlib.finance import quotes_historical_yahoo_ohlc, candlestick_ohlc # (Year, month, day) tuples suffice as args for quotes_historical_yahoo date1 = (2004, 2, 1) date2 = (2004, 4, 12) mondays = WeekdayLocator(MONDAY) # major ticks on the mondays alldays = DayLocator() # minor ticks on the days weekFormatter = DateFormatter('%b %d') # e.g., Jan 12 dayFormatter = DateFormatter('%d') # e.g., 12 quotes = quotes_historical_yahoo_ohlc('INTC', date1, date2) if len(quotes) == 0: raise SystemExit fig, ax = plt.subplots() fig.subplots_adjust(bottom=0.2) ax.xaxis.set_major_locator(mondays) ax.xaxis.set_minor_locator(alldays) ax.xaxis.set_major_formatter(weekFormatter) #ax.xaxis.set_minor_formatter(dayFormatter) #plot_day_summary(ax, quotes, ticksize=3) candlestick_ohlc(ax, quotes, width=0.6) ax.xaxis_date() ax.autoscale_view() plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')
def load_data_yahoo(code, start_date, end_date ): # http://blog.csdn.net/matrix_laboratory/article/details/50687910 # http://blog.csdn.net/mengwuyoulin/article/details/51165851 fh = finance.quotes_historical_yahoo_ohlc(code, start_date, end_date,adjusted=False) # print type(fh) return fh[0][4]