Пример #1
0
def _plot_kline(data, remote=True):
    fig = create_candlestick(data.open, data.high, data.low, data.close, dates=data.index)
    if remote:
        url = plotly.plotly.plot(fig, filename='candle.html')
        print('url: ', url)
    else:
        plotly.offline.plot(fig, filename='candle.html', validate=False)
Пример #2
0
def main():
    args = get_args()

    data = read_data(args)
    data = data[:].iloc[0:-1]
    x = np.arange(len(data.index))
    y = data['close'].values

    trend_reversal_analysis(15,
                            data,
                            direction=-1,
                            change_ratio_margins=np.concatenate([
                                np.linspace(0.0005, 0.005, 10),
                                np.linspace(0.006, 0.035, 9)
                            ]),
                            max_reversal_margins=np.linspace(0.1, 1., 10),
                            show_as_percentage=True)

    # validate_ohlc(data['open'], data['high'], data['low'], data['close'], data)
    if False:
        fig, ax = plt.subplots()
        candlestick2_ohlc(ax,
                          data['open'],
                          data['high'],
                          data['low'],
                          data['close'],
                          width=0.6)
        show()

    validate_ohlc(data['open'], data['high'], data['low'], data['close'], data)
    fig = FF.create_candlestick(data['open'],
                                data['high'],
                                data['high'] * 0.,
                                data['close'],
                                dates=data.index)
Пример #3
0
def totalTogether(stockSymbol,Webster,currentInfo): #plots all the graphs together
	fig=go.create_candlestick(Webster.Open,Webster.High,Webster.Low,Webster.Close,dates=Webster.index)
	figure=obj.Trace(y=Webster.High,x=Webster.index,line=dict(color=('rgb(0,50,100)')))
	currentFigure=obj.Trace(y=currentInfo[0]['LastTradePrice'],x=currentInfo[0]['LastTradeDateTime'],line=dict(color=('rgb(0,0,0)')))
	fig['data'].extend([figure])
	fig['data'].extend([currentFigure])
	py.plot(fig, filename=stockSymbol+'_Line',validate=False)
Пример #4
0
def update_graph(n_clicks, stock, start, end):
    stock_df = web.DataReader(stock, 'iex', start, end).reset_index()
    fig = ff.create_candlestick(open=stock_df['open'],
                                high=stock_df['high'],
                                low=stock_df['low'],
                                close=stock_df['close'],
                                dates=stock_df['date'])
    fig['layout']['title'] = 'Candlestick plot for {} stocks'.format(stock)
    return fig
def update_graph(n_clicks, stock, start, end):
    stock_df = web.DataReader(stock, 'iex', start, end)
    stock_df.reset_index(inplace=True)
    fig = ff.create_candlestick(open=stock_df['open'],
                                high=stock_df['high'],
                                low=stock_df['low'],
                                close=stock_df['close'],
                                dates=stock_df['date'])
    fig['layout']['title'] = 'Candlestick plot for {} - Just for PyData!' \
        .format(stock_lookup[stock])
    return fig
def update_graph(n_clicks, stock, start, end):
    stock_df_all = web.DataReader(stock, 'robinhood').reset_index()
    stock_df = stock_df_all.loc[(stock_df_all['begins_at'] >= start) & (
        stock_df_all['begins_at'] <= end)].reset_index()
    fig = ff.create_candlestick(open=stock_df['open_price'],
                                high=stock_df['high_price'],
                                low=stock_df['low_price'],
                                close=stock_df['close_price'],
                                dates=stock_df['begins_at'])
    fig['layout']['title'] = 'Candlestick plot for {} stocks'.format(stock)
    return fig
Пример #7
0
def printCharts(df):
    delta = datetime.timedelta(days=190)
    end = datetime.date.today()
    start = end - delta
    e = end.strftime("%Y %m %d")
    s = start.strftime("%Y %m %d")
    df = df[s:e]
    
    fig = FF.create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index)

    ts_line = Scatter(
        x=df.index, 
        y=df.tenkan_sen, 
        name= 'Tenkan Sen', 
        line=Line(color='Red')
    )
    fig['data'].extend([ts_line])
    
    ks_line = Scatter(
        x=df.index, 
        y=df.kijun_sen,
        name= 'Kijun Sen', 
        line=Line(color='Blue')
    )    
    fig['data'].extend([ks_line])
    
    cs_line = Scatter(
        x=df.index, 
        y=df.chikou_span,
        name= 'Chikou Span', 
        line=Line(color='Black')
    )    
    fig['data'].extend([cs_line])
    
    ssA_line = Scatter(
        x=df.index, 
        y=df.senkou_span_a,
        fill='none',
        name= 'senkou_span_a', 
        line=Line(color='Grean')
    )    
    fig['data'].extend([ssA_line])

    ssB_line = Scatter(
        x=df.index, 
        y=df.senkou_span_b,
        name= 'senkou_span_b', 
        fill='tonexty',
        line=Line(color='Orange')
    )    
    fig['data'].extend([ssB_line])
        
    py.plot(fig, filename='KGHM', validate=False)
Пример #8
0
def visualise(data, periods, count):

    import plotly.offline as py
    import plotly.figure_factory as ff

    py.init_notebook_mode()  # run at the start of every ipython notebook

    csticks = data.values[0:count:, :periods * 4].ravel().reshape(-1, 4)

    fig = ff.create_candlestick(csticks[:, 0], csticks[:, 1], csticks[:, 2], csticks[:, 3])

    py.iplot(fig, filename='jupyter/simple-candlestick', validate=True)
def update_graph(n_clicks, stock, start, end):

    stock_df = all_stocks.loc[(all_stocks['symbol'] == stock)
                              & (all_stocks['begins_at'] >= start) &
                              (all_stocks['begins_at'] <= end)].reset_index()
    fig = ff.create_candlestick(open=stock_df['open_price'],
                                high=stock_df['high_price'],
                                low=stock_df['low_price'],
                                close=stock_df['close_price'],
                                dates=stock_df['begins_at'])
    fig['layout']['title'] = 'Candlestick plot for {} stocks'.format(stock)
    return fig
Пример #10
0
def drDF_cdl(df,
             m_title='分时数据K线图',
             ftg='tmp/tmp_plotly.html',
             m_tkAng=-20,
             m_dtick=5,
             m_y2k=3):
    fig = pyff.create_candlestick(df.open,
                                  df.high,
                                  df.low,
                                  df.close,
                                  dates=df.index)
    fig['layout'].update(
        title=m_title,
        xaxis=pygo.XAxis(
            autorange=True,
            gridcolor='rgb(180, 180, 180)',
            mirror='all',
            showgrid=True,
            showline=True,
            ticks='outside',
            tickangle=m_tkAng,
            dtick=m_dtick,
            type='category',
            categoryarray=df.index,
        ),
        yaxis=pygo.YAxis(
            autorange=True,
            gridcolor='rgb(180, 180, 180)',
        ),
        yaxis2=pygo.YAxis(
            side='right',
            overlaying='y',
            range=[0, max(df['volume']) * m_y2k],
        ),
    )  # fig.update
    r_vol = pygo.Bar(
        x=df.index,  #df['xtim'],
        y=df['volume'],
        name='volume',
        yaxis='y2',
        opacity=0.6,
        marker=dict(
            color='rgb(158,202,225)',
            line=dict(
                color='rgb(8,48,107)',
                width=1.5,
            ),
        ),
    )  #r_vol
    #
    fig['data'].extend([r_vol])
    #
    pyplt(fig, filename=ftg, show_link=False)
Пример #11
0
def plot_pos(df, pos_df):
    en_l = list(map(str, pos_df['entry_date'].to_list()))
    ex_l = list(map(str, pos_df['exit_date'].to_list()))
    long_i = []
    long_l = []
    short_i = []
    short_l = []
    for i in range(len(df)):
        time = str(df.iat[i, 0])
        # get entry marker
        if time in en_l:
            j = en_l.index(time)
            if pos_df.iat[j, 1] == 'long':
                long_l.extend([pos_df.iat[j, 3]])
                long_i.extend([i])
            else:
                short_l.extend([pos_df.iat[j, 3]])
                short_i.extend([i])
        # get exit marker
        if time in ex_l:
            j = ex_l.index(time)
            if pos_df.iat[j, 1] == 'long':
                short_l.extend([pos_df.iat[j, 5]])
                short_i.extend([i])
            else:
                long_l.extend([pos_df.iat[j, 5]])
                long_i.extend([i])
    fig = create_candlestick(open=df['Open'],
                             high=df['High'],
                             low=df['Low'],
                             close=df['Close'])
    fig.add_scatter(x=long_i,
                    y=long_l,
                    name='long',
                    mode='markers',
                    marker={
                        "size": 10,
                        "symbol": 'triangle-up',
                        'color': '#00e1ff'
                    })
    fig.add_scatter(x=short_i,
                    y=short_l,
                    name='short',
                    mode='markers',
                    marker={
                        "size": 10,
                        "symbol": 'triangle-down',
                        'color': '#ffee00'
                    })
    fig.show()
Пример #12
0
def candlestick_plot():
    ticker = request.args.get('stock')
    stock = retriveStockData(ticker)
    df = stock.info
    fig = FF.create_candlestick(df.open,
                                df.high,
                                df.low,
                                df.close,
                                dates=df.daytime)
    # Create Line of open values
    add_line = Scatter(x=df.daytime,
                       y=df.open,
                       name='Open Vals',
                       line=Line(color='black'))
    fig['data'].extend([add_line])
    plotly.offline.plot(fig,
                        filename='candlestick.html',
                        validate=False,
                        auto_open=False)
    file = open('candlestick.html', 'r')
    return file.read()
Пример #13
0
def plot_plotly(data):
    init_notebook_mode(connected=False)

    fig = ff.create_candlestick(dates=data.index,
                                open=data.open,
                                high=data.high,
                                low=data.low,
                                close=data.close)
    fig['layout'].update({
        'title': 'FX 1min',
        'yaxis': {'title': 'AUDCAD'},
        'shapes': [{
            'x0': '20114-12-28', 'x1': '2014-12-30',
            'y0': 0, 'y1': 1, 'xref': 'x', 'yref': 'paper',
            'line': {'color': 'rgb(30,30,30)', 'width': 1}
        }],
        'annotations': [{
            'x': '2014-12-29', 'y': 0.05, 'xref': 'x', 'yref': 'paper',
            'showarrow': False, 'xanchor': 'left',
            'text': 'Official start of the recession'
        }]
    })
    plot(fig, filename='simple_candlestick.html', validate=True)
def get_candle(df,up_color=None,down_color=None,theme=None,layout=None,**kwargs):
	layout=getLayout(theme=theme) if not layout else layout
	ohlc=['open','high','low','close']
	if not theme:
		theme = auth.get_config_file()['theme']
	c_dir=ta._ohlc_dict(df)
	args=[df[c_dir[_]] for _ in ohlc]
	args.append(df.index)
	fig=ff.create_candlestick(*args,**kwargs)
	candle={}
	candle['data']=fig['data']
	candle['layout']=layout
	data=candle['data']
	def update_color(n,color):
		data[n]['fillcolor']=normalize(color)
		data[n]['line'].update(color=normalize(color))
	if up_color:
		update_color(0,up_color)
	if down_color:
		update_color(1,down_color)
	candle['layout']['hovermode']='closest'
	candle['layout']=merge_dict(layout,candle['layout'])
	return candle
 def plot_all(self):
     #still has problem
     #init_notebook_mode(connected=True) # Jupyter notebook用設定
     if not self.ohlc_pd.empty:
         fig_ff = FF.create_candlestick(self.ohlc_pd.open,
                                        self.ohlc_pd.high,
                                        self.ohlc_pd.low,
                                        self.ohlc_pd.close,
                                        dates=self.ohlc_pd.index)
         fig = go.Candlestick(x=self.ohlc_pd.index,
                              open=self.ohlc_pd.open,
                              high=self.ohlc_pd.high,
                              low=self.ohlc_pd.low,
                              close=self.ohlc_pd.close)
         figure_list = self.technical_analysis()
         #figure_list.append(fig.data)
         #if len(figure_list)>0:
         #    for item in figure_list:
         #       fig["data"].append(item.data)
         #plotly.offline.plot([fig], filename='candlestick.html')
         plotly.offline.plot(figure_list,
                             filename='technical_analysis.html')
         plotly.offline.plot(fig_ff, filename='candlestick_ff.html')
Пример #16
0
def plot_plotly(data):
    init_notebook_mode(connected=False)

    fig = ff.create_candlestick(dates=data.index,
                                open=data.open,
                                high=data.high,
                                low=data.low,
                                close=data.close)
    fig['layout'].update({
        'title':
        'FX 1min',
        'yaxis': {
            'title': 'AUDCAD'
        },
        'shapes': [{
            'x0': '20114-12-28',
            'x1': '2014-12-30',
            'y0': 0,
            'y1': 1,
            'xref': 'x',
            'yref': 'paper',
            'line': {
                'color': 'rgb(30,30,30)',
                'width': 1
            }
        }],
        'annotations': [{
            'x': '2014-12-29',
            'y': 0.05,
            'xref': 'x',
            'yref': 'paper',
            'showarrow': False,
            'xanchor': 'left',
            'text': 'Official start of the recession'
        }]
    })
    plot(fig, filename='simple_candlestick.html', validate=True)
Пример #17
0
 def create_candlestick(*args, **kwargs):
     FigureFactory._deprecated('create_candlestick')
     from plotly.figure_factory import create_candlestick
     return create_candlestick(*args, **kwargs)
Пример #18
0
# ????

# import numpy as np
# import pandas as pd
#
# idx = pd.date_range('2015/01/01', '2015/12/31 23:59', freq='T')
# dn = np.random.randint(2, size=len(idx))*2-1
# rnd_walk = np.cumprod(np.exp(dn*0.0002))*100
# df = pd.Series(rnd_walk, index=idx).resample('B').ohlc()
#
# from plotly.offline import init_notebook_mode, iplot
# from plotly.tools import FigureFactory as FF
#
# init_notebook_mode(connected=True) # Jupyter notebook用設定
#
# fig = FF.create_candlestick(df.open, df.high, df.low, df.close, dates=df.index)
#
# iplot(fig)

import plotly.plotly as py
import plotly.figure_factory as FF
from datetime import datetime

import pandas_datareader.data as web

df = web.DataReader("aapl", 'yahoo', datetime(2007, 10, 1), datetime(2009, 4, 1))
fig = FF.create_candlestick(df.Open, df.High, df.Low, df.Close, dates=df.index)
py.iplot(fig)
Пример #19
0
    def _ohlc(self, bot, update, data, args):
        from_sy = data.pair.split("-")[0]
        to_sy = self.symbol = data.pair.split("-")[1]

        if len(args) >= 1 and args[0].isnumeric() and args[0] != 0:
            self.TIME_FRAME = args[0]

        ohlcv = CryptoCompare().historical_ohlcv_hourly(to_sy, from_sy, self.TIME_FRAME)["Data"]

        if not ohlcv:
            update.message.reply_text(
                text=f"No OHLC data available for {to_sy} {emo.OH_NO}",
                parse_mode=ParseMode.MARKDOWN)
            return

        o = [value["open"] for value in ohlcv]
        h = [value["high"] for value in ohlcv]
        l = [value["low"] for value in ohlcv]
        c = [value["close"] for value in ohlcv]
        t = [value["time"] for value in ohlcv]

        fig = fif.create_candlestick(o, h, l, c, pd.to_datetime(t, unit='s'))
        fig['layout']['yaxis'].update(tickformat="0.8f", ticksuffix="  ")
        fig['layout'].update(title=f"{from_sy} - {to_sy}")
        fig['layout'].update(
            shapes=[{
                "type": "line",
                "xref": "paper",
                "yref": "y",
                "x0": 0,
                "x1": 1,
                "y0": c[len(c) - 1],
                "y1": c[len(c) - 1],
                "line": {
                    "color": "rgb(50, 171, 96)",
                    "width": 1,
                    "dash": "dot"
                }
            }])
        fig['layout'].update(
            autosize=False,
            width=800,
            height=600,
            margin=go.layout.Margin(
                l=125,
                r=50,
                b=70,
                t=100,
                pad=4
            ))
        fig['layout'].update(
            images=[dict(
                source=f"{con.LOGO_URL_PARTIAL}{data.cmc_coin_id}.png",
                opacity=0.8,
                xref="paper", yref="paper",
                x=1.05, y=1,
                sizex=0.2, sizey=0.2,
                xanchor="right", yanchor="bottom"
            )])

        update.message.reply_photo(
            photo=io.BufferedReader(BytesIO(pio.to_image(fig, format='webp'))),
            parse_mode=ParseMode.MARKDOWN)
Пример #20
0
 def create_candlestick(*args, **kwargs):
     FigureFactory._deprecated('create_candlestick')
     from plotly.figure_factory import create_candlestick
     return create_candlestick(*args, **kwargs)
Пример #21
0
    def plot(self, bar='candle', start_view=None, end_view=None, periods_view=None, shift=None,
             start_plot=None, end_plot=None, periods_plot=None,
             showgrid=True, validate=False, **kwargs):
        """Retrun plotly candle chart graph

        Usage: `fx.plot()`

        * Args:
            * bar: 'candle', 'c' -> candle_plot / 'heikin', 'h' -> heikin_ashi plot
            * start, end: 最初と最後のdatetime, 'first'でindexの最初、'last'でindexの最後
            * periods: 足の本数
            > **start, end, periods合わせて2つの引数が必要**
            * shift: shiftの本数の足だけ右側に空白
        * Return: グラフデータとレイアウト(plotly.graph_objs.graph_objs.Figure)
        """
        # ---------Set "plot_dataframe"----------
        # Default Args
        if com._count_not_none(start_plot,
                               end_plot, periods_plot) == 0:
            end_plot = 'last'
            periods_plot = 300
        try:
            # first/last
            start_plot = self.stock_dataframe.index[0] if start_plot == 'first' else start_plot
            end_plot = self.stock_dataframe.index[-1] if end_plot == 'last' else end_plot
        except AttributeError:
            raise AttributeError('{} Use `fx.resample(<TimeFrame>)` at first'
                                 .format(type(self.stock_dataframe)))
        # Set "plot_dataframe"
        start_plot, end_plot = set_span(start_plot, end_plot, periods_plot, self.freq)
        if bar in ('candle', 'c'):
            plot_dataframe = self.stock_dataframe.loc[start_plot:end_plot]
            self._fig = FF.create_candlestick(plot_dataframe.open,
                                              plot_dataframe.high,
                                              plot_dataframe.low,
                                              plot_dataframe.close,
                                              dates=plot_dataframe.index)
        elif bar in ('heikin', 'h'):
            self.stock_dataframe.heikin_ashi()
            plot_dataframe = self.stock_dataframe.loc[start_plot:end_plot]
            self._fig = FF.create_candlestick(plot_dataframe.hopen,
                                              plot_dataframe.hhigh,
                                              plot_dataframe.hlow,
                                              plot_dataframe.hclose,
                                              dates=plot_dataframe.index)
        else:
            raise KeyError('Use bar = "[c]andle" or "[h]eikin"')
        # ---------Append indicators----------
        for indicator in self._indicators.keys():
            self._append_graph(indicator, start_plot, end_plot)  # Re-append indicator in graph
        # ---------Set "view"----------
        # Default Args
        if com._count_not_none(start_view,
                               end_view, periods_view) == 0:
            end_view = 'last'
            periods_view = 50
        # first/last
        start_view = plot_dataframe.index[0] if start_view == 'first' else start_view
        end_view = plot_dataframe.index[-1] if end_view == 'last' else end_view
        # Set "view"
        start_view, end_view = set_span(start_view, end_view, periods_view, self.freq)
        end_view = set_span(start=end_view, periods=shift,
                            freq=self.freq)[-1] if shift else end_view
        view = list(to_unix_time(start_view, end_view))
        # ---------Plot graph----------
        self._fig['layout'].update(xaxis={'showgrid': showgrid, 'range': view},
                                   yaxis={"autorange": True})
        return self._fig
Пример #22
0
import plotly as py  # 导入plotly库并命名为py
import plotly.figure_factory as ff  # 导入plotly工具箱库中的图像工厂方法并命名为FF

# -------------pre def
pyplt = py.offline.plot
import pandas as pd

df = pd.read_csv(r'dat/appl.csv', index_col=['date'], parse_dates=['date'])

fig = ff.create_candlestick(df.open, df.high, df.low, df.close, dates=df.index)

pyplt(fig, filename=r'tmp/first_candlestick_old.html')
Пример #23
0
    def get_action(self, bot, update, args):
        keywords = utl.get_kw(args)
        arg_list = utl.del_kw(args)

        if not arg_list:
            if not keywords.get(Keyword.INLINE):
                update.message.reply_text(text=f"Usage:\n{self.get_usage()}",
                                          parse_mode=ParseMode.MARKDOWN)
            return

        time_frame = 72
        resolution = "HOUR"
        base_coin = "BTC"

        # Coin or pair
        if "-" in arg_list[0]:
            pair = arg_list[0].split("-", 1)
            base_coin = pair[1].upper()
            coin = pair[0].upper()
        else:
            coin = arg_list[0].upper()

        if coin == "BTC" and base_coin == "BTC":
            base_coin = "USD"

        if coin == base_coin:
            update.message.reply_text(
                text=f"{emo.ERROR} Can't compare *{coin}* to itself",
                parse_mode=ParseMode.MARKDOWN)
            return

        if RateLimit.limit_reached(update):
            return

        cmc_thread = threading.Thread(target=self._get_cmc_coin_id,
                                      args=[coin])
        cmc_thread.start()

        # Time frame
        if len(arg_list) > 1:
            if arg_list[1].lower().endswith(
                    "m") and arg_list[1][:-1].isnumeric():
                resolution = "MINUTE"
                time_frame = arg_list[1][:-1]
            elif arg_list[1].lower().endswith(
                    "h") and arg_list[1][:-1].isnumeric():
                resolution = "HOUR"
                time_frame = arg_list[1][:-1]
            elif arg_list[1].lower().endswith(
                    "d") and arg_list[1][:-1].isnumeric():
                resolution = "DAY"
                time_frame = arg_list[1][:-1]
            else:
                update.message.reply_text(
                    text=f"{emo.ERROR} Argument *{arg_list[1]}* is invalid",
                    parse_mode=ParseMode.MARKDOWN)
                return

        try:
            if resolution == "MINUTE":
                ohlcv = CryptoCompare().get_historical_ohlcv_minute(
                    coin, base_coin, time_frame)
            elif resolution == "HOUR":
                ohlcv = CryptoCompare().get_historical_ohlcv_hourly(
                    coin, base_coin, time_frame)
            elif resolution == "DAY":
                ohlcv = CryptoCompare().get_historical_ohlcv_daily(
                    coin, base_coin, time_frame)
            else:
                ohlcv = CryptoCompare().get_historical_ohlcv_hourly(
                    coin, base_coin, time_frame)
        except Exception as e:
            return self.handle_error(e, update)

        if ohlcv["Response"] == "Error":
            if ohlcv["Message"] == "limit is larger than max value.":
                update.message.reply_text(
                    text=f"{emo.ERROR} Time frame can't be larger "
                    f"then *{con.CG_DATA_LIMIT}* data points",
                    parse_mode=ParseMode.MARKDOWN)
                return
            elif ohlcv["Message"].startswith(
                    "There is no data for the symbol"):
                ohlcv = None
            else:
                update.message.reply_text(
                    text=f"{emo.ERROR} CoinGecko ERROR: {ohlcv['Message']}",
                    parse_mode=ParseMode.MARKDOWN)
                return

        ohlcv = ohlcv["Data"]

        if ohlcv:
            try:
                o = [value["open"] for value in ohlcv]
                h = [value["high"] for value in ohlcv]
                l = [value["low"] for value in ohlcv]
                c = [value["close"] for value in ohlcv]
                t = [value["time"] for value in ohlcv]
            except:
                return self.handle_error(f"No OHLC data for {coin}", update)

        if not ohlcv or utl.all_same(o, h, l, c):
            if base_coin != "BTC" and base_coin != "USD":
                update.message.reply_text(
                    text=f"{emo.ERROR} Base currency for "
                    f"*{coin}* can only be *BTC* or *USD*",
                    parse_mode=ParseMode.MARKDOWN)
                return

            # Time frame
            if len(arg_list) > 1:
                if resolution != "DAY":
                    update.message.reply_text(
                        text=f"{emo.ERROR} Timeframe for *{coin}* "
                        f"can only be specified in days",
                        parse_mode=ParseMode.MARKDOWN)
                    return
                else:
                    time_frame = int(time_frame)
            else:
                time_frame = 60  # Days

            try:
                cp_ohlc = APICache.get_cp_coin_list()
            except Exception as e:
                return self.handle_error(e, update)

            for c in cp_ohlc:
                if c["symbol"] == coin:
                    # Current datetime in seconds
                    t_now = time.time()
                    # Convert chart time span to seconds
                    time_frame = time_frame * 24 * 60 * 60
                    # Start datetime for chart in seconds
                    t_start = t_now - int(time_frame)

                    try:
                        ohlcv = CoinPaprika().get_historical_ohlc(
                            c["id"],
                            int(t_start),
                            end=int(t_now),
                            quote=base_coin.lower(),
                            limit=366)
                    except Exception as e:
                        return self.handle_error(e, update)

                    cp_api = True
                    break

            if not ohlcv:
                update.message.reply_text(
                    text=f"{emo.ERROR} No OHLC data for *{coin}* "
                    f"available or time frame too big",
                    parse_mode=ParseMode.MARKDOWN)
                return

            try:
                o = [value["open"] for value in ohlcv]
                h = [value["high"] for value in ohlcv]
                l = [value["low"] for value in ohlcv]
                c = [value["close"] for value in ohlcv]
                t = [
                    time.mktime(dau.parse(value["time_close"]).timetuple())
                    for value in ohlcv
                ]
            except:
                return self.handle_error(f"No OHLC data for {coin}", update)

        margin_l = 140
        tickformat = "0.8f"

        max_value = max(h)
        if max_value > 0.9:
            if max_value > 999:
                margin_l = 120
                tickformat = "0,.0f"
            else:
                margin_l = 125
                tickformat = "0.2f"

        try:
            fig = fif.create_candlestick(o, h, l, c, pd.to_datetime(t,
                                                                    unit='s'))
        except Exception as e:
            return self.handle_error(e, update)

        fig['layout']['yaxis'].update(tickformat=tickformat,
                                      tickprefix="   ",
                                      ticksuffix=f"  ")

        fig['layout'].update(title=dict(text=coin, font=dict(size=26)),
                             yaxis=dict(title=dict(text=base_coin,
                                                   font=dict(size=18)), ))

        fig['layout'].update(shapes=[{
            "type": "line",
            "xref": "paper",
            "yref": "y",
            "x0": 0,
            "x1": 1,
            "y0": c[len(c) - 1],
            "y1": c[len(c) - 1],
            "line": {
                "color": "rgb(50, 171, 96)",
                "width": 1,
                "dash": "dot"
            }
        }])

        fig['layout'].update(paper_bgcolor='rgb(233,233,233)',
                             plot_bgcolor='rgb(233,233,233)',
                             autosize=False,
                             width=800,
                             height=600,
                             margin=go.layout.Margin(l=margin_l,
                                                     r=50,
                                                     b=85,
                                                     t=100,
                                                     pad=4))

        cmc_thread.join()

        fig['layout'].update(images=[
            dict(source=f"{con.CMC_LOGO_URL_PARTIAL}{self.cmc_coin_id}.png",
                 opacity=0.8,
                 xref="paper",
                 yref="paper",
                 x=1.05,
                 y=1,
                 sizex=0.2,
                 sizey=0.2,
                 xanchor="right",
                 yanchor="bottom")
        ])

        self.send_photo(
            io.BufferedReader(BytesIO(pio.to_image(fig, format='jpeg'))),
            update, keywords)
Пример #24
0

# In[ ]:


fig = go.Figure()

for stock,symbol in zip(stocks,symbols):
    fig.add_trace(go.Scatter(x=stock.index, y=stock.Close, name=symbol))

fig.show()


# In[ ]:


df_aapl = pdr.get_data_yahoo(symbol, start="2020-01-01", end="2020-05-31")


# In[ ]:


ff.create_candlestick(dates=df_aapl.index, open=df_aapl.Open, high=df_aapl.High, low=df_aapl.Low, close=df_aapl.Close)


# In[ ]:




Пример #25
0
def makeCandleStickGraph(stockSymbol,Webster): # Makes a Candle Stick Graph
	fig=go.create_candlestick(Webster.Open,Webster.High,Webster.Low,Webster.Close,dates=Webster.index) # Past Data
	py.plot(fig,filename=stockSymbol+'_Candle',validate=False)
Пример #26
0
import plotly
from plotly.graph_objs import Scatter, Layout, Candlestick
from plotly import figure_factory as FigureFactory

# plotly.offline.plot({
#     "data": [Scatter(x=[0, 1, 2, 3], y=[3, 2, 1, 0]), Scatter(x=[1, 2, 3, 4], y=[1, 2, 3, 4])],
#     "layout": Layout(title="hello world")
# })

import pandas_datareader.data as web
from datetime import datetime

df = web.DataReader("aapl", 'google', datetime(2007, 10, 1),
                    datetime(2009, 4, 1))
print(df)
fig = FigureFactory.create_candlestick(df.Open,
                                       df.High,
                                       df.Low,
                                       df.Close,
                                       dates=df.index)

# plotly.offline.plot({
#     "data": [fig],
#     "layout": Layout(title="AAPL")
# })

plotly.offline.plot(fig)
Пример #27
0
def apply_trace(figure, before, date, code, row, col, rows, cols, layout,
                options):
    args = create_args(code)
    end = date
    start = utils.to_format(
        utils.to_datetime(end) - utils.relativeterm(int(before)))

    simulator_data = strategy.load_simulator_data(
        args.code,
        start,
        end,
        args,
        names=["average"] if options["use_multi"] else [])

    df = simulator_data.middle
    df = df[df["date"] >= start]
    df = df.reset_index()

    # 陽線-> candle.data[1], 陰線 -> candle.data[0]
    candle = FF.create_candlestick(df["open"],
                                   df["high"],
                                   df["low"],
                                   df["close"],
                                   dates=df["date"])
    stocks = list(candle.data)
    figure = add_stats(figure, row, col, stocks, df, [])  # ローソク足をグラフに適用

    # 日付リスト
    dates = list(map(lambda x: utils.to_datetime(x), df["date"].astype(str)))
    rangebreaks = [{
        "values":
        list(
            filter(lambda x: not utils.is_weekday(x),
                   utils.daterange(dates[0], dates[-1])))
    }]  # 休日を除外
    daterange = [dates[0], dates[-1]]

    layout_settings = create_layout_settings(options)

    if options["use_multi"]:
        setting = layout_settings[0]
        setting["line"] = [setting["line"][0]]  # candle with average
        layout_settings = [setting]

    # ===================================================================
    # layout_settingをもとに各グラフにデータを入れる
    domain_from = 0
    for setting in sorted(layout_settings, key=lambda x: x["to"]):
        i = row if options["use_multi"] else setting["id"]
        label_i = (
            (col - 1) +
            (row - 1) * cols) + 1 if options["use_multi"] else setting["id"]

        # multiの場合同じlegendがいくつも並ぶので最初のだけ有効に
        showlegend = layout["showlegend"] and row == 1 and col == 1 if options[
            "use_multi"] else layout["showlegend"]

        figure = apply_fig_setting(figure,
                                   i,
                                   col,
                                   df,
                                   setting["bar"],
                                   mode="bar",
                                   showlegend=showlegend)
        figure = apply_fig_setting(figure,
                                   i,
                                   col,
                                   df,
                                   setting["line"],
                                   mode="lines",
                                   showlegend=showlegend)
        figure = apply_fig_setting(figure,
                                   i,
                                   col,
                                   df,
                                   setting["marker"],
                                   mode="markers",
                                   showlegend=showlegend)

        xlabel = "xaxis%s" % label_i
        layout[xlabel] = {
            "range": daterange,
            "rangebreaks": rangebreaks,
            "scaleanchor": "x1"
        }

        if not options["use_multi"]:
            ylabel = "yaxis%s" % label_i
            layout[ylabel] = {"domain": [domain_from, setting["to"]]}
            layout[xlabel]["domain"] = [0.0, 1.0]

        domain_from = setting["to"]

    return figure, layout