Example #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
Example #2
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
                finish_date = datetime.date.today(),            # finish date
                freq = 'daily',                                 # daily data
                data_source = 'google',                         # use Bloomberg as data source
                tickers = ['Apple', 'S&P500 ETF'],                  # ticker (Thalesians)
                fields = ['close'],                                 # which fields to download
                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()
Example #4
0
    def run_arbitrary_sensitivity(self, strat, parameter_list = None, parameter_names = None,
                                  pretty_portfolio_names = None, parameter_type = None):

        asset_df, spot_df, spot_df2, basket_dict = strat.fill_assets()

        port_list = None
        tsd_list = []

        for i in range(0, len(parameter_list)):
            br = strat.fill_backtest_request()

            current_parameter = parameter_list[i]

            # for calculating P&L
            for k in current_parameter.keys():
                setattr(br, k, current_parameter[k])

            strat.br = br   # for calculating signals

            signal_df = strat.construct_signal(spot_df, spot_df2, br.tech_params, br)

            cash_backtest = CashBacktest()
            self.logger.info("Calculating... " + str(pretty_portfolio_names[i]))

            cash_backtest.calculate_trading_PnL(br, asset_df, signal_df)
            tsd_list.append(cash_backtest.get_portfolio_pnl_tsd())
            stats = str(cash_backtest.get_portfolio_pnl_desc()[0])

            port = cash_backtest.get_cumportfolio().resample('B').mean()
            port.columns = [str(pretty_portfolio_names[i]) + ' ' + stats]

            if port_list is None:
                port_list = port
            else:
                port_list = port_list.join(port)

        # reset the parameters of the strategy
        strat.br = strat.fill_backtest_request()

        pf = PlotFactory()
        gp = GraphProperties()

        ir = [t.inforatio()[0] for t in tsd_list]

        # if we have too many combinations remove legend and use scaled shaded colour
        # if len(port_list) > 10:
            # gp.color = 'Blues'
            # gp.display_legend = False

        # plot all the variations
        gp.resample = 'B'
        gp.file_output = self.DUMP_PATH + strat.FINAL_STRATEGY + ' ' + parameter_type + '.png'
        gp.html_file_output = self.DUMP_PATH + strat.FINAL_STRATEGY + ' ' + parameter_type + '.html'
        gp.scale_factor = self.SCALE_FACTOR
        gp.title = strat.FINAL_STRATEGY + ' ' + parameter_type
        pf.plot_line_graph(port_list, adapter = self.DEFAULT_PLOT_ENGINE, gp = gp)

        # plot all the IR in a bar chart form (can be easier to read!)
        gp = GraphProperties()
        gp.file_output = self.DUMP_PATH + strat.FINAL_STRATEGY + ' ' + parameter_type + ' IR.png'
        gp.html_file_output = self.DUMP_PATH + strat.FINAL_STRATEGY + ' ' + parameter_type + ' IR.html'
        gp.scale_factor = self.SCALE_FACTOR
        gp.title = strat.FINAL_STRATEGY + ' ' + parameter_type
        summary = pandas.DataFrame(index = pretty_portfolio_names, data = ir, columns = ['IR'])
        pf.plot_bar_graph(summary, adapter = self.DEFAULT_PLOT_ENGINE, gp = gp)

        return port_list
from chartesians.graphs.graphproperties import GraphProperties
from chartesians.graphs.plotfactory import PlotFactory

from pythalesians.market.loaders.lighttimeseriesfactory import LightTimeSeriesFactory
from pythalesians.market.requests.timeseriesrequest import TimeSeriesRequest
from pythalesians.timeseries.calcs.timeseriescalcs import TimeSeriesCalcs


if True:
    import pandas
    df = pandas.read_csv("volsurface.csv")  # load a snapshot for a vol surface from disk

    gp = GraphProperties()
    gp.plotly_plot_mode = "offline_html"    # render Plotly plot locally (rather than via website)
    gp.file_output = "volsurface.png"       # save as static PNG file
    gp.html_file_output = "volsurface.html" # save as interactive HTML file

    gp.title = "GBP/USD vol surface"
    gp.color = 'Blues'

    # plot surface with Plotly
    pf = PlotFactory()
    pf.plot_generic_graph(df, type = 'surface', adapter = 'cufflinks', gp = gp)

if True:

    time_series_request = TimeSeriesRequest(
                start_date = "01 Jan 2013",                     # start date
                finish_date = datetime.date.today(),            # finish date
                freq = 'daily',                                 # daily data
                data_source = 'google',                         # use Bloomberg as data source
Example #6
0
from chartesians.graphs.graphproperties import GraphProperties
from chartesians.graphs.plotfactory import PlotFactory

from pythalesians.market.loaders.lighttimeseriesfactory import LightTimeSeriesFactory
from pythalesians.market.requests.timeseriesrequest import TimeSeriesRequest
from pythalesians.timeseries.calcs.timeseriescalcs import TimeSeriesCalcs

if True:
    import pandas
    df = pandas.read_csv(
        "volsurface.csv")  # load a snapshot for a vol surface from disk

    gp = GraphProperties()
    gp.plotly_plot_mode = "offline_html"  # render Plotly plot locally (rather than via website)
    gp.file_output = "volsurface.png"  # save as static PNG file
    gp.html_file_output = "volsurface.html"  # save as interactive HTML file

    gp.title = "GBP/USD vol surface"
    gp.color = 'Blues'

    # plot surface with Plotly
    pf = PlotFactory()
    pf.plot_generic_graph(df, type='surface', adapter='cufflinks', gp=gp)

if True:

    time_series_request = TimeSeriesRequest(
        start_date="01 Jan 2013",  # start date
        finish_date=datetime.date.today(),  # finish date
        freq='daily',  # daily data
        data_source='google',  # use Bloomberg as data source
            data_source='bloomberg',  # use Bloomberg as data source
            tickers=tickers,  # ticker (Thalesians)
            fields=['close'],  # which fields to download
            vendor_tickers=vendor_tickers,  # ticker (Bloomberg)
            vendor_fields=['PX_LAST'],  # which Bloomberg fields to download
            cache_algo='internet_load_return')  # how to return data

        daily_vals = ltsf.harvest_time_series(time_series_request)

        pf = PlotFactory()

        gp = GraphProperties()

        gp.title = 'Spot values'
        gp.file_output = 'output_data/demo.png'
        gp.html_file_output = 'output_data/demo.htm'
        gp.source = 'Thalesians/BBG'

        # plot using PyThalesians
        pf.plot_line_graph(daily_vals, adapter='pythalesians', gp=gp)

        # plot using Bokeh (still needs a lot of work!)
        pf.plot_line_graph(daily_vals, adapter='bokeh', gp=gp)

    # do more complicated charts using several different Matplotib stylesheets (which have been customised)
    if False:
        ltsf = LightTimeSeriesFactory()

        # load market data
        start = '01 Jan 1970'
        end = datetime.datetime.utcnow()