示例#1
0
    def run_day_of_month_analysis(self, strat):
        from pythalesians.economics.seasonality.seasonality import Seasonality
        from pythalesians.timeseries.calcs.timeseriescalcs import TimeSeriesCalcs

        tsc = TimeSeriesCalcs()
        seas = Seasonality()
        strat.construct_strategy()
        pnl = strat.get_strategy_pnl()

        # get seasonality by day of the month
        pnl = pnl.resample('B').mean()
        rets = tsc.calculate_returns(pnl)
        bus_day = seas.bus_day_of_month_seasonality(rets, add_average = True)

        # get seasonality by month
        pnl = pnl.resample('BM').mean()
        rets = tsc.calculate_returns(pnl)
        month = seas.monthly_seasonality(rets)

        self.logger.info("About to plot seasonality...")
        gp = GraphProperties()
        pf = PlotFactory()

        # Plotting spot over day of month/month of year
        gp.color = 'Blues'
        gp.scale_factor = self.SCALE_FACTOR
        gp.file_output = self.DUMP_PATH + strat.FINAL_STRATEGY + ' seasonality day of month.png'
        gp.html_file_output = self.DUMP_PATH + strat.FINAL_STRATEGY + ' seasonality day of month.html'
        gp.title = strat.FINAL_STRATEGY + ' day of month seasonality'
        gp.display_legend = False
        gp.color_2_series = [bus_day.columns[-1]]
        gp.color_2 = ['red'] # red, pink
        gp.linewidth_2 = 4
        gp.linewidth_2_series = [bus_day.columns[-1]]
        gp.y_axis_2_series = [bus_day.columns[-1]]

        pf.plot_line_graph(bus_day, adapter = self.DEFAULT_PLOT_ENGINE, gp = gp)

        gp = GraphProperties()

        gp.scale_factor = self.SCALE_FACTOR
        gp.file_output = self.DUMP_PATH + strat.FINAL_STRATEGY + ' seasonality month of year.png'
        gp.html_file_output = self.DUMP_PATH + strat.FINAL_STRATEGY + ' seasonality month of year.html'
        gp.title = strat.FINAL_STRATEGY + ' month of year seasonality'

        pf.plot_line_graph(month, adapter = self.DEFAULT_PLOT_ENGINE, gp = gp)

        return month
示例#2
0
    def plot_single_var_regression(self, y, x, y_variable_names, x_variable_names, statistic,
                                          tag = 'stats',
                                          title = None,
                                          pretty_index = None, output_path = None,
                                          scale_factor = Constants.plotfactory_scale_factor,
                                          silent_plot = False,
                                          shift=[0]):

        if not(isinstance(statistic, list)):
            statistic = [statistic]

        # TODO optimise loop so that we are calculating each regression *once* at present calculating it
        # for each statistic, which is redundant
        for st in statistic:
            stats_df = []

            for sh in shift:
                x_sh = x.shift(sh)
                stats_temp = self.report_single_var_regression(y, x_sh, y_variable_names, x_variable_names, st,
                                                             pretty_index)

                stats_temp.columns = [ x + "_" + str(sh) for x in stats_temp.columns]

                stats_df.append(stats_temp)

            stats_df = pandas.concat(stats_df, axis=1)
            stats_df = stats_df.dropna(how='all')

            if silent_plot: return stats_df

            pf = PlotFactory()
            gp = GraphProperties()

            if title is None: title = statistic

            gp.title = title
            gp.display_legend = True
            gp.scale_factor = scale_factor
            # gp.color = ['red', 'blue', 'purple', 'gray', 'yellow', 'green', 'pink']

            if output_path is not None:
                gp.file_output = output_path + ' (' + tag + ' ' + st + ').png'

            pf.plot_bar_graph(stats_df, adapter = 'pythalesians', gp = gp)

        return stats_df
示例#3
0
    def create_graph_properties(self, title, file_add):
        gp = GraphProperties()

        gp.title = self.FINAL_STRATEGY + " " + title
        gp.display_legend = True
        gp.scale_factor = self.SCALE_FACTOR

        if self.DEFAULT_PLOT_ENGINE != 'cufflinks':
            gp.file_output = self.DUMP_PATH + self.FINAL_STRATEGY + ' (' + file_add + ') ' + str(gp.scale_factor) + '.png'

        gp.html_file_output = self.DUMP_PATH + self.FINAL_STRATEGY + ' (' + file_add + ') ' + str(gp.scale_factor) + '.html'

        try:
            gp.silent_display = self.SILENT_DISPLAY
        except: pass

        return gp
        df = ltsf.harvest_time_series(time_series_request)
        df.columns = [x.replace('.close', '') for x in df.columns.values]

        df = tsc.calculate_returns(df) * 100
        df = df.dropna()

        df_sorted = tsc.get_bottom_valued_sorted(df, "USDBRL", n = 20)
        # df = tsc.get_top_valued_sorted(df, "USDBRL", n = 20) # get biggest up moves

        # get values on day after
        df2 = df.shift(-1)
        df2 = df2.ix[df_sorted.index]
        df2.columns = ['T+1']

        df_sorted.columns = ['T']

        df_sorted = df_sorted.join(df2)
        df_sorted.index = [str(x.year) + '/' + str(x.month) + '/' + str(x.day) for x in df_sorted.index]

        gp = GraphProperties()
        gp.title = 'Largest daily falls in USDBRL'
        gp.scale_factor = 3
        gp.display_legend = True
        gp.chart_type = 'bar'
        gp.x_title = 'Dates'
        gp.y_title = 'Pc'
        gp.file_output = "usdbrl-biggest-downmoves.png"

        pf = PlotFactory()
        pf.plot_line_graph(df_sorted, adapter = 'pythalesians', gp=gp)
        from pythalesians.economics.events.eventstudy import EventStudy

        es = EventStudy()

        # work out cumulative asset price moves moves over the event
        df_event = es.get_intraday_moves_over_custom_event(df, df_event_times)

        # create an average move
        df_event['Avg'] = df_event.mean(axis=1)

        # plotting spot over economic data event
        gp = GraphProperties()
        gp.scale_factor = 3

        gp.title = 'USDJPY spot moves over recent NFP'

        # plot in shades of blue (so earlier releases are lighter, later releases are darker)
        gp.color = 'Blues'
        gp.color_2 = []
        gp.y_axis_2_series = []
        gp.display_legend = False

        # last release will be in red, average move in orange
        gp.color_2_series = [df_event.columns[-2], df_event.columns[-1]]
        gp.color_2 = ['red', 'orange']  # red, pink
        gp.linewidth_2 = 2
        gp.linewidth_2_series = gp.color_2_series

        pf = PlotFactory()
        pf.plot_line_graph(df_event * 100, adapter='pythalesians', gp=gp)
        df_event_times.index = df_event_times.index.tz_localize(utc_time)    # work in UTC time

        from pythalesians.economics.events.eventstudy import EventStudy

        es = EventStudy()

        # work out cumulative asset price moves moves over the event
        df_event = es.get_intraday_moves_over_custom_event(df, df_event_times)

        # create an average move
        df_event['Avg'] = df_event.mean(axis = 1)

        # plotting spot over economic data event
        gp = GraphProperties()
        gp.scale_factor = 3

        gp.title = 'USDJPY spot moves over recent NFP'

        # plot in shades of blue (so earlier releases are lighter, later releases are darker)
        gp.color = 'Blues'; gp.color_2 = []
        gp.y_axis_2_series = []
        gp.display_legend = False

        # last release will be in red, average move in orange
        gp.color_2_series = [df_event.columns[-2], df_event.columns[-1]]
        gp.color_2 = ['red', 'orange'] # red, pink
        gp.linewidth_2 = 2
        gp.linewidth_2_series = gp.color_2_series

        pf = PlotFactory()
        pf.plot_line_graph(df_event * 100, adapter = 'pythalesians', gp = gp)
示例#7
0
                vendor_tickers = ['aapl', 'spy'],                   # ticker (Google)
                vendor_fields = ['Close'],                          # which Bloomberg fields to download
                cache_algo = 'internet_load_return')                # how to return data

    ltsf = LightTimeSeriesFactory()
    tsc = TimeSeriesCalcs()

    df = tsc.create_mult_index_from_prices(ltsf.harvest_time_series(time_series_request))

    gp = GraphProperties()
    gp.html_file_output = "output_data/apple.htm"
    gp.title = "S&P500 vs Apple"

    # plot first with PyThalesians and then Bokeh
    # just needs 1 word to change
    gp.display_legend = False

    pf = PlotFactory()
    pf.plot_generic_graph(df, type = 'line', adapter = 'pythalesians', gp = gp)
    pf.plot_generic_graph(df, type = 'line', adapter = 'bokeh', gp = gp)

# test simple Bokeh bar charts - monthly returns over past 6 months
if True:
    from datetime import timedelta
    ltsf = LightTimeSeriesFactory()

    end = datetime.datetime.utcnow()
    start = end - timedelta(days=180)

    tickers = ['S&P500', 'FTSE', 'Nikkei']
    vendor_tickers = ['SPX Index', 'UKX Index', 'NKY Index']
示例#8
0
    short_dates = df[["EURUSDV1M", "USDJPYV1M"]]
    long_dates = df[["EURUSDV1Y", "USDJPYV1Y"]]
    short_dates, long_dates = short_dates.align(long_dates,
                                                join='left',
                                                axis=0)

    slope = pandas.DataFrame(data=short_dates.values - long_dates.values,
                             index=short_dates.index,
                             columns=["EURUSDV1M-1Y", "USDJPYV1M-1Y"])

    # resample fand calculate average over month
    slope_monthly = slope.resample('M').mean()

    slope_monthly.index = [
        str(x.year) + '/' + str(x.month) for x in slope_monthly.index
    ]

    pf = PlotFactory()

    gp = GraphProperties()

    gp.source = 'Thalesians/BBG'
    gp.title = 'Vol slopes in EUR/USD and USD/JPY recently'
    gp.scale_factor = 2
    gp.display_legend = True
    gp.chart_type = 'bar'
    gp.x_title = 'Dates'
    gp.y_title = 'Pc'

    # plot using Cufflinks
    pf.plot_bar_graph(slope_monthly, adapter='cufflinks', gp=gp)