Exemplo n.º 1
0
def TableInfluenceIntegerVariables():
    """
    Illustrates the influence of the additional Integer constraints (Nmax and Wmin) on computation time. Computes,
    draws and plots MAD Model computation time on N scenarios with N increasing, with the different parameters.
    """
    rows = []
    N = [10, 50, 100, 200, 300, 400, 500, 1000]
    params = [{
        'Wmin': Wmin,
        'Nmax': Nmax
    } for Nmax in (None, 5) for Wmin in (None, 0.005)]
    print(params)
    for n in N:
        print("Computing with {:d} scenarios".format(n))
        s, p = generateGaussianScenarios(n)
        row = [n]
        for param in params:
            t = time()
            MAD(s, p, **param).optimize()
            row.append(time() - t)
        rows.append(row)
    rows = np.array(rows)
    print("\nComputation times:\n")
    headers = ['N', 'LP', 'Wmin', 'Nmax', 'Wmin and Nmax']
    print(tabulate(rows, headers=headers))
    for i in range(1, 5):
        plt.plot(N, rows[:, i], label=headers[i])
    plt.legend(loc='upper left')
    plt.xlabel('Number of scenarios')
    plt.ylabel('Computation time (s)')
    plt.title('Influence of additional integer variables on computation time')
    plt.show()
Exemplo n.º 2
0
    def test_same_output(self):
        """Checks that the MAD and the SemiMAD give the same output portfolio and half of the objective value."""
        s, p = generateGaussianScenarios()
        m = MAD(s, p).optimize()
        m2 = SemiMAD(s, p).optimize()

        self.assertAlmostEqual((m.getPortfolio() - m2.getPortfolio()).max(),
                               0,
                               places=4)
        self.assertAlmostEqual(m.objval, 2 * m2.objval)
Exemplo n.º 3
0
        def test_reconfigure(self):
            """
            Checks that reconfiguring the model with new scenarios/probas gives the same output as creating a new Model.
            """
            s, p = self.scenarios, self.probas
            s2, p2 = generateGaussianScenarios(
                len(p), seed=self.seed + 1 if self.seed is not None else None)

            self.assertEqual(
                self.Model(s, p).update().reconfigure(s2,
                                                      p2).optimize().objval,
                self.Model(s2, p2).optimize().objval)
Exemplo n.º 4
0
def test_generation_student(stock1, stock2, nu=4):
    r1 = Returns.iloc[:, stock1]
    r2 = Returns.iloc[:, stock2]
    bins1 = np.linspace(- r1.quantile(0.05), r1.quantile(0.95), 100)
    bins2 = np.linspace(- r2.quantile(0.05), r2.quantile(0.95), 100)
    plt.figure(1, figsize=(14, 8))
    plt.subplot(321)
    plt.hist(r1, normed=True, bins=bins1)
    plt.subplot(322)
    plt.hist(r2, normed=True, bins=bins2)
    students = generateStudentTScenarios(nu, 100000)[0]
    plt.subplot(323)
    plt.hist(students[:, stock1], normed=True, bins=bins1)
    plt.subplot(324)
    plt.hist(students[:, stock2], normed=True, bins=bins2)
    plt.subplot(325)
    gaussians = generateGaussianScenarios(100000)[0]
    plt.hist(gaussians[:, stock1], normed=True, bins=bins1)
    plt.subplot(326)
    plt.hist(gaussians[:, stock2], normed=True, bins=bins2)
    plt.show()
Exemplo n.º 5
0
 def setUp(self):
     self.seed = 5
     self.scenarios, self.probas = generateGaussianScenarios(
         100, seed=self.seed)
Exemplo n.º 6
0
        # Plots the beta % worst returns
        plt.plot(worstIndex,
                 returns[worstIndex],
                 'o',
                 color='red',
                 label='{:.0%} Worst Cases'.format(self._beta))
        plt.plot(oldWorstIndex,
                 equally[oldWorstIndex],
                 'o',
                 color='orange',
                 label='E.W. {:.0%} Worst Cases'.format(self._beta))

        # Plots the mean of the beta % worst returns in equally weighted portfolio
        plt.plot([S[0], S[-1]], [oldMean, oldMean], '-', color='orange')
        # Plots the mean of the beta % worst returns
        plt.plot([S[0], S[-1]], [mean, mean], '-', color='red')

        plt.xlabel('Scenarios')
        plt.ylabel('Returns')
        plt.title('Conditional Value-at-Risk Optimization with {:d} scenarios'.
                  format(len(S)))
        plt.gca().yaxis.set_major_formatter(
            FuncFormatter(lambda y, _: '{:.0%}'.format(y)))
        plt.legend()
        plt.show()


if __name__ == '__main__':
    s, p = generateGaussianScenarios(300)
    CVaR(s, p, output=True).optimize().plot()
Exemplo n.º 7
0
                         xy=(middle, values[Min]),
                         xytext=(middle, values[Max]),
                         fontsize=7,
                         color='red',
                         arrowprops=dict(arrowstyle='<->',
                                         shrinkA=0,
                                         shrinkB=0,
                                         lw=2,
                                         color='red'))

            plt.plot([Min, middle], [values[Min], values[Min]],
                     '--',
                     color='red',
                     lw=2)
            plt.plot([middle, Max], [values[Max], values[Max]],
                     '--',
                     color='red',
                     lw=2)

        plt.xlabel('Scenarios')
        plt.ylabel('Returns')
        plt.gca().yaxis.set_major_formatter(
            FuncFormatter(lambda y, _: '{:.0%}'.format(y)))
        plt.title('GMD Optimization with {:d} scenarios'.format(len(S)))
        plt.legend()
        plt.show()


if __name__ == '__main__':
    GMD(*generateGaussianScenarios(100)).optimize().plot()
Exemplo n.º 8
0
def TestMADSemiMAD():
    """Checks that MAD and Semi MAD model lead to the same portfolio, and that MAD = 2 * SemiMAD."""
    s, p = generateGaussianScenarios()
    MADPort = MAD(s, p).optimize().getPortfolio()
    SemiMADPort = SemiMAD(s, p).optimize().getPortfolio()
    PortfolioGroup([MADPort, SemiMADPort]).plot()