예제 #1
0
    def candle_plot(self, code):
        def format_date(x, pos):
            if x < 0 or x > len(date_tickers) - 1:
                return ''
            return date_tickers[int(x)]

        df = self.getdata_day(code, 240, 260)
        df['5'] = df.close.rolling(5).mean()
        df['20'] = df.close.rolling(20).mean()
        df['30'] = df.close.rolling(30).mean()
        df['60'] = df.close.rolling(60).mean()
        df['120'] = df.close.rolling(120).mean()
        # df['250'] = df.close.rolling(250).mean()
        date_tickers = df['datetime'].copy().values
        df['datetime'] = pd.to_datetime(df['datetime']).map(date2num)
        df['dates'] = np.arange(0, len(df))

        # date_tickers = df.trade_date2.values
        fig, ax = plt.subplots(figsize=(10, 5))
        ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
        # 绘制K线图
        mpl_finance.candlestick_ochl(
            ax=ax,
            quotes=df[['dates', 'open', 'close', 'high', 'low']].values,
            width=0.7,
            colorup='r',
            colordown='g',
            alpha=0.7)
        # 绘制均线
        for ma in ['5', '20', '30', '60', '120']:
            plt.plot(df['dates'], df[ma])
        plt.legend()
        ax.set_title(code, fontsize=20)
        plt.show()
예제 #2
0
    def draw_subgraph(self, stockdat, numt):
        # 绘制K线图
        ochl = list(zip(np.arange(0, len(stockdat.index)), stockdat.Open, stockdat.Close,
                        stockdat.High, stockdat.Low))
        # K线走势图
        mpf.candlestick_ochl(self.am, ochl, width=0.5, colorup='r', colordown='g')

        # 绘制均线
        self.am.plot(numt, stockdat['Ma20'], 'black', label='M20', lw=1.0)
        self.am.plot(numt, stockdat['Ma60'], 'green', label='M60', lw=1.0)
        self.am.plot(numt, stockdat['Ma120'], 'blue', label='M120', lw=1.0)
        self.am.legend(loc='best', shadow=True, fontsize='10')

        # 绘制成交量
        self.vol.bar(numt, stockdat.Volume, color=[
            'g' if stockdat.Open[x] > stockdat.Close[x]
            else 'r' for x in range(0, len(stockdat.index))])

        # 绘制MACD
        bar_red = np.where(stockdat['macd_bar'] > 0, 2 * stockdat['macd_bar'], 0)
        bar_green = np.where(stockdat['macd_bar'] < 0, 2 * stockdat['macd_bar'], 0)
        self.macd.plot(numt, stockdat['macd_dif'], 'red', label='macd dif')
        self.macd.plot(numt, stockdat['macd_dea'], 'blue', label='macd dea')
        self.macd.bar(numt, bar_red, facecolor='red', label='hist bar')
        self.macd.bar(numt, bar_green, facecolor='green', label='hist bar')
        self.macd.legend(loc='best', shadow=True, fontsize='10')

        # 绘制KDJ
        self.devol.plot(numt, stockdat['K'], 'blue', label='K')
        self.devol.plot(numt, stockdat['D'], 'g--', label='D')
        self.devol.plot(numt, stockdat['J'], 'r--', label='J')
        self.devol.legend(loc='best', shadow=True, fontsize='10')
예제 #3
0
def stockPricePlot(ticker):
    #step 1. load data
    history = pandas.read_csv('IntradayCN/' + ticker + '.csv',
                              parse_dates=True,
                              index_col=0)

    #step 2. data manipulation
    close = history['close']
    close = close.reset_index()
    close['timestamp'] = close['timestamp'].map(matplotlib.dates.date2num)

    onlc = history[['open', 'high', 'low', 'close']].resample('1H').ohlc()
    onlc = onlc.reset_index()
    onlc['timestamp'] = onlc['timestamp'].map(matplotlib.dates.date2num)

    #step 3. plot figure,  subplot 1: scatter plot, 2 ,candle
    #3.1 subplot 1: scatter plot
    plt.figure(figsize=(20, 20))
    subplot1 = plt.subplot2grid((2, 1), (0, 0), rowspan=1, colspan=1)
    subplot1.xaxis_date()
    subplot1.plot(close['timestamp'], close['close'], 'b.')
    plt.title(ticker)

    #3.2 subplot 2: candle stick plot
    plt.figure(figsize=(20, 20))
    subplot2 = plt.subplot2grid((2, 1), (1, 0),
                                rowspan=1,
                                colspan=1,
                                sharex=subplot1)
    mpf.candlestick_ochl(ax=subplot2,
                         quotes=onlc.values,
                         width=0.01,
                         colorup='g',
                         colordown='r')
    plt.show()
예제 #4
0
파일: kplot.py 프로젝트: lechen36/Qigit
def ax_kline(ax, df):
    date_tickers = df['trade_date'].values

    def format_date(x, pos=None):
        # 由于前面股票数据在 date 这个位置传入的都是int
        # 因此 x=0,1,2,...
        # date_tickers 是所有日期的字符串形式列表
        if x < 0 or x > len(date_tickers) - 1:
            return ''
        return date_tickers[int(x)]

    date_len = len(df)
    dateLoc = int(date_len / 10 + 0.5)
    ax.xaxis.set_major_locator(ticker.MultipleLocator(dateLoc))
    ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    ax.set_ylabel('K')
    ax.grid(True)
    plt.setp(ax.get_xticklabels(), visible=False)
    mpl_finance.candlestick_ochl(
        ax=ax,
        quotes=df[['iNum', 'open', 'close', 'high', 'low']].values,
        width=0.7,
        colorup='r',
        colordown='g',
        alpha=0.7)

    ax.set_title('%s' % (df['ts_code'].iloc[0]))
def plotCandle(daily_df, stock_code = "" , focus_date = None, gs = None ):
    if not focus_date:
        focus_date = daily_df.trade_date2.values[-1]
    # plot 
    if gs:
        ax1 = plt.subplot(gs[0:6,:])
    else:
        fig, ax1 = plt.subplots(figsize=(16,6))
    mpf.candlestick_ochl(
       ax=ax1,
       quotes=daily_df[['dates', 'open', 'close', 'high', 'low']].values,
       width=0.7,
       colorup='r',
       colordown='g',
       alpha=0.7)
    plt.grid(True)
    plt.xticks(rotation=40)
    plt.title(stock_code)
    ax1.xaxis.set_major_locator(ticker.MultipleLocator(5))
    date_tickers = daily_df["trade_date2"].values[0::5]
    date_tickers = np.insert(date_tickers,0," ")
    ax1.set_xticklabels(date_tickers)
    # mean values
    for ma in ['lag_5', 'lag_10', 'lag_20', 'lag_30', 'lag_60', 'lag_120', 'lag_250']:
        plt.plot(daily_df['dates'], daily_df[ma], label = ma)
    plt.legend()
    # 分割线
    #    print(focus_date)
    x = daily_df.loc[daily_df["trade_date2"] == focus_date, "dates"].values[0]
    plt.axvline(x,c="blue")#添加vertical直线
    y = daily_df.loc[daily_df["trade_date2"] == focus_date, "close"].values[0]
    plt.axhline(y,c="blue",ls = "-.")#添加水平直线

    return 0
예제 #6
0
def test_indicator(file_name, start_date, end_date, figure_title, candlestick_width):
    date_format = "%Y.%m.%d %H:%M:%S"
    csv_data = pd.read_csv(file_name)
    csv_data['Time'] = pd.to_datetime(csv_data['Time'], format=date_format)
    csv_data = csv_data.set_index('Time')
    csv_data = csv_data.iloc[::-1]

    plot_data = csv_data.copy()

    print('Sample data:')
    plot_data['EMA'] = exponential_moving_average(plot_data['Close'], 10)

    print(plot_data.tail(10))

    subplot_df1 = plot_data.drop(['Volume', 'EMA'], 1).loc[start_date:end_date]
    subplot_df2 = plot_data['EMA'].loc[start_date:end_date]

    df1_tuples = utils.candlestick_tuples(subplot_df1)

    fig, ax = plt.subplots()
    plt.xticks(rotation=45)
    plt.title(figure_title)

    fplt.candlestick_ochl(ax, df1_tuples, width=candlestick_width, colorup='g', colordown='r')
    subplot_df2.plot(ax=ax)

    plt.show()
예제 #7
0
def load_json(stock):
	title='Plot the time, open, close, high, low as a vertical line ranging from low to high. Use a rectangular bar to represent the open-close span. If close >= open, use colorup="k" to color the bar, otherwise use colordown="r"'
	df=pd.read_json('AllStocks.json')
	df=df[df['Symbol']==stock]
	fig,ax=plt.subplots()
	df['Open']=pd.to_numeric(df['Open'])
	df['Low']=pd.to_numeric(df['Low'])
	df['High']=pd.to_numeric(df['High'])
	df['Date']=date2num(pd.to_datetime(df['Date']).tolist())
	new_df=df.copy()
	new_df=new_df[['Date','Open','Close','Low','High']]
	quotes = [tuple(x) for x in new_df.values]

	candlestick_ochl(ax,quotes)	
	ax.xaxis.set_major_formatter(matplotlib.dates.DateFormatter('%Y-%m-%d'))
	ax.grid(True)
	ax.set_xlabel('Dates')
	ax.set_ylabel('Price')

	fig_size = ax.rcParams["figure.figsize"]  
	# Set figure width to 12 and height to 9
	fig_size[0] = 35
	fig_size[1] = 25
	ax.rcParams["figure.figsize"] = fig_size

	plt.savefig('GOOG.png')

	plt.show()
예제 #8
0
def test_indicator(file_name, start_date, end_date, figure_title,
                   candlestick_width):
    csv_data = utils.load_data(file_name, "%Y.%m.%d %H:%M:%S")

    plot_data = csv_data.copy()

    print('Sample data:')
    plot_data['SMA'] = simple_moving_average(plot_data['Close'], 10)

    print(plot_data.tail(20))

    subplot_df1 = plot_data.drop(['Volume', 'SMA'], 1).loc[start_date:end_date]
    subplot_df2 = plot_data['SMA'].loc[start_date:end_date]

    df1_tuples = utils.candlestick_tuples(subplot_df1)

    fig, ax = plt.subplots()
    plt.xticks(rotation=45)
    plt.title(figure_title)

    fplt.candlestick_ochl(ax,
                          df1_tuples,
                          width=candlestick_width,
                          colorup='g',
                          colordown='r')
    subplot_df2.plot(ax=ax)

    plt.show()
예제 #9
0
파일: c5.py 프로젝트: OsbornHu/abu
def sample_513():
    """
    5.1.3 k线图的绘制
    :return:
    """
    #pip install https://github.com/matplotlib/mpl_finance/archive/master.zip
    import mpl_finance as mpf
    import matplotlib.dates as dts

    __colorup__ = "red"
    __colordown__ = "green"
    # 为了示例清晰,只拿出前30天的交易数据绘制蜡烛图,
    tsla_part_df = tsla_df[:30]
    fig, ax = plt.subplots(figsize=(14, 7))
    qutotes = []

    for index, (d, o, c, h, l) in enumerate(
            zip(tsla_part_df.index, tsla_part_df.open, tsla_part_df.close,
                tsla_part_df.high, tsla_part_df.low)):
        # 蜡烛图的日期要使用matplotlib.finance.date2num进行转换为特有的数字值
        d = dts.date2num(d)
        # 日期,开盘,收盘,最高,最低组成tuple对象val
        val = (d, o, c, h, l)
        # 加val加入qutotes
        qutotes.append(val)
    # 使用mpf.candlestick_ochl进行蜡烛绘制,ochl代表:open,close,high,low
    mpf.candlestick_ochl(ax,
                         qutotes,
                         width=0.6,
                         colorup=__colorup__,
                         colordown=__colordown__)
    ax.autoscale_view()
    ax.xaxis_date()
    plt.show()
def save_historic_klines_csv(symbol, start, end, interval):
    klines = get_historical_klines(symbol, interval, start, end)
    ochl = []
    list_of_open = []
    three_period_moving_ave = []
    time3 = []
    five_period_moving_ave = []
    ten_period_moving_ave = []
    time10 = []
    with open('Binance_{}_{}-{}.txt'.format(symbol, start, end), 'w') as f:
        f.write('Time, Open, High, Low, Close, Volume\n')
        for kline in klines:
            #print(kline)
            time1 = int(kline[0])
            open1 = float(kline[1])
            Low = float(kline[2])
            High = float(kline[3])
            Close = float(kline[4])
            Volume = float(kline[5])
            format_kline = "{}, {}, {}, {}, {}, {}\n".format(
                time1, open1, High, Low, Close,
                Volume)  #Thanks to user Apneef for correction
            ochl.append([time1, open1, Close, High, Low, Volume])
            f.write(format_kline)

            #track opening prices, use for calculating moving averages
            list_of_open.append(open1)
            #Calculate three 'period' moving average - Based on Candlestick duration
            if len(list_of_open) > 2:
                price3 = 0
                for pri in list_of_open[-3:]:
                    price3 += pri
                three_period_moving_ave.append(float(price3 / 3))
                time3.append(time1)
            #Perform Moving Average Calculation for 10 periods
            if len(list_of_open) > 9:
                price10 = 0
                for pri in list_of_open[-10:]:
                    price10 += pri
                ten_period_moving_ave.append(float(price10 / 10))
                time10.append(time1)

    #Matplotlib visualization how-to from: https://pythonprogramming.net/candlestick-ohlc-graph-matplotlib-tutorial/
    fig, ax = plt.subplots()
    mpl_finance.candlestick_ochl(ax, ochl, width=1)
    plt.plot(time3,
             three_period_moving_ave,
             color='green',
             label='3 Period MA - Open')
    plt.plot(time10,
             ten_period_moving_ave,
             color='blue',
             label='10 Period MA - Open')
    #ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d-%h-%m')) #Converting to date format not working
    ax.set(xlabel='Date',
           ylabel='Price',
           title='{} {}-{}'.format(symbol, start, end))
    plt.legend()
    plt.show()
def test_indicator(file_name, start_date, end_date, figure_title,
                   candlestick_width):
    csv_data = utils.load_data(file_name, "%Y.%m.%d %H:%M:%S")

    print("Sample data:")
    print(csv_data.head(10))

    data_CHO = chaikin_oscillator(csv_data)

    print("")
    print(data_CHO.tail(20))

    ax1_data = data_CHO.drop(
        ['Volume', 'ADL', '3 day EMA of ADL', '10 day EMA of ADL', 'CHO'], 1)
    ax1_data = ax1_data.loc[start_date:end_date]

    ax2_data = data_CHO.drop(['Open', 'High', 'Low', 'Close', 'Volume', 'CHO'],
                             1)
    ax2_data = ax2_data.loc[start_date:end_date]

    ax3_data = data_CHO['CHO'].loc[start_date:end_date]

    # fig1.suptitle('Hourly OHLC data') <- figure title

    df1_tuples = utils.candlestick_tuples(ax1_data)

    fig1, ax1 = plt.subplots(1, 1)
    ax1.xaxis_date()
    ax1.set_ylabel('OHLC', color='g')
    ax1.set_title(figure_title)
    for tick in ax1.get_xticklabels():
        tick.set_rotation(45)
    for t1 in ax1.get_yticklabels():
        t1.set_color('g')
    ax1.grid()
    fplt.candlestick_ochl(ax1,
                          df1_tuples,
                          width=candlestick_width,
                          colorup='g',
                          colordown='r')

    ax2 = ax1.twinx()
    ax2.plot(ax3_data, 'b-')
    ax2.set_ylabel('%R', color='b')
    for t1 in ax2.get_yticklabels():
        t1.set_color('b')
    fig1.show()

    fig2 = plt.figure(2)
    plt.plot(ax2_data)
    plt.title('ADL vs EMAs')
    plt.legend(['ADL', '3 day EMA of ADL', '10 day EMA of ADL'])
    plt.xlabel('Laikas')
    plt.ylabel('ADL')
    plt.grid()
    plt.xticks(rotation=90)
    fig2.show()

    plt.close()
예제 #12
0
def draw_stock(df):
    global t_profit, buying_price, selling_price, profit
    # select df
    #df=df.iloc[len(df)-50:len(df)]
    #print(df)

    #figure = plt.figure(figsize=(12, 9))
    plt.cla()

    mpl.rcParams['font.family'] = 'sans-serif'
    mpl.rcParams['font.sans-serif'] = 'SimHei'

    def format_date(x, pos):
        if x < 0 or x > len(date_tickers) - 1:
            return ''
        return date_tickers[int(x)]

    date_tickers = df.dates.values
    #

    gs = GridSpec(3, 1)
    ax1 = plt.subplot(gs[:2, :], facecolor="black")
    ax2 = plt.subplot(gs[2, :], facecolor="black")

    ax1.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    #
    mpl_finance.candlestick_ochl(
        ax=ax1,
        quotes=df[['dates', 'open', 'close', 'high', 'low']].values,
        width=0.7,
        colorup='r',
        colordown='cyan',
        alpha=0.7)
    #
    for ma in ['5', '10', '20']:
        ax1.plot(df['dates'], df[ma])
    #plt.legend()
    ax1.set_title(
        "Total: {:.2f} Profit : {:.2f}% buy price : {}  sell price : {}  temp profit : {:.2f}%"
        .format(20000 * (1 + t_profit), t_profit * 100, buying_price,
                selling_price, profit * 100),
        fontsize=15)

    #
    ax2.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    #df2['up'] = df.apply(lambda row: 1 if row['close'] >= row['open'] else 0, axis=1)
    ax2.bar(df.query('up == 1')['dates'],
            df.query('up == 1')['vol1'],
            color='r',
            alpha=0.7)
    ax2.bar(df.query('up == 0')['dates'],
            df.query('up == 0')['vol1'],
            color='cyan',
            alpha=0.7)
    ax2.set_xlabel('Stock Simulator', fontsize=30)
    ax2.set_title(
        "Help : mouse left click:buy/keep,  mouse right click:sell/waiting  mouse mid click:reset",
        fontsize=15)
예제 #13
0
파일: MarketWidth.py 프로젝트: mildone/ecap
def contextPlot(df, start='2020-01-01', end='cur'):
    import core.Util as ut
    if (end == 'cur'):
        cur = datetime.datetime.now()
        mon = str(cur.month)
        day = str(cur.day)
        if (re.match('[0-9]{1}', mon) and len(mon) == 1):
            mon = '0' + mon
        if (re.match('[0-9]{1}', day) and len(day) == 1):
            day = '0' + day

        et = str(cur.year) + '-' + mon + '-' + day
    else:
        et = end
    sample = QA.QA_fetch_stock_day_adv('000977', start, et).data
    quots = ut.candlestruct(sample)

    N = df.shape[0]
    ind = np.arange(N)

    def format_date(x, pos=None):
        thisind = np.clip(int(x + 0.5), 0, N - 1)
        return m.index.get_level_values(uti.dayindex)[thisind]

    fig = plt.figure()
    #gs = gridspec.GridSpec(3, 1)
    fig.set_size_inches(30.5, 20.5)

    ax3 = fig.add_subplot(2, 1, 2)
    ax3.set_title("candlestick", fontsize='xx-large', fontweight='bold')

    mpf.candlestick_ochl(ax3,
                         quots,
                         width=0.6,
                         colorup='r',
                         colordown='g',
                         alpha=1.0)
    '''
    for i in range(N):
        if (day.single[i] == 1):
            ax2.axvline(x=i, ls='--', color='red')
        if (day.single[i] == 3):
            ax2.axvline(x=i, ls='--', color='green')
    '''
    ax3.xaxis.set_major_formatter(mtk.FuncFormatter(format_date))
    ax3.grid(True)
    ax3.legend(loc='best')
    fig.autofmt_xdate()

    ax2 = fig.add_subplot(2, 1, 1, sharex=ax3)
    # ax3.set_title("Divergence", fontsize='xx-large', fontweight='bold')
    ax2.plot(ind, m.value, 'r-', linewidth=1)
    ax2.grid(True)
    ax2.xaxis.set_major_formatter(mtk.FuncFormatter(format_date))

    fig.autofmt_xdate()

    plt.show()
예제 #14
0
파일: MonthTrend.py 프로젝트: mildone/ecap
def Plot(sample):
    print(sample)
    quotes = []
    N = sample.shape[0]
    ind = np.arange(N)
    for i in range(len(sample)):
        li = []
        datef = ind[i]  # 日期转换成float days
        open_p = sample.open[i]
        close_p = sample.close[i]
        high_p = sample.high[i]
        low_p = sample.low[i]
        li = [datef, open_p, close_p, high_p, low_p]
        t = tuple(li)
        quotes.append(t)

    def format_date(x, pos=None):
        thisind = np.clip(int(x + 0.5), 0, N - 1)
        return sample.date[thisind].strftime('%Y-%m-%d')

    fig = plt.figure()
    fig.set_size_inches(30.5, 20.5)
    print('call here')
    ax2 = fig.add_subplot(3, 1, 1)
    ax2.set_title("Monthly candlestick",
                  fontsize='xx-large',
                  fontweight='bold')

    mpf.candlestick_ochl(ax2,
                         quotes,
                         width=0.6,
                         colorup='r',
                         colordown='g',
                         alpha=1.0)
    ax2.plot(ind, sample.EMA5, 'r-', label='EMA5')
    ax2.plot(ind, sample.EMA10, 'blue', label='EMA10')
    ax2.xaxis.set_major_formatter(mtk.FuncFormatter(format_date))
    ax2.grid(True)
    ax2.legend(loc='best')
    fig.autofmt_xdate()

    ax1 = fig.add_subplot(3, 1, 2, sharex=ax2)
    ax1.set_title(' macd', fontsize='xx-large', fontweight='bold')
    ax1.grid(True)
    ax1.plot(ind, sample.MACDQ, 'red', label='DIF')
    ax1.plot(ind, sample.MACDSIG, 'blue', label='DEA')
    m_red = np.where(sample.MACDBlock >= 0, sample.MACDBlock, 0)
    m_green = np.where(sample.MACDBlock < 0, sample.MACDBlock, 0)
    ax1.bar(ind, m_red, color='red')
    ax1.bar(ind, m_green, color='green')
    ax1.xaxis.set_major_formatter(mtk.FuncFormatter(format_date))
    # ax2.set_yticks(np.linspace(ax2.get_yticks()[0], ax2.get_yticks()[-1], len(ax1.get_yticks())))
    ax1.legend(loc='best')
    fig.autofmt_xdate()
    plt.legend()
    plt.show()
예제 #15
0
def draw_kl2(df: pd.DataFrame, minute=False, day_sum=False):

    # 为了示例清晰,只拿出前30天的交易数据绘制蜡烛图,
    part_df = df
    # fig, ax = plt.subplots(figsize=(14, 7))
    fig, ax1 = plt.subplots(figsize=(6, 6))
    qutotes = []

    if day_sum:
        # 端线图绘制
        qutotes = []
        for index, (d, o, c, l, h) in enumerate(
                zip(part_df.time, part_df.open, part_df.close, part_df.high,
                    part_df.low)):
            d = index if minute else dts.date2num(d)
            val = (d, o, c, l, h)
            qutotes.append(val)
        # plot_day_summary_oclh接口,与mpf.candlestick_ochl不同,即数据顺序为开收低高
        mpf.plot_day_summary_oclh(ax1,
                                  qutotes,
                                  ticksize=5,
                                  colorup=__colorup__,
                                  colordown=__colordown__)
    else:
        # k线图绘制
        qutotes = []
        for index, (d, o, c, h, l) in enumerate(
                zip(part_df.time, part_df.open, part_df.close, part_df.high,
                    part_df.low)):
            d = index if minute else dts.date2num(d)
            val = (d, o, c, h, l)
            qutotes.append(val)
        # mpf.candlestick_ochl即数据顺序为开收高低
        mpf.candlestick_ochl(ax1,
                             qutotes,
                             width=0.6,
                             colorup=__colorup__,
                             colordown=__colordown__)
    # for index, (d, o, c, h, l) in enumerate(
    #         zip(part_df.time, part_df.open, part_df.close,
    #             part_df.high, part_df.low)):
    #     # 蜡烛图的日期要使用dts.date2num进行转换为特有的数字值
    #     # d = datetime.datetime.fromtimestamp(d / 1000)
    #     # d = dts.date2num(d)
    #     d = index
    #     # 日期,开盘,收盘,最高,最低组成tuple对象val
    #     val = (d, o, c, h, l)
    #     # 加val加入qutotes
    #     qutotes.append(val)
    # 使用mpf.candlestick_ochl进行蜡烛绘制,ochl代表:open,close,high,low
    # mpf.candlestick_ochl(ax, qutotes, width=0.6, colorup=__colorup__,
    #                      colordown=__colordown__)
    # ax.autoscale_view()
    # ax.xaxis_date()
    plt.show()
예제 #16
0
def main():
    args = parse_args()

    # read
    df = pd.read_csv(args.input, index_col=0, parse_dates=True)
    df.index = pd.to_datetime(df.index)
    df.index = mdates.date2num(df.index)

    # rolling_average
    for span in args.roll_spans:
        name = 'roll_{}'.format(span)
        df[name] = df['close'].rolling(span).mean()

    if args.output_length > 0:
        df = df.tail(args.output_length)

    # Plot Figure
    fig, axes = plt.subplots(nrows=2,
                             ncols=1,
                             figsize=(16, 9),
                             sharex=True,
                             gridspec_kw={'height_ratios': [4, 1]})

    # Plot candle
    width = (df.index[1] - df.index[0]) * 0.7
    if args.plot_candle:
        ohlc = df.reset_index().values
        width = (ohlc[1][0] - ohlc[0][0]) * 0.7
        mpf.candlestick_ochl(axes[0],
                             ohlc,
                             colorup='g',
                             colordown='r',
                             width=width,
                             alpha=0.75)
    else:
        axes[0].plot(df.index, df.close, color="black", linewidth=0.7)

    # Plot rolling means
    for span in args.roll_spans:
        name = "roll_{}".format(span)
        axes[0].plot(df.index, getattr(df, name), linewidth=0.7, label=name)

    # Plot Volumes
    axes[1].bar(df.index, df.volume, width=width)

    # Graph Settings
    axes[0].grid(linestyle=':')
    axes[0].legend()
    axes[1].grid(linestyle=':')

    locator = mdates.AutoDateLocator()
    axes[0].xaxis.set_major_locator(locator)
    axes[0].xaxis.set_major_formatter(mdates.DateFormatter('%y/%m/%d %H:%M'))

    fig.savefig(args.output)
예제 #17
0
def Draw_Stock(stock_id,
               stock_info,
               buy_day,
               sell_date=None,
               left_offset=5,
               right_offset=5):
    """
    绘制股票交易前后其股价变化
    :param stock_id: 股票id
    :param stock_info: 所有股票的信息
    :param buy_day: 买入股票的日子
    :param left_offset: 绘图左偏天数,用于调整可见天数
    :param right_offset: 绘图右偏天数,用于调整可见天数
    :return:
    """
    fig, ax = plt.subplots(1, 1, figsize=(8, 3))
    idx = (stock_info['trade_date'] == buy_day) & (stock_info['ts_code']
                                                   == stock_id)
    ts_date_id = stock_info[idx]['ts_date_id'].values[0]
    idx = (stock_info['ts_date_id'] <= ts_date_id + right_offset) & (
        stock_info['ts_date_id'] >= ts_date_id - left_offset)
    tmp_df = stock_info[idx].sort_values('trade_date').reset_index()
    x = list(range(len(tmp_df)))
    tmp_df['index'] = x
    idx = (tmp_df['trade_date'] == buy_day)
    x_loc = tmp_df[idx]['index'].values[0]
    y_loc = tmp_df[idx]['close'].values[0]
    # print(x_loc, y_loc)
    data = tmp_df[['index', 'open', 'close', 'high', 'low']].values
    candlestick_ochl(ax, data, width=0.1, colorup='r', colordown='g')
    # plt.arrow(x_loc, y_loc*1.5, x_loc, y_loc, length_includes_head=True, head_width=0.25, head_length=0.5, fc='r', ec='b')
    plt.annotate(
        "buy",
        xy=(x_loc, y_loc * 1.001),
        xytext=(x_loc, y_loc * 1.06),
        # xycoords="figure points",
        arrowprops=dict(arrowstyle="->", color="b"))
    # plt.plot(x_loc, y_loc * 1.03, '*')
    title = tmp_df['name'][0]
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    plt.title(title)
    plt.tick_params(labelsize=15)

    if sell_date:
        idx = (tmp_df['trade_date'] == sell_date)
        x_loc = tmp_df[idx]['index'].values[0]
        y_loc = tmp_df[idx]['high'].values[0]
        plt.annotate(
            "sell",
            xy=(x_loc, y_loc * 1.001),
            xytext=(x_loc, y_loc * 1.06),
            # xycoords="figure points",
            arrowprops=dict(arrowstyle="->", color="r"))
예제 #18
0
def K(ts_code, type):
    if type == 0:
        date = '年'
        end_date = datetime.now().strftime('%Y%m%d')
        delta = timedelta(days=365)
        start_date = (datetime.now() - delta).strftime('%Y%m%d')
    elif type == 1:
        date = '月'
        end_date = datetime.now().strftime('%Y%m%d')
        delta = timedelta(days=31)
        start_date = (datetime.now() - delta).strftime('%Y%m%d')
    else:
        date = '周'
        end_date = datetime.now().strftime('%Y%m%d')
        delta = timedelta(days=7)
        start_date = (datetime.now() - delta).strftime('%Y%m%d')
    token = "d078bd5a718954f48ee1f41013279afae62d1affd0866b56658cd918"
    ts.set_token(token)
    pro = ts.pro_api()
    data = pro.query('daily',
                     ts_code=ts_code,
                     start_date=start_date,
                     end_date=end_date)
    #删除空行
    data[data['vol'] == 0] = np.nan
    data = data.dropna()
    #按时间升序排列数据
    data.sort_values(by='trade_date', ascending=True, inplace=True)
    data = data[['trade_date', 'open', 'close', 'high',
                 'low']]  #这里由于数据太多,仅取前3000行进行绘制
    data.trade_date = pd.to_datetime(data.trade_date)
    #将date转化为特定的时间戳数据
    data.trade_date = data.trade_date.apply(lambda x: date2num(x))
    #将 DataFrame 转为 matrix格式
    data_mat = data.values
    # print(data_mat)
    #绘制图片
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    fig, ax = plt.subplots(figsize=(1200 / 72, 480 / 72))
    fig.subplots_adjust(bottom=0.1)
    fig.suptitle(r'{0}的{1}K线图'.format(ts_code, date), fontsize=20.00)
    mpf.candlestick_ochl(ax,
                         data_mat,
                         colordown='#53c156',
                         colorup='#ff1717',
                         width=0.3,
                         alpha=1)
    ax.grid(True)
    ax.xaxis_date()
    plt.savefig(r'./{0}的{1}K线图.jpg'.format(ts_code, date))
    url = '{0}的{1}K线图.jpg'.format(ts_code, date)
    return url
예제 #19
0
    def draw_image(self, stock_id, chart_title, open, high, low, new_price):
        self.id = stock_id
        self.select_df()
        self.insert_today_trade(open, high, low, new_price)
        stock = stock_buffer.put_stock_instance(self.id)
        self.df['dates'] = np.arange(0, len(self.df))
        self.df['5'] = self.df['close_price'].rolling(5).mean()

        def format_date(x, pos):
            if x < 0 or x > len(date_tickers) - 1:
                return ''
            return date_tickers[int(x)]

        date_tickers = self.df.trade_date.values
        plt.rcParams['font.sans-serif'] = ['KaiTi']
        plt.rcParams['axes.unicode_minus'] = False
        fig, ax = plt.subplots(figsize=(23, 5))
        ax.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
        ax.set_title(chart_title, fontsize=20)
        # 绘制K线图
        mpl_finance.candlestick_ochl(ax=ax,
                                     quotes=self.df[[
                                         'dates', 'open_price', 'close_price',
                                         'high_price', 'low_price'
                                     ]].values,
                                     width=0.7,
                                     colorup='r',
                                     colordown='g',
                                     alpha=0.7)
        plt.plot(self.df['dates'], self.df['5'])
        zhuang_section = self.info_df.loc[0, 'zhuang_section']
        # print('zhuang_section:', zhuang_section)
        try:
            zhuang_section = eval(zhuang_section)
        except Exception as err:
            if zhuang_section == None:
                zhuang_section = []
            logging.error('ERR:{} zhuang_section:{},df:{}'.format(
                err, zhuang_section, self.info_df))
            print('ERR:{} zhuang_section:{},df:{}'.format(
                err, zhuang_section, self.info_df))
        for zhaung_tup in zhuang_section:
            sta = self.__comput_ind(zhaung_tup[1])
            end = self.__comput_ind(zhaung_tup[0])
            print('indexs:', sta, end)
            plt.plot(self.df['dates'][sta:end],
                     self.df['5'][sta:end],
                     color='green')
        plt.legend()
        # self.image_path = '../pic/{0}{1}{2}{3}.jpg'.format(stock.stock_id, stock.stock_name, self.to_day, stock.inform_type)
        self.image_path = '../pic/{0}{1}{2}.jpg'.format(
            stock.stock_id, self.to_day, stock.inform_type)
        plt.savefig(self.image_path)
예제 #20
0
	def DrawKLine(self):
		ohlc = []
		ohlc = list(zip(np.arange(0,len(self.df.index)),self.df.open,self.df.close,self.df.high,self.df.low))
		mpf.candlestick_ochl(self.graph_KAV, ohlc, width=0.2, colorup='r', colordown='g', alpha=1.0)
		self.graph_KAV.plot(self.numt, self.df['Ma20'],'black', label='M20',lw=1.0)
		self.graph_KAV.plot(self.numt, self.df['Ma30'],'green',label='M30', lw=1.0)
		self.graph_KAV.plot(self.numt, self.df['Ma60'],'blue',label='M60', lw=1.0)
		self.graph_KAV.legend(loc='best')
		self.graph_KAV.set_ylabel(u"价格")
		self.graph_KAV.set_xlim(0,len(self.df.index))
		self.graph_KAV.set_xticks(range(0,len(self.df.index),15))
		self.graph_KAV.grid(True,color='k')
예제 #21
0
 def draw(self):
     self.read_data()
     fig, ax = plt.subplots(figsize=(1200 / 72, 480 / 72))
     fig.subplots_adjust(bottom=0.1)
     mpf.candlestick_ochl(ax,
                          self.data_mat,
                          colordown=self.colordown,
                          colorup=self.colorup,
                          width=0.3,
                          alpha=1)
     ax.grid(True)
     ax.xaxis_date()
     plt.show()
예제 #22
0
파일: job.py 프로젝트: mildone/ecap
def MACDPLOT(sample):
    quotes = candlestruct(sample)
    N=sample.index.get_level_values('date').shape[0]
    ind = np.arange(N)
    def format_date(x, pos=None):
        thisind = np.clip(int(x+0.5), 0, N-1)
        return sample.index.get_level_values('date')[thisind].strftime('%Y-%m-%d')
    fig = plt.figure()
    #fig = plt.gcf()
    fig.set_size_inches(20.5,12.5)
    #plt.xlabel('Trading Day')
    #plt.ylabel('MACD EMA')
    ax2 = fig.add_subplot(3,1,1)
    ax2.set_title("candlestick")
  
    
    #fig,ax=plt.subplots()
    #mpf.candlestick_ochl(ax2,quotes,width=0.2,colorup='r',colordown='g',alpha=1.0)
    #ax2.xaxis_date()
    #plt.setp(plt.gca().get_xticklabels(),rotation=30)
    #ax2.plot(ind,sample.close,'b-',marker='*')
    mpf.candlestick_ochl(ax2,quotes,width=0.6,colorup='r',colordown='g',alpha=1.0)
    ax2.xaxis.set_major_formatter(mtk.FuncFormatter(format_date))
    ax2.grid(True)
    #t.legend()
    fig.autofmt_xdate()
    
    ax3 = fig.add_subplot(3,1,3,sharex=ax2)
    ax3.set_title("volume")
    #ax1 = ax2.twinx()   #not working like it's 
    ax3.bar(ind,sample.volume)
    ax3.grid(True)
    ax3.xaxis.set_major_formatter(mtk.FuncFormatter(format_date))
    fig.autofmt_xdate()
    
    #ax1 = ax2.twinx()   #not working like it's 
    ax1 = fig.add_subplot(3,1,2,sharex=ax2)
    ax1.set_title("macd")
    ax1.grid(True)
    ax1.plot(ind,sample.MACDQ,'r-',marker='*')
    ax1.plot(ind,sample.MACDSIG,'o-')
    ax1.bar(ind,sample.MACDBlock)
    ax1.xaxis.set_major_formatter(mtk.FuncFormatter(format_date))
    #ax2.set_yticks(np.linspace(ax2.get_yticks()[0], ax2.get_yticks()[-1], len(ax1.get_yticks())))
    fig.autofmt_xdate()
    plt.legend()
    code = sample.index.get_level_values('code')[0]
    
    plt.savefig('/home/mildone/monitor/'+'Trend'+code+'.png')
    #plt.show()  comment out for hanging with 1 pic 
    plt.close()
예제 #23
0
파일: test2.py 프로젝트: Tree12323/BackTest
def plot_k(data, title):
    fig, ax = plt.subplots(figsize=(15, 5))
    fig.subplots_adjust(bottom=0.5)
    mpf.candlestick_ochl(ax,
                         data,
                         width=0.3,
                         colorup='g',
                         colordown='r',
                         alpha=1.0)
    plt.grid(True)
    plt.title(title)
    plt.xlabel('Date')
    plt.ylabel('Price')
    plt.show()
예제 #24
0
def plot_candles(som_model):
    import matplotlib.pyplot as plt
    from mpl_finance import candlestick_ochl

    weights = som_model.get_weights()

    f, ax = plt.subplots(nrows=weights[0],
                         ncols=1,
                         sharey=True,
                         figsize=(10, 10))
    for i in range(weights.shape[0]):
        candlestick_ochl(ax[i], [
            _np.append([j], weights[i, j] + 1) for j in range(weights.shape[1])
        ])
    def addcandlestick(self,data,plotname):
        """Creates a candlestick subplot for the dataplotter figure based on the data
        
        Args:
            data (Pandas DataFrame): 2-column dataframe. 
            plotname (String): Name for the subplot
        """
        #constructing the candlestick plot
        currentplot = self.fig.add_subplot(1,1,1)
        candlestick_ochl(currentplot,data,colorup="g")
        currentplot.set_xlabel("Iteration")
        currentplot.grid(True)

        #Add the subplot to the subplot dictionary
        self.subplots[plotname]=currentplot
예제 #26
0
def kgrid(stock_code, data_list):
    fig, ax = plt.subplots()
    fig.subplots_adjust(bottom=0.2)
    ax.xaxis_date()
    plt.xticks(rotation=45)
    plt.yticks()
    plt.title("Stock Code: %s" % stock_code)
    plt.xlabel("Time")
    plt.ylabel("Price")
    mpf.candlestick_ochl(ax,
                         data_list,
                         width=0.72,
                         colorup='r',
                         colordown='green')
    plt.grid()
def graphs(stock):
    with open(stock+'.csv', 'r') as csvfile:
        fig = plt.figure('figure one')

        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('dates')
        plt.ylabel('price')
        ax3 = plt.subplot2grid((6, 1), (5, 0), rowspan=1, colspan=1)

        source_code = csvfile.read()
        stock_data = []
        split_source = source_code.split('\n')

        for line in split_source:
            split_line = line.split(',')
            if len(split_line) == 7:
                if 'Date' is not line and 'Close' not in line:
                    stock_data.append(line)

        date, openp, hightp, lowp, closep, aclosep, 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], hightp[x], lowp[x], closep[x], aclosep[x], volume[x]
            ohlc.append(append_me)
            x+=1

        candlestick_ochl(ax2, ohlc, width=0.4, colordown='r', colorup='g')

        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')
        ax2.annotate(str(closep[-1]), (date[-1],closep[-1]), xytext=(date[-1]+3,closep[-1]), bbox=bbox_props)

        plt.subplots_adjust(left=0.09, bottom=0.25, right=0.82, top=0.90, wspace=0.2, hspace=0)
        plt.show()
예제 #28
0
def showall(df, nrows=3):
    # 提取原始日期格式
    df['dates'] = np.arange(0, len(df))
    df = df.reset_index()
    df['date2'] = df['date'].copy()
    df['date'] = df['date'].map(date2num)
    global date_tickers
    date_tickers = (df.date2).apply(lambda x: x.strftime('%Y%m%d')).values
    # 画子图
    figure = plt.figure(figsize=(16, 9))
    gs = GridSpec(nrows, 1)
    gs.update(wspace=0.05, hspace=0.05)
    ax1 = plt.subplot(gs[:2, :])
    ax2 = plt.subplot(gs[2, :])
    ax3 = plt.subplot(gs[nrows - 1, :])
    # 画K线图
    mpf.candlestick_ochl(ax=ax1,
                         quotes=df[['dates', 'open', 'close', 'high',
                                    'low']].values,
                         width=0.7,
                         colorup='r',
                         colordown='g',
                         alpha=0.7)
    ax1.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    # 画均线,均线可使用talib来计算
    for ma in ['5', '20', '30', '60', '120']:
        df[ma] = df.close.rolling(int(ma)).mean()
        ax1.plot(df['dates'], df[ma])
    ax1.legend()
    ax1.set_title('沪深300指数K线图', fontsize=15)
    ax1.set_ylabel('指数')
    # 画成交量
    ax2.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    # 收阳线;收盘价大于等于开盘价=1
    df['up'] = df.apply(lambda row: 1 if row['close'] >= row['open'] else 0,
                        axis=1)
    ax2.bar(df.query('up == 1')['dates'],
            df.query('up == 1')['vol'],
            color='r',
            alpha=0.7)
    ax2.bar(df.query('up == 0')['dates'],
            df.query('up == 0')['vol'],
            color='g',
            alpha=0.7)
    ax2.set_ylabel('成交量')
    ax2.xaxis.set_major_formatter(ticker.FuncFormatter(format_date))
    plt.show()
    time.sleep(2)
예제 #29
0
    def plot_graph(self, start):
        price_sheet = None
        try:
            # obtain the data from IEX cloud. we use json format since it's easy to process
            # chartSimplify meant to simply the data, since we don't want to many data to plot the graph
            price_sheet = get_historical_data(self.symbol_info['symbol'],
                                              start,
                                              str(datetime.date.today()),
                                              output_format='json',
                                              chartSimplify=True,
                                              token=API_KEY)
        except IEXQueryError as ex:
            return "Sorry, but I have trouble obtaining the balance data."

        try:
            # Import the MatPlotLib and MatPlotLib Finance libraries
            import matplotlib.pyplot as plt
            import mpl_finance as mpf
            from matplotlib.pylab import date2num

            # Convert the obtained data to the format that MatPlotLib can understand
            data = []
            for k in price_sheet.keys():
                a = price_sheet[k]
                # Convert the dates to float, making MatPlotLib understand them
                date_time = datetime.datetime.strptime(k, '%Y-%m-%d')
                data.append([
                    date2num(date_time), a['open'], a['close'], a['high'],
                    a['low'], a['volume']
                ])

            fig, ax = plt.subplots(figsize=(1200 / 72, 480 / 72))
            fig.subplots_adjust(bottom=0.1)
            mpf.candlestick_ochl(ax,
                                 data,
                                 colordown='#53c156',
                                 colorup='#ff1717',
                                 width=0.3,
                                 alpha=1)
            ax.grid(True)
            ax.xaxis_date()

            # Now return the figure instead of string.
            # Different user interfaces have different ways to show figures
            return fig
        except Exception as e:
            # Once there's errors, we just return a error message.
            return "Oops, something wrong happened while plotting the graph!"
예제 #30
0
 def draw_k_v(self):
     fig, (ax1, ax2) = plt.subplots(2, sharex=True, figsize=(15, 8))
     mpf.candlestick_ochl(ax1,
                          self.mat_data,
                          width=0.5,
                          colorup='r',
                          colordown='k')
     ax1.set_title(self.name + ':' + self.code)
     ax1.set_ylabel('Price')
     ax1.grid(True)
     ax1.xaxis_date()
     plt.bar(self.mat_data[:, 0], self.mat_data[:, 5],
             width=0.5)  # ? mat_data[:,0] - 0.25
     ax2.set_ylabel('Volume')
     ax2.grid(True)
     plt.show()
예제 #31
0
파일: k_line.py 프로젝트: jjmonster/trade
 def update_k_line(self, tochlva):
     print("update_k_line", tochlva)
     self.amount = [i.pop() for i in tochlva]
     self.volume = [i.pop() for i in tochlva]        
     self.x = []
     for i in tochlva:
         i[0] = mdates.epoch2num(i[0]) #convert timestamp to matplotlib.dates num format
         self.x.append(i[0])
     self.x0 = min(self.x)
     self.x1 = max(self.x)
     if self.k_lines == None and self.k_patches == None:
         self.k_lines,self.k_patches = candlestick_ochl(self.ax1, tochlva)#, width=0.4, colorup='#77d879', colordown='#db3f3f')
     else:
         self.k_lines,self.k_patches = candlestick_ochl(self.ax1, tochlva)
         
     self.ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d'))
     self.ax1.xaxis.set_major_locator(mdates.DayLocator())
     plt.xticks(rotation=45)
예제 #32
0
파일: window.py 프로젝트: jjmonster/trade
def ta_graphic(indicator, ax, *params):
    df = params[0]
    if indicator == 'kline':
        candlestick_ochl(ax, np.array(df))#, width=0.4, colorup='#77d879', colordown='#db3f3f')
    else:
        line_color = ('b','g','r','c','m','y','k')#,'w')
        line_maker = ('.',',','o') ###...
        line_style = ('-', '--', '-.', ':')
        t = list(map(datetime.fromtimestamp, df['t']))
        for i in range(df.columns.size): #exclude 't'
            if df.columns[i] == 't':
                continue
            col = df[df.columns[i]]
            cms = line_color[int(i%len(line_color))]+line_maker[0]+line_style[int(i/len(line_color))]
            ax.plot(t, col, cms)

    ax.set_title(indicator, fontproperties="SimHei")
    ax.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d %H')) #%H:%M:%S'))
    ax.xaxis.set_major_locator(mdates.DayLocator()) #HourLocator())
    ax.legend()
    plt.xticks(rotation=45)
    #plt.show()

    if len(params) > 1:
        hist = params[1]
        if hist.index.size > 0:
            for i in hist.index:
                row = hist.loc[i]
                time = datetime.fromtimestamp(row['t'])
                type = row['type']
                price = row['price']
                if type == 'open_buy':
                    cms = 'r+'
                elif type == 'margin_buy' or type == 'loss_buy':
                    cms = 'rx'
                elif type == 'open_sell':
                    cms = 'y+'
                elif type == 'margin_sell' or type == 'loss_sell':
                    cms = 'yx'
                ax.plot([time], [price], cms)