예제 #1
0
    def get_color_code(self, code):
        # redefine color names
        dict = GraphicsConstants().plotfactory_color_overwrites

        if code in dict: return dict[code]

        return code
예제 #2
0
    def __init__(self):
        self.logger = LoggerManager().getLogger(__name__)
        self.DUMP_PATH = 'output_data/' + datetime.date.today().strftime("%Y%m%d") + ' '
        self.SCALE_FACTOR = 3
        self.DEFAULT_PLOT_ENGINE = GraphicsConstants().plotfactory_default_adapter

        return
예제 #3
0
 def create_brand_label(self, ax, anno, scale_factor):
     ax.annotate(
         anno,
         xy=(0, 1),
         xycoords='axes fraction',
         fontsize=10 * scale_factor,
         color='white',
         xytext=(0 * scale_factor, 15 * scale_factor),
         textcoords='offset points',
         va="center",
         ha="center",
         bbox=dict(boxstyle="round,pad=0.4",
                   facecolor=GraphicsConstants().plotfactory_brand_colour))
예제 #4
0
    def apply_style_sheet(self, gp):
        # set the matplotlib style sheet & defaults
        matplotlib.rcdefaults()

        # first search PyThalesians styles, then try matplotlib
        try:
            plt.style.use(
                GraphicsConstants().plotfactory_pythalesians_style_sheet[
                    gp.style_sheet])
        except:
            plt.style.use(gp.style_sheet)

        # adjust font size for scale factor
        matplotlib.rcParams.update(
            {'font.size': matplotlib.rcParams['font.size'] * gp.scale_factor})

        # do not use offsets/scientific notation
        matplotlib.rcParams.update({'axes.formatter.useoffset': False})
예제 #5
0
    def run_strategy_returns_stats(self, strategy):
        """
        run_strategy_returns_stats - Plots useful statistics for the trading strategy (using PyFolio)

        Parameters
        ----------
        strategy : StrategyTemplate
            defining trading strategy

        """

        pnl = strategy.get_strategy_pnl()
        tz = TimeSeriesTimezone()
        tsc = TimeSeriesCalcs()

        # PyFolio assumes UTC time based DataFrames (so force this localisation)
        try:
            pnl = tz.localise_index_as_UTC(pnl)
        except: pass

        # set the matplotlib style sheet & defaults
        # at present this only works in Matplotlib engine
        try:
            matplotlib.rcdefaults()
            plt.style.use(GraphicsConstants().plotfactory_pythalesians_style_sheet['pythalesians-pyfolio'])
        except: pass

        # TODO for intraday strategies, make daily

        # convert DataFrame (assumed to have only one column) to Series
        pnl = tsc.calculate_returns(pnl)
        pnl = pnl.dropna()
        pnl = pnl[pnl.columns[0]]
        fig = pf.create_returns_tear_sheet(pnl, return_fig=True)

        try:
            plt.savefig (strategy.DUMP_PATH + "stats.png")
        except: pass

        plt.show()
예제 #6
0
 def plotly_username(self, plotly_username):
     self.__plotly_username = plotly_username
     try:
         self.plotly_api_key = GraphicsConstants().plotly_creds[plotly_username]
     except: pass
예제 #7
0
    def __init__(self,
        # captions
        title = '',
	    x_title = '',
	    y_title = '',
        units = '',

        # type of plot (can be defined as list)
        chart_type = None,

        # colors
        color = [],
        color_2 = [],
        color_2_series = [],
        exclude_from_color = [],

        # display sizes
        scale_factor = GraphicsConstants().plotfactory_scale_factor,
        dpi = GraphicsConstants().plotfactory_dpi,
        width = GraphicsConstants().plotfactory_width,
        height = GraphicsConstants().plotfactory_height,
        resample = None,

        # lines and multiple y-axis
        y_axis_2_series = [],
        linewidth_2_series = [],
        linewidth = None,
        linewidth_2 = None,
    	marker_size = 1,
        line_of_best_fit = False,

        # labelling of sources
        brand_label = GraphicsConstants().plotfactory_brand_label,
        display_brand_label = GraphicsConstants().plotfactory_display_brand_label,
        source = GraphicsConstants().plotfactory_source,
        source_color = 'black',
        display_source_label =  GraphicsConstants().plotfactory_display_source_label,
        display_legend = True,

        # display output
        silent_display = False,
        file_output = None,
        date_formatter = None,

        # output
        html_file_output = None,
        display_mpld3 = False,

        # plotly only
        plotly_url = None,
        plotly_as_image = False,
        plotly_username = GraphicsConstants().plotly_default_username,
        plotly_api_key = None,
        plotly_world_readable = GraphicsConstants().plotly_world_readable,
        plotly_theme = None,
        plotly_plot_mode = GraphicsConstants().plotly_plot_mode,

        # bokeh
        bokeh_plot_mode = GraphicsConstants().bokeh_plot_mode,

        # plotly choropleth fields


        # matplotlib only
        style_sheet = GraphicsConstants().plotfactory_default_stylesheet,
        convert_matplotlib_to_plotly = False
                 ):

        self.logger = LoggerManager().getLogger(__name__)

        # captions
        self.title = title
        self.x_title = x_title
        self.y_title = y_title
        self.units = units
        
        # chart type
        self.chart_type = chart_type

        # colors
        self.color = color
        self.color_2 = color_2
        self.color_2_series = color_2_series
        self.exclude_from_color = exclude_from_color

        # display sizes
        self.scale_factor = scale_factor
        self.dpi = dpi
        self.width = width
        self.height = height
        self.resample = resample

        # lines and multiple y-axis
        self.y_axis_2_series = y_axis_2_series
        self.linewidth_2_series = linewidth_2_series
        self.linewidth = linewidth
        self.linewidth_2 = linewidth_2
        self.marker_size = marker_size
        self.line_of_best_fit = line_of_best_fit

        # labelling of sources
        self.brand_label = brand_label
        self.display_brand_label = display_brand_label
        self.source = source
        self.source_color = source_color
        self.display_source_label = display_source_label
        self.display_legend = display_legend

        # display output
        self.silent_display = silent_display
        self.file_output = file_output
        self.date_formatter = date_formatter

        # output
        self.html_file_output = html_file_output
        self.display_mpld3 = display_mpld3

        # bokeh only
        self.bokeh_plot_mode = bokeh_plot_mode  # 'online', 'offline_html', 'offline_jupyter'

        # plotly only
        if plotly_url is None:
            plotly_url = title + datetime.datetime.utcnow().strftime("%b-%d-%Y-%H-%M-%S")

        self.plotly_url = plotly_url
        self.plotly_as_image = plotly_as_image
        self.plotly_username = plotly_username

        # try to get API key from GraphicsConstants file
        try:
            if plotly_api_key is None: plotly_api_key = GraphicsConstants().plotly_creds[plotly_username]
        except: pass

        self.plotly_api_key = plotly_api_key
        self.plotly_world_readable = plotly_world_readable
        self.plotly_theme = plotly_theme
        self.plotly_plot_mode = plotly_plot_mode    # 'online', 'offline_html', 'offline_jupyter'

        # matplotlib only
        self.style_sheet = style_sheet
        self.convert_matplotlib_to_plotly = convert_matplotlib_to_plotly
예제 #8
0
class PlotFactory:

    default_adapter = GraphicsConstants().plotfactory_default_adapter

    def __init__(self):
        pass

    def plot_heatmap_graph(self, data_frame, adapter=default_adapter, gp=None):
        return self.get_adapter(adapter).plot_2d_graph(data_frame, gp,
                                                       'heatmap')

    def plot_scatter_graph(self, data_frame, adapter=default_adapter, gp=None):
        return self.get_adapter(adapter).plot_2d_graph(data_frame, gp,
                                                       'scatter')

    def plot_line_graph(self, data_frame, adapter=default_adapter, gp=None):
        return self.get_adapter(adapter).plot_2d_graph(data_frame, gp, 'line')

    def plot_bar_graph(self, data_frame, adapter=default_adapter, gp=None):
        return self.get_adapter(adapter).plot_2d_graph(data_frame, gp, 'bar')

    def plot_stacked_graph(self, data_frame, adapter=default_adapter, gp=None):
        return self.get_adapter(adapter).plot_2d_graph(data_frame, gp,
                                                       'stacked')

    def tweet_line_graph(self,
                         data_frame,
                         adapter=default_adapter,
                         gp=None,
                         twitter_msg=None,
                         twitter_on=None):
        return self.tweet_generic_graph(data_frame,
                                        type='line',
                                        adapter=adapter,
                                        gp=gp,
                                        twitter_msg=twitter_msg,
                                        twitter_on=twitter_on)

    def tweet_bar_graph(self,
                        data_frame,
                        adapter=default_adapter,
                        gp=None,
                        twitter_msg=None,
                        twitter_on=None):
        return self.tweet_generic_graph(data_frame,
                                        type='bar',
                                        adapter=adapter,
                                        gp=gp,
                                        twitter_msg=twitter_msg,
                                        twitter_on=twitter_on)

    def tweet_generic_graph(self,
                            data_frame,
                            adapter=default_adapter,
                            type='line',
                            gp=None,
                            twitter_msg=None,
                            twitter_on=None):
        self.plot_generic_graph(data_frame, type=type, adapter=adapter, gp=gp)

        twitter = TwitterPyThalesians()
        twitter.auto_set_key()

        if twitter_on:
            twitter.update_status(twitter_msg, picture=gp.file_output)

    def plot_generic_graph(self,
                           data_frame,
                           adapter=default_adapter,
                           type=None,
                           gp=None,
                           excel_file=None,
                           excel_sheet=None,
                           freq='daily'):

        if (excel_file is not None):
            tio = TimeSeriesIO()

            data_frame = tio.read_excel_data_frame(excel_file, excel_sheet,
                                                   freq)

        return self.get_adapter(adapter).plot_2d_graph(data_frame, gp, type)

    def get_adapter(self, adapter):

        if adapter == 'pythalesians' or adapter == 'matplotlib':
            # use pythalesians wrapper for matplotlib
            return AdapterPyThalesians()

        elif adapter == 'seaborn':
            from chartesians import AdapterSeaborn
            return AdapterSeaborn()

        elif adapter == 'bokeh':
            return AdapterBokeh()

        elif adapter == 'cufflinks' or adapter == 'plotly':
            return AdapterCufflinks()

        return None