コード例 #1
0
    def update_metrics(self):
        self.dates = self.stock_data['date']
        self.stock_prices = self.stock_data['adjclose']
        self.bench_prices = self.bench_data['adjclose']
        self.ratearray = rate_array(self.stock_data)
        self.bencharray = rate_array(self.bench_data)

        # TODO: Not sure if these are the metrics I'm looking for...
        self.annual_volatility = volatility(self.ratearray)
        self.beta = beta_bb(self.ratearray, self.bencharray)
        self.annualized_adjusted_return = annualized_adjusted_rate(self.ratearray, rfr=0.01)
        self.expected_return = expected_return(self.ratearray,
                                               self.bencharray,
                                               rfr=self.rfr)
        return
コード例 #2
0
def test_annualized_adjusted_rate():
    """ Check annual rate of return."""
    pa = np.array(dummy_data, dtype=schema)
    ra = metrics.rate_array(pa)
    aar = metrics.annualized_adjusted_rate(ra)
    # This is not a great test ... needs to be independently calculated, 
    #     as does the rate array data.
    np.testing.assert_almost_equal(aar, 2.6020844941637074)
コード例 #3
0
def test_rate_array():
    """ simple test of pricearray in, ratearray out.
        TODO: Note, this thing fails when I do a complete comparison, so I
            just compare the rate columns.
    """

    rate_dt = np.dtype({'names':['date', 'rate'],
                        'formats':['M8', float]})
    ra_correct = np.array([("2001-01-01", 0.0),
                  ("2001-01-02", 0.01),
                  ("2001-01-03", -0.019801980198),
                  ("2001-01-04", 0.010101010101),
                  ("2001-01-05", 0.01),
                  ("2001-01-08", -0.00990099009901)], dtype=rate_dt)
                      
    # Construct dummy array.
    pa = np.array(dummy_data, dtype=schema)
    ra = metrics.rate_array(pa)
    #print "ra:", ra
    #print "ra_correct:", ra_correct
    x = ra[:][1]
    y = ra[:][1]
    np.testing.assert_array_equal(x, y)
コード例 #4
0
    def _create_plot_component(self):

        # find longest date
        index_lengths = []
        for stock in self.stocks:
            if stock.stock_data_cache is not None:
                index_lengths.append(len(stock.stock_data_cache['date']))
            else:
                index_lengths.append(len(stock.stock_data['date']))

        index_lengths = np.array(index_lengths)
        lngest = index_lengths.argmax()
        shrtest = index_lengths.argmin()

        index = np.array([
            time.mktime(x.timetuple())
            for x in self.stocks[lngest].dates.tolist()
        ])

        sel_range_low = time.mktime(
            self.stocks[shrtest].dates.tolist()[0].timetuple())
        sel_range_high = time.mktime(
            self.stocks[shrtest].dates.tolist()[-1].timetuple())

        sel_range_low_idx = np.where(index == sel_range_low)[0].item()
        sel_range_high_idx = np.where(index == sel_range_high)[0].item()

        pd = ArrayPlotData()

        # Now plot the returns for each asset (cumulative sum of periodic rates of return)
        for i in range(len(self.stocks)):
            if self.stocks[i].stock_data_cache is None:
                stk = self.stocks[i].stock_data
            else:
                stk = self.stocks[i].stock_data_cache
            pd.set_data(
                "idx%s" % i,
                np.array([
                    time.mktime(x.timetuple()) for x in stk['date'].tolist()
                ]))
            pd.set_data("y%s" % i, metrics.rate_array(stk)['rate'].cumsum())

        plot = Plot(pd,
                    bgcolor="none",
                    padding=30,
                    border_visible=True,
                    overlay_border=True,
                    use_backbuffer=False)

        for i in range(len(self.stocks)):
            # hang on to a reference to the last one of these...
            plt = plot.plot(("idx%s" % i, "y%s" % i),
                            name=self.stocks[i].symbol,
                            color=self.colors[i])

        #value_range = plot.value_mapper.range
        #index_range = plot.index_mapper.range

        plt[0].active_tool = RangeSelection(plt[0], left_button_selects=True)
        plt[0].active_tool.selection = [
            index[sel_range_low_idx], index[sel_range_high_idx]
        ]
        plt[0].overlays.append(RangeSelectionOverlay(component=plt[0]))
        #plot.bgcolor = "white"
        plot.padding = 50
        add_default_grids(plot)

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(
            fill_ratio=0.4,
            default_numlabels=5,
            default_numticks=10,
        )
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = PlotAxis(plot,
                               orientation="bottom",
                               tick_generator=tick_gen,
                               label_color="white",
                               line_color="white")

        # Hack to remove default axis - TODO: how do I *replace* an axis?
        del (plot.underlays[-4])

        plot.overlays.append(bottom_axis)
        plot.legend.visible = True
        return plot
コード例 #5
0
    def _create_plot_component(self):

        # find longest date
        index_lengths = []
        for stock in self.stocks:
            if stock.stock_data_cache is not None:
                index_lengths.append(len(stock.stock_data_cache['date']))
            else:
                index_lengths.append(len(stock.stock_data['date']))

        index_lengths = np.array(index_lengths)
        lngest = index_lengths.argmax()
        shrtest = index_lengths.argmin()

        index = np.array([time.mktime(x.timetuple()) for x in self.stocks[lngest].dates.tolist()])

        sel_range_low = time.mktime(self.stocks[shrtest].dates.tolist()[0].timetuple())
        sel_range_high = time.mktime(self.stocks[shrtest].dates.tolist()[-1].timetuple())

        sel_range_low_idx = np.where(index==sel_range_low)[0].item()
        sel_range_high_idx = np.where(index==sel_range_high)[0].item()

        pd = ArrayPlotData()

        # Now plot the returns for each asset (cumulative sum of periodic rates of return)
        for i in range(len(self.stocks)):
            if self.stocks[i].stock_data_cache is None:
                stk = self.stocks[i].stock_data
            else:
                stk = self.stocks[i].stock_data_cache
            pd.set_data("idx%s" % i, np.array([time.mktime(x.timetuple()) for x in stk['date'].tolist()]))
            pd.set_data("y%s" % i, metrics.rate_array(stk)['rate'].cumsum())

        plot = Plot(pd, bgcolor="none", padding=30, border_visible=True,
                     overlay_border=True, use_backbuffer=False)

        for i in range(len(self.stocks)):
            # hang on to a reference to the last one of these...
            plt = plot.plot(("idx%s" % i, "y%s" % i), name=self.stocks[i].symbol, color=self.colors[i])

        #value_range = plot.value_mapper.range
        #index_range = plot.index_mapper.range

        plt[0].active_tool = RangeSelection(plt[0], left_button_selects=True)
        plt[0].active_tool.selection=[index[sel_range_low_idx], index[sel_range_high_idx]]
        plt[0].overlays.append(RangeSelectionOverlay(component=plt[0]))
        #plot.bgcolor = "white"
        plot.padding = 50
        add_default_grids(plot)

        # Set the plot's bottom axis to use the Scales ticking system
        scale_sys = CalendarScaleSystem(fill_ratio=0.4,
                                        default_numlabels=5,
                                        default_numticks=10,)
        tick_gen = ScalesTickGenerator(scale=scale_sys)

        bottom_axis = PlotAxis(plot, orientation="bottom",
                                     tick_generator=tick_gen,
                                     label_color="white",
                                     line_color="white")

        # Hack to remove default axis - TODO: how do I *replace* an axis?
        del(plot.underlays[-4])

        plot.overlays.append(bottom_axis)
        plot.legend.visible = True
        return plot
コード例 #6
0
def test_chain_linked_return():
    """ Chain linked return should be 'total return.'"""
    pa = np.array(dummy_data, dtype=schema)
    ra = metrics.rate_array(pa)
    clr = metrics.chain_linked_return(ra)
    np.testing.assert_almost_equal(clr, 0.05)