Advertisement
Guest User

Untitled

a guest
Mar 26th, 2019
125
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 5.03 KB | None | 0 0
  1. import pandas as pd
  2. from bokeh.io import output_file, show
  3. from bokeh.plotting import figure
  4. from bokeh.models import CustomJS, ColumnDataSource, HoverTool, NumeralTickFormatter
  5. from sqlalchemy import create_engine
  6.  
  7.  
  8. def candlestick_plot(df, name):
  9.     # Select the datetime format for the x axis depending on the timeframe
  10.     xaxis_dt_format = '%d %b %Y'
  11.     if df['candletime'][0].hour > 0:
  12.         xaxis_dt_format = '%d %b %Y, %H:%M:%S'
  13.  
  14.     fig = figure(sizing_mode='stretch_both',
  15.                  tools="xpan,xwheel_zoom,reset,save",
  16.                  active_drag='xpan',
  17.                  active_scroll='xwheel_zoom',
  18.                  x_axis_type='linear',
  19.                  # x_range=Range1d(df.index[0], df.index[-1], bounds="auto"),
  20.                  title=name
  21.                  )
  22.     fig.yaxis[0].formatter = NumeralTickFormatter(format="$5.3f")
  23.     fig.background_fill_color = 'darkgrey'
  24.     fig.xgrid.grid_line_color = 'darkgrey'
  25.     fig.ygrid.grid_line_color = 'darkgrey'
  26.     fig.border_fill_color = "whitesmoke"
  27.     inc = df.close > df.open
  28.     dec = ~inc
  29.  
  30.     # Colour scheme for increasing and descending candles
  31.     INCREASING_COLOR = 'green'
  32.     DECREASING_COLOR = 'red'
  33.  
  34.     width = 0.5
  35.     inc_source = ColumnDataSource(data=dict(
  36.         x1=df.index[inc],
  37.         top1=df.open[inc],
  38.         bottom1=df.close[inc],
  39.         high1=df.high[inc],
  40.         low1=df.low[inc],
  41.         Date1=df.candletime[inc]
  42.     ))
  43.  
  44.     dec_source = ColumnDataSource(data=dict(
  45.         x2=df.index[dec],
  46.         top2=df.open[dec],
  47.         bottom2=df.close[dec],
  48.         high2=df.high[dec],
  49.         low2=df.low[dec],
  50.         Date2=df.candletime[dec]
  51.     ))
  52.     # Plot candles
  53.     # High and low
  54.     fig.segment(x0='x1', y0='high1', x1='x1', y1='low1', source=inc_source, color='black')
  55.     fig.segment(x0='x2', y0='high2', x1='x2', y1='low2', source=dec_source, color='black')
  56.  
  57.     # Open and close
  58.     r1 = fig.vbar(x='x1', width=width, top='top1', bottom='bottom1', source=inc_source,
  59.                     fill_color=INCREASING_COLOR, line_color="black")
  60.     r2 = fig.vbar(x='x2', width=width, top='top2', bottom='bottom2', source=dec_source,
  61.                     fill_color=DECREASING_COLOR, line_color="black")
  62.  
  63.     # Add on extra lines (e.g. moving averages) here
  64.     # fig.line(df.index, <your data>)
  65.  
  66.     # Add on a vertical line to indicate a trading signal here
  67.     # vline = Span(location=df.index[-<your index>, dimension='height',
  68.     #              line_color="green", line_width=2)
  69.     # fig.renderers.extend([vline])
  70.  
  71.     # Add date labels to x axis
  72.     fig.xaxis.major_label_overrides = {
  73.         i: date.strftime(xaxis_dt_format) for i, date in enumerate(pd.to_datetime(df["candletime"]))
  74.     }
  75.  
  76.     # Set up the hover tooltip to display some useful data
  77.     fig.add_tools(HoverTool(
  78.         renderers=[r1],
  79.         tooltips=[
  80.             ("Open", "$@top1"),
  81.             ("High", "$@high1"),
  82.             ("Low", "$@low1"),
  83.             ("Close", "$@bottom1"),
  84.             ("Date", "@Date1{" + xaxis_dt_format + "}"),
  85.         ],
  86.         formatters={
  87.             'Date1': 'datetime',
  88.         }))
  89.  
  90.     fig.add_tools(HoverTool(
  91.         renderers=[r2],
  92.         tooltips=[
  93.             ("Open", "$@top2"),
  94.             ("High", "$@high2"),
  95.             ("Low", "$@low2"),
  96.             ("Close", "$@bottom2"),
  97.             ("Date", "@Date2{" + xaxis_dt_format + "}")
  98.         ],
  99.         formatters={
  100.             'Date2': 'datetime'
  101.         }))
  102.  
  103.     # JavaScript callback function to automatically zoom the Y axis to
  104.     # view the data properly
  105.     source = ColumnDataSource({'Index': df.index, 'High': df.high, 'Low': df.low})
  106.     callback = CustomJS(args={'y_range': fig.y_range, 'source': source}, code='''
  107.        clearTimeout(window._autoscale_timeout);
  108.        var Index = source.data.Index,
  109.            Low = source.data.Low,
  110.            High = source.data.High,
  111.            start = cb_obj.start,
  112.            end = cb_obj.end,
  113.            min = Infinity,
  114.            max = -Infinity;
  115.        for (var i=0; i < Index.length; ++i) {
  116.            if (start <= Index[i] && Index[i] <= end) {
  117.                max = Math.max(High[i], max);
  118.                min = Math.min(Low[i], min);
  119.            }
  120.        }
  121.        var pad = (max - min) * .05;
  122.        window._autoscale_timeout = setTimeout(function() {
  123.            y_range.start = min - pad;
  124.            y_range.end = max + pad;
  125.        });
  126.    ''')
  127.  
  128.     # Finalise the figure
  129.     fig.x_range.callback = callback
  130.     show(fig)
  131.  
  132.  
  133. # Main function
  134. if __name__ == '__main__':
  135.     engine = create_engine('postgresql://<NAME>:<PASSWORD>@192.999.9.999:32790/fx_data')
  136.     with engine.connect() as conn, conn.begin():
  137.         data = pd.read_sql_table('audusd_tf_60', conn)
  138.         df = pd.DataFrame(data)
  139.         output_file("candlestick.html")
  140.     # Convert the dates column to datetime objects
  141.         df["candletime"] = pd.to_datetime(df["candletime"], format='%Y-%m-%d %H:%M:%S')  # Adjust this
  142.  
  143.         output_file("plot.html")
  144.         candlestick_plot(df, "AUDUSD")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement