示例#1
0
    def g10_line_plot_gdp(self, start_date, finish_date):
        today_root = datetime.date.today().strftime("%Y%m%d") + " "
        country_group = 'g10-ez'
        gdp = self.get_GDP_QoQ(start_date, finish_date, country_group)

        from chartesians.graphs import PlotFactory
        from chartesians.graphs.graphproperties import GraphProperties

        gp = GraphProperties()
        pf = PlotFactory()

        gp.title = "G10 GDP"
        gp.units = 'Rebased'
        gp.scale_factor = Constants.plotfactory_scale_factor
        gp.file_output = today_root + 'G10 UNE ' + str(
            gp.scale_factor) + '.png'
        gdp.columns = [x.split('-')[0] for x in gdp.columns]
        gp.linewidth_2 = 3
        gp.linewidth_2_series = ['United Kingdom']

        from pythalesians.timeseries.calcs.timeseriescalcs import TimeSeriesCalcs
        tsc = TimeSeriesCalcs()
        gdp = gdp / 100
        gdp = tsc.create_mult_index_from_prices(gdp)
        pf.plot_generic_graph(gdp, type='line', adapter='pythalesians', gp=gp)
示例#2
0
    def compare_strategy_vs_benchmark(self, br, strategy_df, benchmark_df):
        """
        compare_strategy_vs_benchmark - Compares the trading strategy we are backtesting against a benchmark

        Parameters
        ----------
        br : BacktestRequest
            Parameters for backtest such as start and finish dates

        strategy_df : pandas.DataFrame
            Strategy time series

        benchmark_df : pandas.DataFrame
            Benchmark time series
        """

        include_benchmark = False
        calc_stats = False

        if hasattr(br, 'include_benchmark'): include_benchmark = br.include_benchmark
        if hasattr(br, 'calc_stats'): calc_stats = br.calc_stats

        if include_benchmark:
            tsd = TimeSeriesDesc()
            cash_backtest = CashBacktest()
            ts_filter = TimeSeriesFilter()
            ts_calcs = TimeSeriesCalcs()

            # align strategy time series with that of benchmark
            strategy_df, benchmark_df = strategy_df.align(benchmark_df, join='left', axis = 0)

            # if necessary apply vol target to benchmark (to make it comparable with strategy)
            if hasattr(br, 'portfolio_vol_adjust'):
                if br.portfolio_vol_adjust is True:
                    benchmark_df = cash_backtest.calculate_vol_adjusted_index_from_prices(benchmark_df, br = br)

            # only calculate return statistics if this has been specified (note when different frequencies of data
            # might underrepresent vol
            if calc_stats:
                benchmark_df = benchmark_df.fillna(method='ffill')
                tsd.calculate_ret_stats_from_prices(benchmark_df, br.ann_factor)
                benchmark_df.columns = tsd.summary()

            # realign strategy & benchmark
            strategy_benchmark_df = strategy_df.join(benchmark_df, how='inner')
            strategy_benchmark_df = strategy_benchmark_df.fillna(method='ffill')

            strategy_benchmark_df = ts_filter.filter_time_series_by_date(br.plot_start, br.finish_date, strategy_benchmark_df)
            strategy_benchmark_df = ts_calcs.create_mult_index_from_prices(strategy_benchmark_df)

            self._benchmark_pnl = benchmark_df
            self._benchmark_tsd = tsd

            return strategy_benchmark_df

        return strategy_df
    def g10_line_plot_gdp(self, start_date, finish_date):
        today_root = datetime.date.today().strftime("%Y%m%d") + " "
        country_group = 'g10-ez'
        gdp = self.get_GDP_QoQ(start_date, finish_date, country_group)

        from pythalesians_graphics.graphs import PlotFactory
        from pythalesians_graphics.graphs.graphproperties import GraphProperties

        gp = GraphProperties()
        pf = PlotFactory()

        gp.title = "G10 GDP"
        gp.units = 'Rebased'
        gp.scale_factor = Constants.plotfactory_scale_factor
        gp.file_output = today_root + 'G10 UNE ' + str(gp.scale_factor) + '.png'
        gdp.columns = [x.split('-')[0] for x in gdp.columns]
        gp.linewidth_2 = 3
        gp.linewidth_2_series = ['United Kingdom']

        from pythalesians.timeseries.calcs.timeseriescalcs import TimeSeriesCalcs
        tsc = TimeSeriesCalcs()
        gdp = gdp / 100
        gdp = tsc.create_mult_index_from_prices(gdp)
        pf.plot_generic_graph(gdp, type = 'line', adapter = 'pythalesians', gp = gp)
示例#4
0
from pythalesians.market.loaders.lighttimeseriesfactory import LightTimeSeriesFactory

ltsf = LightTimeSeriesFactory()
daily_vals = ltsf.harvest_time_series(time_series_request)


# We now have the various time series in a pandas dataframe. We can rebase all the datapoints using a function in TimeSeriesCalcs

# In[ ]:

from pythalesians.timeseries.calcs.timeseriescalcs import TimeSeriesCalcs

tsc = TimeSeriesCalcs()

df = tsc.create_mult_index_from_prices(daily_vals)
df = df.fillna(method='ffill')


# Lastly we can plot the results! We shall plot it with the PlotFactory class using PyThalesians engine (a wrapper on top of matplotlib). We can specify the properties of the plot using a GraphProperties class. The first line, forces matplotlib to give us the plot in the notebook, as opposed to a separate window. 

# In[ ]:

get_ipython().magic(u'matplotlib inline')

from pythalesians.graphics.graphs.plotfactory import PlotFactory
from pythalesians.graphics.graphs.graphproperties import GraphProperties

gp = GraphProperties()

gp.source = 'Thalesians/BBG (created with PyThalesians Python library)'
示例#5
0
    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
        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.title = "S&P500 vs Apple"

    # plot first with PyThalesians and then Plotly (via Cufflinks)
    # just needs 1 word to change
    # (although, note that AdapterCufflinks does have some extra parameters that can be set in
    # GraphProperties)
    gp.plotly_username = '******'
    gp.plotly_world_readable = True

    pf = PlotFactory()
    pf.plot_generic_graph(df, type='line', adapter='pythalesians', gp=gp)
    pf.plot_generic_graph(df, type='line', 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
                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:
                'AUDUSD BGN Curncy'
            ],
            vendor_fields=['close'],  # which Bloomberg fields to download
            cache_algo='internet_load_return')  # how to return data

        ltsf = LightTimeSeriesFactory()

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

        gp = GraphProperties()
        pf = PlotFactory()
        gp.source = 'Thalesians/BBG (created with PyThalesians Python library)'

        tsc = TimeSeriesCalcs()
        df = tsc.create_mult_index_from_prices(df)

        pf.plot_line_graph(df, adapter='pythalesians', gp=gp)

    ###### download daily data from Quandl (via FRED) for EUR/USD and GBP/USD spot and then plot
    if True:

        time_series_request = TimeSeriesRequest(
            start_date="01 Jan 1970",  # start date
            finish_date=datetime.date.today(),  # finish date
            freq='daily',  # daily data
            data_source='quandl',  # use Quandl as data source
            tickers=[
                'EURUSD',  # ticker (Thalesians)
                'GBPUSD'
            ],
        time_series_request_total_ret = copy.copy(time_series_request_spot)
        time_series_request_total_ret.tickers = ['EURUSD', 'GBPUSD', 'AUDUSD']
        time_series_request_total_ret.vendor_tickers = ['EURUSDCR BGN Curncy', 'GBPUSDCR BGN Curncy', 'AUDUSDCR BGN Curncy']

        ltsf = LightTimeSeriesFactory()

        df = None
        spot_df = ltsf.harvest_time_series(time_series_request_spot)
        deposit_df = ltsf.harvest_time_series(time_series_request_deposit)

        deposit_df = deposit_df.fillna(method = 'ffill')
        deposit_df = deposit_df.fillna(method = 'bfill') # bit of a hack - because some deposit data sparse
        tot_df = ltsf.harvest_time_series(time_series_request_total_ret)
        tsc = TimeSeriesCalcs()

        tot_df = tsc.create_mult_index_from_prices(tot_df) # rebase index at 100

        # we can change the
        tenor = 'ON'

        # plot total return series comparison for all our crosses
        # in practice, we would typically make a set of xxxUSD total return indices
        # and use them to compute all other crosses (assuming we are USD denominated investor)
        for cross in ['AUDUSD', 'EURUSD', 'GBPUSD']:

            # create total return index using spot + deposits
            ind = IndicesFX()
            ind_df = ind.create_total_return_index(cross, tenor, spot_df, deposit_df)
            ind_df.columns = [x + '.PYT (with carry)' for x in ind_df.columns]

            # grab total return index which we downloaded from Bloomberg
            ],
            vendor_fields=["close"],  # which Bloomberg fields to download
            cache_algo="internet_load_return",
        )  # how to return data

        ltsf = LightTimeSeriesFactory()

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

        gp = GraphProperties()
        pf = PlotFactory()
        gp.source = "Thalesians/BBG (created with PyThalesians Python library)"

        tsc = TimeSeriesCalcs()
        df = tsc.create_mult_index_from_prices(df)

        pf.plot_line_graph(df, adapter="pythalesians", gp=gp)

    ###### download daily data from Quandl (via FRED) for EUR/USD and GBP/USD spot and then plot
    if False:

        time_series_request = TimeSeriesRequest(
            start_date="01 Jan 1970",  # start date
            finish_date=datetime.date.today(),  # finish date
            freq="daily",  # daily data
            data_source="quandl",  # use Quandl as data source
            tickers=["EURUSD", "GBPUSD"],  # ticker (Thalesians)
            fields=["close"],  # which fields to download
            vendor_tickers=["FRED/DEXUSEU", "FRED/DEXUSUK"],  # ticker (Quandl)
            vendor_fields=["close"],  # which Bloomberg fields to download