Exemplo n.º 1
0
def candlesticks(ticker, date, interval, tickers=[]):
    if len(tickers) == 0:
        SPX = priceHistoryConfigs(ticker, date, interval)
        mc = mpf.make_marketcolors(up='g', down='r')
        s = mpf.make_mpf_style(marketcolors=mc)
        setup = dict(type='candle',
                     mav=(7, 11, 20),
                     volume=True,
                     figratio=(11, 8),
                     figscale=0.85,
                     style=s)
        mpf.plot(SPX.iloc[0:len(SPX) - 1], **setup)
        plt.show()
    else:
        for k in tickers:
            SPX = priceHistoryConfigs(k[0], date, interval)
            mc = mpf.make_marketcolors(up='g', down='r')
            s = mpf.make_mpf_style(marketcolors=mc)
            setup = dict(type='candle',
                         mav=(7, 11, 20),
                         volume=True,
                         figratio=(11, 8),
                         figscale=0.85,
                         style=s)
            plt.figure(runner)
            mpf.plot(SPX.iloc[0:len(SPX) - 1], **setup)
        plt.show()
Exemplo n.º 2
0
def ohlc_to_image(tickers,
                  start=0,
                  end=0,
                  category="daily",
                  dpi=300,
                  type="candle"):
    for ticker in tickers:

        path = f'./datasets/{ticker}/'
        if not os.path.isdir(path):
            os.mkdir(path)

        try:
            print(f"{ticker} : start -> ", end="")

            csv_data = pd.read_csv(f"./datasets/{category}/{ticker}.csv",
                                   index_col=0,
                                   parse_dates=True)
            if (start != 0) or (end != 0):
                csv_data = csv_data[start:end]
            csv_data.index.name = "Date"

            mc = mpf.make_marketcolors(up='r', down='b')
            #up과 down에는 색상 지정할수 있다. 예 #ffffff
            s = mpf.make_mpf_style(marketcolors=mc)
            file_path = path + f'{ticker}_{type}'

            savefig = dict(fname=file_path, dpi=300, pad_inches=0.25)
            mpf.plot(csv_data, type=type, style=s, savefig=savefig)

        except err:
            print(err)
            print(f"{ticker} 에서 오류발생")
Exemplo n.º 3
0
def make_mav_candlestick_mplfinance(df, save_png: str) -> None:
    """
    mplfinanceを使って移動平均線+ローソク足画像作成する
    ※論文では出来高入れない方が精度良さそうだったから出来高は入れない
    """
    import sys

    current_dir = pathlib.Path(__file__).resolve().parent
    sys.path.append(str(current_dir) + "/../GitHub/mplfinance/src")
    import mplfinance as mpf

    kwargs = dict(
        type="candle",
        figratio=(1.5, 1.5),
        figscale=1,
        title="",
        ylabel="",
        ylabel_lower="",
        mav=(5, 10),
    )
    mc = mpf.make_marketcolors(up="#FF0000", down="#0000FF", inherit=True)
    s = mpf.make_mpf_style(base_mpf_style="nightclouds", marketcolors=mc, gridstyle="")
    mpf.plot(
        df, **kwargs, style=s, is_not_set_visible=True, savefig=save_png,
    )
Exemplo n.º 4
0
    def plot(df: pd.DataFrame, title: str, mav: Tuple[int, int]):
        """

        Args:
            df
            title:
            mav:

        Returns:

        """
        style = mpf.make_mpf_style(base_mpf_style='yahoo',
                                   marketcolors=mpf.make_marketcolors(
                                       up='r',
                                       down='g',
                                       edge='',
                                       wick='inherit',
                                       volume='inherit'))
        mpf.plot(df,
                 type='candle',
                 mav=mav,
                 volume=True,
                 style=style,
                 title=title,
                 ylabel_lower='Shares')
Exemplo n.º 5
0
def ohlc_plot_protype(ohlc_data, code=None, codename=None, title=None):
    # 暗色主题
    plt.style.use('Solarize_Light2')

    # 正常显示中文字体
    plt.rcParams['font.sans-serif'] = ['Microsoft YaHei']

    # 设定布局
    fig = plt.figure(figsize=(22, 9))
    plt.subplots_adjust(left=0.04, right=0.96)
    if (title is None):
        fig.suptitle(u'阿财的 {:s}({:s})量化学习笔记绘制K线DEMO'.format(codename, code),
                     fontsize=16)
    else:
        fig.suptitle(title, fontsize=16)
    ax1 = fig.add_subplot(111)

    # 绘制K线
    ohlc_data = ohlc_data.reset_index([1], drop=False)
    mc_stock_cn = mpf.make_marketcolors(up='r', down='g')
    s_stock_cn = mpf.make_mpf_style(marketcolors=mc_stock_cn)
    mpf.plot(data=ohlc_data, ax=ax1, type='candle', style=s_stock_cn)

    # 设定最标轴时间
    datetime_index = ohlc_data.index.get_level_values(level=0).to_series()
    DATETIME_LABEL = datetime_index.apply(
        lambda x: x.strftime("%Y-%m-%d %H:%M")[2:16])
    ax1.set_xticks(
        range(0, len(DATETIME_LABEL), round(len(DATETIME_LABEL) / 12)))
    ax1.set_xticklabels(DATETIME_LABEL[::round(len(DATETIME_LABEL) / 12)])
    ax1.grid(True)
    return ax1
Exemplo n.º 6
0
    def create(data, csv_rows, X):
        n = csv_rows - 22
        q = 0
        w = 50
        num = 1
        while w < n:

            s = mpf.make_mpf_style(base_mpf_style='yahoo',
                                   gridcolor='white',
                                   figcolor='white',
                                   edgecolor='white',
                                   facecolor='white')
            mpf.plot(
                data[q:w],
                type='candle',
                show_nontrading=False,
                savefig=dict(
                    fname=
                    'scripts/Finance_Data/Chart_Snapshot/TEST/operation/{name}_{number}test.jpg'
                    .format(name=X, number=num)),
                style=s,
                axisoff=False)
            f = open("darknet/data/test.txt", 'a')
            f.write(
                "\nscripts/Finance_Data/Chart_Snapshot/TEST/operation/{name}_{number}test.jpg"
                .format(name=X, number=num))
            q += 50
            w += 50
            num += 1
Exemplo n.º 7
0
def draw_candle_chart(stock_id):
    stock_id = str(stock_id) + ".TW"  # Yahoo Finance 的 代號為台灣的代號 + .TW
    data = yf.Ticker(stock_id)  # 抓取資料

    # 1mo = 1個月,max 可以把所有期間的資料都下載
    ohlc = data.history(period="2mo")
    ohlc = ohlc.loc[:, ["Open", "High", "Low", "Close",
                        "Volume"]]  # 選擇製圖需要欄位(開高低收量)

    # 調整圖表標示顏色
    mc = fplt.make_marketcolors(
        up='tab:red',
        down='tab:green',  # 上漲為紅,下跌為綠
        wick={
            'up': 'red',
            'down': 'green'
        },  # 影線上漲為紅,下跌為綠
        volume='tab:green',  # 交易量顏色
    )

    s = fplt.make_mpf_style(marketcolors=mc)  # 定義圖表風格

    fplt.plot(
        ohlc,  # 開高低收量的資料
        type='candle',  # 類型為蠟燭圖,也就是 K 線圖
        style=s,  # 套用圖表風格
        title=stock_id,  # 設定圖表標題
        ylabel='Price ($)',  # 設定 Y 軸標題
        volume=True,
        savefig='stock_Kbar.png',  # 儲存檔案
    )
Exemplo n.º 8
0
def draw_chart(symbol, hist):
    mc = fplt.make_marketcolors(up='tab:blue',
                                down='tab:red',
                                edge='black',
                                wick={
                                    'up': 'blue',
                                    'down': 'red'
                                },
                                volume='green',
                                alpha=1.0)
    s = fplt.make_mpf_style(marketcolors=mc,
                            mavcolors=["yellow", "orange", 'brown'])
    image_file = f"./live_graphs/{symbol}_{hist.index[-1].isoformat().replace(':', '-')}.png"
    fplt.plot(hist.iloc[-46:],
              type='candle',
              style=s,
              volume=True,
              axisoff=True,
              mav=(5, 8, 13),
              figsize=(3.2, 3.2),
              xlim=(12.5, 44.5),
              savefig=image_file,
              tight_layout=True,
              returnfig=False)
    return image_file
Exemplo n.º 9
0
def gen_graph(stock, timespan, multiplier, start, end):
    r = requests.get(f'https://api.polygon.io/v2/aggs/ticker/{stock.upper()}/range/{multiplier}/{timespan}/{start.strftime("%Y-%m-%d")}/{end.strftime("%Y-%m-%d")}?apiKey={VERY_SECRET_LAUNCH_CODES.HYDROGEN_LAUNCH_CODE()}')

    # Copy pasted code to format dataframe for mplfinance
    df = pd.DataFrame(r.json()['results'])
    est = pytz.timezone('US/Eastern')
    utc = pytz.utc
    df.index = [datetime.utcfromtimestamp(ts / 1000.).replace(tzinfo=utc).astimezone(est) for ts in df['t']]
    df.index.name = 'Date'
    df.columns = ['Volume', 'Volume Weighted', 'Open', 'Close', 'High', 'Low', 'Time', 'Num Items']

    # Very dank custom mpl theme copyright your mom LLC
    mc = mpf.make_marketcolors(up='#00a320', down='#ff3334', inherit=True)
    s = mpf.make_mpf_style(base_mpf_style='nightclouds', marketcolors=mc, gridaxis='horizontal', gridcolor='#454545', gridstyle='solid', edgecolor='#454545', facecolor='#000000')

    # This is probably the most autistic shit I have ever written in my life
    delta = end - start

    weekend = {5, 6}
    splits = []
    for i in range(delta.days + 1):
        if (start + timedelta(days=i)).weekday() not in weekend:
            splits.append((start + timedelta(days=i)).strftime("%Y-%m-%d" + " 09:30"))
            splits.append((start + timedelta(days=i)).strftime("%Y-%m-%d" + " 16:00"))

    # Saves graph
    saving_params = dict(fname='plot.png', dpi=1200)
    mpf.plot(df, type='candle', volume=True, style=s, savefig=saving_params, vlines=dict(vlines=splits, linewidths=0.5, linestyle='-.', colors="#454545"))
Exemplo n.º 10
0
def plot_candle(df,start_index,end_index,bottom,output_path):
    #df = pd.read_csv(r'D:\stock\history\000001.SZ.csv')
    sub_df = df[['trade_date','open','high','low','close','vol']].copy()
    # daily = sub_df.head(30)
    sub_df.rename(columns={'trade_date':'Date', 'open':'Open', 'high':'High','low':'Low', 'close':'Close','vol':'Volume'}, inplace = True)

    # daily['Date'] = pd.to_datetime(daily['Date'])
    sub_df[['Date']] = sub_df[['Date']].astype(str)
    # print(sub_df['Date'])
    sub_df['Date'] = pd.to_datetime(sub_df['Date'])
    start_date = sub_df['Date'][start_index]
    end_date = sub_df['Date'][end_index]
    sub_df.set_index("Date", inplace=True)


    kwargs = dict(type='candle',volume=True,figratio=(11,8),figscale=0.85)
    mc = mpf.make_marketcolors(up='r',down='g',volume='in')
    s = mpf.make_mpf_style(marketcolors=mc)
    # mpf.plot(daily,**kwargs,style=s,savefig='testsave.png')
    saved_filename = '{}_{}.png'.format(str(start_date).split(' ')[0],df['ts_code'][0].split('.')[0])
    outputfile = os.path.join(output_path,saved_filename)

    # mpf.plot(sub_df, **kwargs, style=s,vlines=dict(vlines=[start_date,end_date],linewidths=(0.5,0.5),linestyle='-.'),\
    #          hlines=dict(hlines=[bottom],linewidths=(0.5),colors=['r'],linestyle='-.'),savefig=outputfile)

    mpf.plot(sub_df, **kwargs, style=s,\
             hlines=dict(hlines=[bottom],linewidths=(0.5),colors=['r'],linestyle='-.'),savefig=outputfile,title=saved_filename)
Exemplo n.º 11
0
def chart():
    df = dataframe()
    df.index = pd.DatetimeIndex(df['timestamp'])
    df = df.iloc[::-1]
    s = mpf.make_mpf_style(base_mpf_style='charles', gridcolor='#555555', gridstyle="--", rc={'axes.edgecolor': 'white', 'font.size': 5})
    fig, axlist = mpf.plot(df, type='candle', style=s, title= coin, ylabel = 'Price (€)', volume=True, warn_too_much_data=9999999, returnfig=True)
    mpf.show(block=True)
Exemplo n.º 12
0
def plot_graph(ticker, df):

    mc = mpl.make_marketcolors(up='green', down='red', inherit=True)
    s = mpl.make_mpf_style(base_mpl_style='ggplot',
    marketcolors=mc, y_on_right=False, mavcolors=['#1f77b4', '#ff7f0e', '#2ca02c'], gridcolor='#b6b6b6',
    gridstyle='--', figcolor='#eee9e9', edgecolor='#8b8585')

    ap = [mpl.make_addplot(df['Bought'], type='scatter',markersize=200,marker='>', color='#29854f', panel=1),
          mpl.make_addplot(df['Sold'], type='scatter', marker='<', markersize=200, color='#720c06', panel=1),
          mpl.make_addplot(df['ATR'], type='line', panel=0, ylabel='ATR', color='#8774AB', secondary_y=False, ylim=(
              min(df['ATR']), max(df['ATR'])
          )),
          mpl.make_addplot(df['Lower B'], type='line', panel=1, color='#3838ea', alpha=0.50),
          mpl.make_addplot(df['Upper B'], type='line', panel=1, color='#3838ea', alpha=0.50),
          mpl.make_addplot(df['70'], panel=2, type='line', secondary_y=False, ylim=(0, 100), color='r', alpha=0.25),
          mpl.make_addplot(df['30'], panel=2, type='line', secondary_y=False, ylim=(0, 100), color='g', alpha=0.25),
          mpl.make_addplot(df['RSI'], panel=2, type='line', ylabel='RSI', secondary_y=False, ylim=(0, 100)),
          mpl.make_addplot(df['SMA_20'], panel=1, type='line', alpha=0.5, color='orange'),
          mpl.make_addplot(df['macdline'], type='line', color='purple', panel=3, secondary_y=False),
          mpl.make_addplot(df['signalline'], type ='line', color='orange', panel=3, secondary_y=False),
          mpl.make_addplot(df['hist'], type='bar',panel=3, ylabel='MACD',color='#9c9796'),
          mpl.make_addplot(df['0'],type='line',panel=3,color='k',secondary_y=False,
                           ylim=((min(df['signalline']-1), (max(df['signalline']+0.5))))),
          mpl.make_addplot(df['Chandelier_Exit'],type='scatter',marker='_', panel=1)]
    mpl.plot(df, title=ticker, type='candle', style=s, ylabel='Price'
        , addplot=ap, panel_ratios=(0.7, 2, 0.7, 0.8), figratio=(2, 1),
        figscale=1.1, datetime_format='%m-%Y', tight_layout=True, main_panel=1,
             ylim=(min(df['Adj Close']-2), max(df['Adj Close']+2)),
             fill_between=dict(y1=df['Lower B'].values, y2=df['Upper B'].values, color='#f2ad73', alpha=0.20))
    plt.show()
def style_test():
    now = datetime.datetime.today().strftime('%Y%m%d')
    df_1 = get_stock_price_df(stock_code='002415.SZ',
                              start_date='20160101',
                              end_date=now)

    my_color = mpf.make_marketcolors(up='red',
                                     down='green',
                                     edge='inherit',
                                     wick='inherit',
                                     volume='inherit')
    my_style = mpf.make_mpf_style(marketcolors=my_color,
                                  gridaxis='both',
                                  gridstyle='-.',
                                  y_on_right=True)

    # fig = plt.figure()
    # 建立划分1行1列的子图,取第1幅子图
    # ax1 = fig.add_subplot(1, 1, 1)
    mpf.plot(df_1,
             type='candle',
             volume=True,
             figscale=1.5,
             style=my_style,
             title='****报价',
             figratio=(5, 5),
             ylabel='价格',
             ylabel_lower='成交量',
             savefig='my_image.png')

    print('end')
Exemplo n.º 14
0
def plot_kline(stock_data, volume=False, mav=(5, 10)):
    rename_map = {
        "交易日期": "Date",
        "开盘价": "Open",
        "收盘价": "Close",
        "最高价": "High",
        "最低价": "Low",
        "成交量": "Volume",
    }

    stock_data = stock_data.rename(columns=rename_map)
    stock_data = stock_data[list(rename_map.values())]
    stock_data.set_index('Date', inplace=True)

    print(stock_data)
    """
    up: 设置上涨K线的颜色
    down: 设置下跌K线的颜色
    edge=inherit: K线图边缘和主题颜色保持一致
    volume=in: 成交量bar的颜色继承K线颜色
    wick=in: 上下引线颜色继承K线颜色
    """
    mc = mpf.make_marketcolors(up='r',
                               down='g',
                               volume='in',
                               edge='inherit',
                               wick='in')
    s = mpf.make_mpf_style(marketcolors=mc)
    mpf.plot(stock_data,
             type='candle',
             style=s,
             volume=volume,
             mav=mav,
             figratio=(9, 6),
             figscale=2)
Exemplo n.º 15
0
def plot_profitline(stock_data,
                    profit_ratio,
                    title='',
                    output=os.path.join(_test_path, 'profitline.jpg')):
    stock_data['close'] = profit_ratio
    stock_profitline = stock_data.set_index("date")
    stock_profitline.index = pd.to_datetime(stock_profitline.index)
    stock_profitline = stock_profitline.astype(float)
    kwargs = dict(type='line',
                  volume=False,
                  ylabel='Return Rate',
                  figratio=(11, 8),
                  figscale=0.85)
    style = mpf.make_mpf_style(base_mpf_style='yahoo', rc={'font.size': 8})
    fig, axes = mpf.plot(stock_profitline,
                         **kwargs,
                         style=style,
                         scale_padding={
                             'left': 0.1,
                             'top': 1,
                             'right': 1,
                             'bottom': 1
                         },
                         returnfig=True)
    axes[0].yaxis.set_major_formatter(
        matplotlib.ticker.PercentFormatter(xmax=1.0))
    axes[0].set_title(title)
    fig.savefig(output, dpi=300)
    plt.close(fig)
Exemplo n.º 16
0
    def __call__(self, show_buy_and_sell=False, analyze_positions=False, make_plot_param={}):
        self.cal_technical_index()
        if show_buy_and_sell:
            res_list = []
            data_dict = {}
            item_list = ["date", "open", "close", "low", "high", "volume", "trade", "MACD", "MACDsignal", "MACDhist",
                         "slowk", "slowd", "slowj"]
            for index, row in self.data.iterrows():
                for item in item_list:
                    data_dict[item] = row[item]
                res_list.append(data_dict.copy())
            return json.dumps(res_list, indent=2, ensure_ascii=False)
        self.strategy_exec()
        if analyze_positions:
            self.eval_index()

        is_make_plot = make_plot_param.get("is_make_plot", False)
        if is_make_plot:
            self.data['Date'] = pd.to_datetime(self.data["date"])
            self.data.set_index('Date', inplace=True)

            my_color = mpf.make_marketcolors(up="red", down="green", edge="inherit", volume="inherit")
            my_style = mpf.make_mpf_style(marketcolors=my_color)
            add_plot = [mpf.make_addplot(self.data[['wma10']])]
            mpf.plot(self.data, type="line", ylabel="price", style=my_style, volume=True, ylabel_lower="volume",
                     addplot=add_plot)
Exemplo n.º 17
0
 def plot_benchmark(self, stock_code):
     import pandas as pd
     import math
     from dev_global.env import TIME_FMT
     df = self.mysql.select_values(
         stock_code,
         'trade_date,open_price,close_price,highest_price,lowest_price,volume')
     # data cleaning
     df.columns = ['Date', 'Open', 'Close', 'High', 'Low', 'Volume']
     df['Date'] = pd.to_datetime(df['Date'])
     df.set_index('Date', inplace=True)
     # data constructing
     LEN = 70
     df = df[-LEN:]
     import mplfinance as mpf
     usr_color = mpf.make_marketcolors(up='red', down='green')
     usr_style = mpf.make_mpf_style(marketcolors=usr_color)
     plt, _ = mpf.plot(
         df,returnfig=True, type='candle', mav=(5,10,20),
         volume=True, title=stock_code, style=usr_style,
         datetime_format='%Y-%m-%d'
         )
     #img_path = f"/home/friederich/Documents/dev/neutrino/applications/template/{stock_code}.png"
     img_path = f"/var/www/neutrino/static/images/{stock_code}.png"
     plt.savefig(img_path, format='png')
Exemplo n.º 18
0
def get_style(background_colour, line_colour, text_colour):
    market_colours = mpf.make_marketcolors(up="g",
                                           down="r",
                                           edge=background_colour,
                                           wick=line_colour)

    style_dict = {
        "xtick.color": line_colour,
        "ytick.color": line_colour,
        "xtick.labelcolor": text_colour,
        "ytick.labelcolor": text_colour,
        "axes.spines.top": False,
        "axes.spines.right": False,
        "axes.labelcolor": text_colour,
        "axes.labelsize": 18
    }

    style = mpf.make_mpf_style(marketcolors=market_colours,
                               facecolor=background_colour,
                               edgecolor=line_colour,
                               figcolor=background_colour,
                               gridcolor=line_colour,
                               gridstyle="--",
                               rc=style_dict)
    return style
Exemplo n.º 19
0
def run(pickle_file=PICKLE_FILE):

    mc = mpf.make_marketcolors(up='cyan', down='fuchsia', inherit=True)
    style = mpf.make_mpf_style(base_mpf_style='nightclouds',
                               gridstyle='',
                               marketcolors=mc)

    fig = mpf.figure(style=style, figsize=(19, 20))

    plt.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.95, 0.95)

    df1 = utils.try_to_get_df(pickle_file)
    ntickets = len(df1.groupby('Papel').first().index.to_list())

    positions = []
    j1 = 0

    for i in range(ntickets):
        if ntickets % 2 != 0 and i == ntickets - 1:
            positions.append((j1 + 1, j1 + 68))
            j1 += 80
        elif i % 2 == 0:
            positions.append((j1 + 1, j1 + 68))
            positions.append((j1 + 5, j1 + 72))
            j1 += 80

    dimension = [j1 / 8, 8]

    global axes
    axes = []
    for pos in positions:
        ax = fig.add_subplot(dimension[0], dimension[1], pos)
        axes.append(ax)

    a = ScrollableWindow(fig, analysis, pickle_file)
Exemplo n.º 20
0
    def plot_candlestick(self, df, addplot_list=None):
        print('[Plot]: plot_candlestick()')
        # 设置基本参数
        # type:绘制图形的类型,有candle, renko, ohlc, line等
        # 此处选择candle,即K线图
        # mav(moving average):均线类型,此处设置7,30,60日线
        # volume:布尔类型,设置是否显示成交量,默认False
        # title:设置标题
        # y_label_lower:设置成交量图一栏的标题
        # figratio:设置图形纵横比
        # figscale:设置图形尺寸(数值越大图像质量越高)
        kwargs = dict(
            type='candle',
            volume=True,
            # title='\nA_stock %s candle_line' % (symbol),
            ylabel='OHLC Candles',
            ylabel_lower='Shares\nTraded Volume',
            figratio=(15, 10),
            figscale=5)

        # 设置marketcolors
        # up:设置K线线柱颜色,up意为收盘价大于等于开盘价
        # down:与up相反,这样设置与国内K线颜色标准相符
        # edge:K线线柱边缘颜色(i代表继承自up和down的颜色),下同。详见官方文档)
        # wick:灯芯(上下影线)颜色
        # volume:成交量直方图的颜色
        # inherit:是否继承,选填
        mc = mpf.make_marketcolors(up='red',
                                   down='green',
                                   edge='i',
                                   wick='i',
                                   volume='in',
                                   inherit=True)

        # 设置图形风格
        # gridaxis:设置网格线位置
        # gridstyle:设置网格线线型
        # y_on_right:设置y轴位置是否在右
        s = mpf.make_mpf_style(gridaxis='both',
                               gridstyle='-.',
                               y_on_right=False,
                               marketcolors=mc)

        # 设置均线颜色,配色表可见下图
        # 建议设置较深的颜色且与红色、绿色形成对比
        # 此处设置七条均线的颜色,也可应用默认设置
        mpl.rcParams['axes.prop_cycle'] = cycler(color=[
            'dodgerblue', 'deeppink', 'navy', 'teal', 'maroon', 'darkorange',
            'indigo'
        ])

        # 设置线宽
        mpl.rcParams['lines.linewidth'] = .5

        if addplot_list is not None:
            addplot_list = self._make_addplot(addplot_list)
            mpf.plot(df, **kwargs, style=s, addplot=addplot_list)
        else:
            kwargs['mav'] = (7, 30, 60)
            mpf.plot(df, **kwargs, style=s)
Exemplo n.º 21
0
def image_preprocessing(pattern_data, pattern_csv):
    #pattern_data for shown pattern
    #pattern csv for get the data of shown_pattern
    uuid_list = []
    whole_data = pattern_data['bull'] + pattern_data['bear']
    path = path = os.path.join(os.getcwd(), 'ml_model/image_db/')
    for data in whole_data:
        #get the timedata
        date = data[1]
        nei_data = pattern_csv.iloc[pattern_csv.index.get_loc(date) -
                                    2:pattern_csv.index.get_loc(date) + 3]
        #uuid for image name
        name = uuid.uuid4()
        uuid_list.append((date, name))
        #시각과 image 이름을 기억한다.
        #mplplot setting
        mc = mpf.make_marketcolors(up='r', down='b')
        s = mpf.make_mpf_style(marketcolors=mc)
        savefig = dict(fname=f'{path}/{name}.png',\
        dpi=50,pad_inches=0,bbox_inches='tight')
        #plot
        mpf.plot(nei_data,
                 axisoff=True,
                 type='candle',
                 style=s,
                 savefig=savefig)

    return uuid_list
Exemplo n.º 22
0
def plot_ka(ka, file_image, mav=(5, 20, 120, 250), max_k_count=1000, dpi=50):
    """绘制 ka,保存到 file_image"""
    df = pd.DataFrame(ka.kline)
    df.rename(
        {
            "open": "Open",
            "close": "Close",
            "high": "High",
            "low": "Low",
            "vol": "Volume"
        },
        axis=1,
        inplace=True)
    df.index = pd.to_datetime(df['dt'])
    df = df.tail(max_k_count)
    kwargs = dict(type='candle', mav=mav, volume=True)

    bi_xd = [[(x['dt'], x['bi']) for _, x in df.iterrows() if x['bi'] > 0],
             [(x['dt'], x['xd']) for _, x in df.iterrows() if x['xd'] > 0]]

    mc = mpf.make_marketcolors(up='red',
                               down='green',
                               edge='i',
                               wick='i',
                               volume='in',
                               inherit=True)

    s = mpf.make_mpf_style(gridaxis='both',
                           gridstyle='-.',
                           y_on_right=False,
                           marketcolors=mc)

    mpl.rcParams['font.sans-serif'] = ['KaiTi']
    mpl.rcParams['font.serif'] = ['KaiTi']
    mpl.rcParams['font.size'] = 48
    mpl.rcParams['axes.unicode_minus'] = False
    mpl.rcParams['lines.linewidth'] = 1.0

    title = '%s@%s(%s - %s)' % (ka.symbol, ka.name, df.index[0].__str__(),
                                df.index[-1].__str__())
    fig, axes = mpf.plot(df,
                         columns=['Open', 'High', 'Low', 'Close', 'Volume'],
                         style=s,
                         title=title,
                         ylabel='K线',
                         ylabel_lower='成交量',
                         **kwargs,
                         alines=dict(alines=bi_xd,
                                     colors=['r', 'g'],
                                     linewidths=8,
                                     alpha=0.35),
                         returnfig=True)

    w = len(df) * 0.15
    fig.set_size_inches(w, 30)
    ax = plt.gca()
    ax.set_xbound(-1, len(df) + 1)
    fig.savefig(fname=file_image, dpi=dpi, bbox_inches='tight')
    plt.close()
 def show_adv(self, ftitle="Stock", **kwargs):
     """
     顯示進階K線圖,K線搭配一主圖指標與兩個副圖指標
     使用mplfinance實現之(panel method)
     已定義的作圖參數:
     ti_main = "SMA" / "VWMA"
     ti_sub1 = "KD" / "MACD" / "STD" / "VIX" / "CVOL"
     ti_sub2 = "KD" / "MACD" / "STD" / "VIX" / "CVOL"
     """
     self._setrun(**kwargs)  # 進行參數驗證與指標計算
     dest = Dpath + '\\' + ftitle + ".png"
     mc = mpf.make_marketcolors(up='r', down='g', inherit=True)
     ms = mpf.make_mpf_style(base_mpf_style = "yahoo", \
                             marketcolors = mc, y_on_right = True)
     # 不支援中文字型,圖表文字需為英文
     mfargs = dict(type = "candle", volume = True, \
                   columns = ("O", "H", "L", "C", "V"), \
                   show_nontrading = False, returnfig = True, \
                   figsize = (self.fx, self.fy), \
                   title = ftitle, style = ms, ylabel = "Price", \
                   ylabel_lower = "Volume in shares", \
                   panel_ratios = (1, 1))
     aps = []
     if "ti_main" in kwargs:
         tidf = self.val_main.copy()
         isma = False
         if kwargs["ti_main"] == "SMA" or kwargs["ti_main"] == "VWMA":
             isma = True  # 主圖技術指標為均線類型
         for i in range(0, tidf.shape[1]):
             aps.append(mpf.make_addplot(tidf.iloc[:, i], \
                                         color = MA_Colors[i]))
             if isma:  # 補均線扣抵記號,配色同均線
                 aps.append(mpf.make_addplot(self.sig_main.iloc[:, i], \
                                             type = "scatter", \
                                             markersize = 200, \
                                             marker = '^', \
                                             color = MA_Colors[i]))
     pid = 1  # Panel ID = 0 for candlestick, 1 for volume
     if "ti_sub1" in kwargs:  # pid = 2
         pid += 1
         ap2 = self._setsubti(self.val_sub1, kwargs["ti_sub1"], pid)
         for item in ap2:
             aps.append(item)
     if "ti_sub2" in kwargs:  # pid = 3 (or 2 if ti_sub1 is not assigned)
         pid += 1
         ap3 = self._setsubti(self.val_sub2, kwargs["ti_sub2"], pid)
         for item in ap3:
             aps.append(item)
     if len(aps) > 0:
         if pid == 2:
             mfargs["panel_ratios"] = (2, 1, 1)
         elif pid == 3:
             mfargs["panel_ratios"] = (3, 1, 1, 1)
         fig, axes = mpf.plot(self.df, addplot=aps, **mfargs)
     else:
         fig, axes = mpf.plot(self.df, **mfargs)
     mpf.show()
     fig.savefig(dest)
     return None
Exemplo n.º 24
0
async def candle(message: types.Message, regexp_command):
    chat_id = message.chat.id
    try:
        coin = regexp_command.group(1)
        trades = get_ohcl_trades(coin, 180)
        trades = trades[-60:]
        df = pd.DataFrame(
            trades, columns='time open high low close volume amount'.split())
        df['time'] = pd.DatetimeIndex(df['time'] * 10**9)
        df.set_index('time', inplace=True)

        df['MA20'] = df['close'].rolling(window=20).mean()
        df['20dSTD'] = df['close'].rolling(window=20).std()

        df['Upper'] = df['MA20'] + (df['20dSTD'] * 2)
        df['Lower'] = df['MA20'] - (df['20dSTD'] * 2)

        rsi_df = get_rsi_df(df)
        df = df.tail(30)
        rsi_df = rsi_df.tail(30)

        apd = [
            mpf.make_addplot(df['Lower'], color='#EC407A', width=0.9),
            mpf.make_addplot(df['Upper'], color='#42A5F5', width=0.9),
            mpf.make_addplot(df['MA20'], color='#FFEB3B', width=0.9)
        ]

        if rsi_df is not None:
            apd.append(
                mpf.make_addplot(rsi_df,
                                 color='#FFFFFF',
                                 panel=1,
                                 ylabel='RSI',
                                 ylim=[0, 100]))
        kwargs = dict(type='candle',
                      ylabel=coin.upper() + ' Price in $',
                      volume=True,
                      figratio=(3, 2),
                      figscale=1.5,
                      addplot=apd)
        mpf.plot(df, **kwargs, style='nightclouds')
        mc = mpf.make_marketcolors(up='#69F0AE', down='#FF5252', inherit=True)
        s = mpf.make_mpf_style(base_mpf_style='nightclouds',
                               facecolor='#121212',
                               edgecolor="#131313",
                               gridcolor="#232323",
                               marketcolors=mc)
        mpf.plot(df,
                 **kwargs,
                 style=s,
                 scale_width_adjustment=dict(volume=0.55, candle=0.8),
                 savefig=coin + '-mplfiance.png')
        await bot.send_photo(chat_id=chat_id,
                             photo=InputFile(coin + '-mplfiance.png'))
    except Exception as e:
        logging.error("ERROR Making chart:" + str(e))
        await bot.send_message(chat_id=chat_id,
                               text="Failed to create chart",
                               parse_mode="HTML")
Exemplo n.º 25
0
def build_graph(data):
    imgdata = BytesIO()
    style = mpf.make_mpf_style(base_mpf_style='yahoo', rc={'font.size': 6})
    mpf.plot(data, type='candle', style=style, figscale=0.5, savefig=imgdata)
    imgdata.seek(0)
    string = base64.b64encode(imgdata.read())
    uri = urllib.parse.quote(string)
    return uri
Exemplo n.º 26
0
def plot(df: pd.DataFrame,
         title: Optional[str] = None,
         mav: Optional[Tuple[int]] = None,
         alines: Optional[dict] = None):
    color = mpf.make_marketcolors(up='red', down='cyan', inherit=True)
    style = mpf.make_mpf_style(marketcolors=color)

    # # 设置外观效果
    # plt.rc('font', family='Microsoft YaHei')  # 用中文字体,防止中文显示不出来
    # plt.rc('figure', fc='k')  # 绘图对象背景图
    # plt.rc('text', c='#800000')  # 文本颜色
    # plt.rc('axes', axisbelow=True, xmargin=0, fc='k', ec='#800000', lw=1.5, labelcolor='#800000',
    #        unicode_minus=False)  # 坐标轴属性(置底,左边无空隙,背景色,边框色,线宽,文本颜色,中文负号修正)
    # plt.rc('xtick', c='#d43221')  # x轴刻度文字颜色
    # plt.rc('ytick', c='#d43221')  # y轴刻度文字颜色
    # plt.rc('grid', c='#800000', alpha=0.9, ls=':', lw=0.8)  # 网格属性(颜色,透明值,线条样式,线宽)
    # plt.rc('lines', lw=0.8)  # 全局线宽
    #
    # # 创建绘图对象和4个坐标轴
    # figure = plt.figure(figsize=(16, 8))
    # left, width = 0.01, 0.98
    # ax1 = figure.add_axes([left, 0.6, width, 0.35])  # left, bottom, width, height
    # ax2 = figure.add_axes([left, 0.45, width, 0.15], sharex=ax1)  # 共享ax1轴
    # ax3 = figure.add_axes([left, 0.25, width, 0.2], sharex=ax1)  # 共享ax1轴
    # ax4 = figure.add_axes([left, 0.05, width, 0.2], sharex=ax1)  # 共享ax1轴
    # plt.setp(ax1.get_xticklabels(), visible=False)  # 使x轴刻度文本不可见,因为共享,不需要显示
    # plt.setp(ax2.get_xticklabels(), visible=False)  # 使x轴刻度文本不可见,因为共享,不需要显示
    # plt.setp(ax3.get_xticklabels(), visible=False)  # 使x轴刻度文本不可见,因为共享,不需要显示
    #
    # # 绘制蜡烛图
    # mpf.c(ax, data['open'], data['close'], data['high'], data['low'],
    #                       width=0.5, colorup='r', colordown='green',
    #                       alpha=0.6)

    kwargs: dict = {
        'type':
        'candle',
        'style':
        style,
        'volume':
        True,
        'figratio': (3, 1),
        'figscale':
        20,
        'savefig':
        dict(fname=
             f'D:\\Test_{datetime.now().strftime("%Y-%m-%d_%H-%M-%S")}.png',
             bbox_inches='tight')
    }
    if title:
        kwargs['title'] = title
    if mav:
        kwargs['mav'] = mav
    if alines:
        kwargs['alines'] = alines

    mpf.plot(df, **kwargs)
    mpf.show()
Exemplo n.º 27
0
def mpf_Candlestick():
    #INPUT
    excel_file = "YOUR PATH/Data/Stock_YTS.xlsx"
    #Stock INPUT
    file = open('YOUR PATH/stocks/stocks.txt', 'r')
    #Produce data visuals for desired stocks
    for stock in file:
        # Parse Stock Symbols
        stock = stock.strip()

        # Creating sql engine to use SQL/reading Excel sheets
        engine = create_engine('sqlite://', echo=False)
        df = pd.read_excel(excel_file, sheet_name=stock)

        # Creating Tables to extract data
        df.to_sql('Monthly', engine, if_exists='replace', index=False)

        #Query1 - Filtering monthly stock data using SQL method
        q1 = engine.execute("Select * FROM Monthly \
                                WHERE DATE LIKE '%2020%' \
                                OR DATE LIKE '%2019%' \
                                ORDER BY DATE ASC \
                                ")
        monthly_Stock = pd.DataFrame(q1, columns=df.columns)
        ''' Method 2 [OPTIONAL]:
                #filter = df[(df.DATE >= '2020-01-31')]
                #filter = filter.sort_values(by=['DATE']) '''

        # Converting Date to datetime datatype and setting as index
        monthly_Stock.DATE = pd.to_datetime(monthly_Stock.DATE)
        monthly_Stock = monthly_Stock.set_index('DATE')

        # Data Visual - Candlestick chart with custom parameters
        mc = mpf.make_marketcolors(up='purple',
                                   down='Black',
                                   edge='black',
                                   wick={
                                       'up': 'blue',
                                       'down': 'red'
                                   },
                                   volume='green')

        s = mpf.make_mpf_style(marketcolors=mc,
                               gridstyle='--',
                               gridaxis='both',
                               mavcolors=['red'])

        mpf.plot(monthly_Stock,
                 type='candle',
                 mav=(2),
                 figratio=(18, 10),
                 figscale=1.0,
                 volume=True,
                 tight_layout=True,
                 title='[' + stock + ']' + 'Monthly Time Series',
                 style=s,
                 xrotation=20,
                 savefig='YOUR PATH/Data_Visuals/candles/' + stock + '.png')
Exemplo n.º 28
0
    def __init__(self, parent=None, width=5, height=5, dpi=100):
        idf = pd.read_csv('datas/SPY_20110701_20120630_Bollinger.csv',
                          index_col=0,
                          parse_dates=True)
        idf.shape
        idf.head(3)
        idf.tail(3)
        self.df = idf.loc['2011-07-01':'2011-12-30', :]
        self.df = self.df.iloc[0:30]
        self.exp12 = self.df['Close'].ewm(span=12, adjust=False).mean()
        self.exp26 = self.df['Close'].ewm(span=26, adjust=False).mean()
        self.macd = self.exp12 - self.exp26
        self.signal = self.macd.ewm(span=9, adjust=False).mean()
        self.histogram = self.macd - self.signal
        self.apds = [
            mpf.make_addplot(self.exp12, color='lime'),
            mpf.make_addplot(self.exp26, color='c'),
            mpf.make_addplot(self.histogram,
                             type='bar',
                             width=0.7,
                             panel=1,
                             color='dimgray',
                             alpha=1,
                             secondary_y=False),
            mpf.make_addplot(self.macd,
                             panel=1,
                             color='fuchsia',
                             secondary_y=True),
            mpf.make_addplot(self.signal, panel=1, color='b',
                             secondary_y=True),
        ]

        s = mpf.make_mpf_style(base_mpf_style='starsandstripes',
                               rc={'figure.facecolor': 'lightgray'})
        self.fig, self.axes = mpf.plot(self.df,
                                       type='candle',
                                       addplot=self.apds,
                                       figscale=1.5,
                                       figratio=(7, 5),
                                       title='\n\nMACD',
                                       style=s,
                                       volume=True,
                                       volume_panel=2,
                                       panel_ratios=(6, 3, 2),
                                       returnfig=True)
        FigureCanvas.__init__(self, self.fig)
        self.setParent(parent)

        self.ax_main = self.axes[0]
        self.ax_emav = self.ax_main
        self.ax_hisg = self.axes[2]
        self.ax_macd = self.axes[3]
        self.ax_sign = self.ax_macd
        self.ax_volu = self.axes[4]
        self.df = idf.loc['2011-07-01':'2011-12-30', :]
        self.ani = animation.FuncAnimation(self.fig,
                                           self.animate,
                                           interval=250)
Exemplo n.º 29
0
def view_vwap(
    s_ticker: str,
    df_stock: pd.DataFrame,
    offset: int = 0,
    s_interval: str = "",
    export: str = "",
):
    """Plots EMA technical indicator

    Parameters
    ----------
    s_ticker : str
        Ticker
    df_stock : pd.DataFrame
        Dataframe of prices
    offset : int
        Offset variable
    s_interval : str
        Interval of data
    export : str
        Format to export data
    """

    df_stock.index = df_stock.index.tz_localize(None)
    df_stock["Day"] = [idx.date() for idx in df_stock.index]

    day_df = df_stock[df_stock.Day == df_stock.Day[-1]]

    df_vwap = overlap_model.vwap(day_df, offset)
    mc = mpf.make_marketcolors(
        up="green", down="red", edge="black", wick="black", volume="in", ohlc="i"
    )

    s = mpf.make_mpf_style(marketcolors=mc, gridstyle=":", y_on_right=True)
    addplot_result = mpf.make_addplot(df_vwap, color="k")

    mpf.plot(
        day_df,
        style=s,
        type="candle",
        addplot=addplot_result,
        volume=True,
        title=f"\n{s_ticker} {s_interval} VWAP",
    )

    if gtff.USE_ION:
        plt.ion()

    plt.show()
    console.print("")

    export_data(
        export,
        os.path.dirname(os.path.abspath(__file__)).replace("common", "stocks"),
        "VWAP",
        df_vwap,
    )
Exemplo n.º 30
0
def plot_image(df_):
    my_color = mpf.make_marketcolors(up="red", down="green", edge="inherit", volume="inherit")
    my_style = mpf.make_mpf_style(marketcolors=my_color)

    add_plot = [mpf.make_addplot(df_[['ma_short', 'ma_long']]),
                mpf.make_addplot(df_['signal_long'], scatter=True, marker="^", color="r"),
                mpf.make_addplot(df_['signal_short'], scatter=True, marker="v", color="g")]
    mpf.plot(df_, type="line", ylabel="price(usdt)", style=my_style, volume=True, ylabel_lower="vol",
             addplot=add_plot)