Ejemplo n.º 1
0
 def __init__(self, V, m):
     self.V = V
     self.m = m
     self.generator = GaussianGenerator()
     self.h_plus = array([], dtype=np.int64).reshape(0, N + 1)
     self.RT = array([], dtype=np.int64).reshape(0, N + 1)
     self.counter = count()
Ejemplo n.º 2
0
class LValueFunctionUpdater:
    def __init__(self, V, m):
        self.V = V
        self.m = m
        self.generator = GaussianGenerator()
        self.h_plus = array([], dtype=np.int64).reshape(0, N + 1)
        self.RT = array([], dtype=np.int64).reshape(0, N + 1)
        self.counter = count()

    def __next__(self):
        s = next(self.counter)
        print("Scenario", s)

        # Initialization
        deltaV = zeros((T, N + 1))
        h_plus = zeros(N + 1)
        h_plus[0] = init

        print("\tTime 0")
        self.m.solve(ones(N + 1), h_plus, self.V[0])
        h_plus = self.m.h_plus

        # 1 <= t <= T - 1
        for t in range(1, T):
            self.m.solve(self.generator.generate(), h_plus, self.V[t])
            h_plus = self.m.h_plus
            deltaV[t - 1] = self.m.deltaV

        # Last returns (which we store for later scenarios)
        self.RT = np.vstack((self.RT, self.generator.generate()))
        self.h_plus = np.vstack((self.h_plus, h_plus))

        # t = T
        print("\tLast time: t =", T)
        ΔCVaR = generateΔCVaR(self.RT[:s + 1], self.h_plus[:s + 1])
        deltaV[T - 1] = (1 - gamma) * self.RT[s] - gamma * ΔCVaR

        self.V[:] = (1 - alpha[s]) * self.V + alpha[s] * deltaV
Ejemplo n.º 3
0
        fig = figure(figsize=figsize)
        ax = fig.gca()

        ax.plot([Data_test.index[0], Data_test.index[-1]], [0, 0],
                color='black',
                lw=1)
        perf_ew.plot(ax=ax, label='EW Portfolio', color='blue', lw=1)
        colors = ['purple', 'cyan', 'yellow']
        for i, (RRR, perf_RRR) in enumerate(perf_marko.items()):
            perf_RRR.plot(ax=ax,
                          label='Markowitz {:.0f}\%'.format(RRR * 100),
                          lw=1,
                          color=colors[i])

        # Single Period
        R = GaussianGenerator(r=r, start=start, end=middle).generate(S)
        single_h = singlePeriodModel(R, gamma)
        perf_single = (Gross_test.cumprod() * single_h).sum(axis=1) / init - 1
        """:type: pandas.DataFrame"""
        print('\tSingle {}: {:.1%}'.format(gamma, perf_single[-1]))
        perf_single.plot(ax=ax, label='SP', color='green', lw=1)

        # Multi Period
        for (type, type_key, style) in (('gaussian', 'G', '-'), ('student',
                                                                 'T', '--')):
            for (m, color) in [(3, 'orange'), (5, 'red')]:
                dir_name = perf_dir_name.format(type, S, k, key, m, gamma * 10)
                try:
                    with open(dir_name + "strategy", "rb") as file:
                        strategy = pickle.load(file)
                except FileNotFoundError as e:
Ejemplo n.º 4
0
from matplotlib import pyplot as plt

from adp.generator import GaussianGenerator
from adp.plot.slopes import FirstSlopeAx
from adp.plot.test import GrossTestPlotter
from adp.plot.wealth import FinalReturnPlotter
from adp.pwladp.trainer import ADPStrategyTrainer
from adp.strategy import ADPStrategy
from adp.value_function import PWLDynamicFunction
from parameters import S, repeat

strategy = ADPStrategy(
    value_function_class=PWLDynamicFunction)  # Value Function
generator = GaussianGenerator(r=0.001)  # Scenarios Generator
trainer = ADPStrategyTrainer(gamma=0.2, generator=generator)  # Process trainer

# Plotters
plt.ion()
plotters = [
    # PWLValueFunctionPlotter(i, strategy),
    FinalReturnPlotter(trainer, lengths=(10, 50)),
    GrossTestPlotter(trainer, strategy)
]

firstSlopeAx = FirstSlopeAx(strategy)

for s in range(S):
    print(s)
    trainer.train(strategy)
    if s % repeat == 1:
        for plotter in plotters:
Ejemplo n.º 5
0
from adp.generator import GaussianGenerator
from adp.plot.slopes import FirstSlopeAx
from adp.plot.test import GrossTestPlotter
from adp.plot.value_function import PWLValueFunctionPlotter
from adp.plot.wealth import FinalReturnPlotter
from adp.pwladp.trainer import ADPStrategyTrainer
from adp.strategy import ADPStrategy
from adp.value_function import PWLDynamicFunction
from data import Data
from parameters import S, freq, periods, repeat
from report.config import *

(period, start, middle, end, _) = periods[3]

Gross_test = (Data.asfreq(freq, method='pad').pct_change() + 1)[1:][middle:end]
generator = GaussianGenerator(start=start, end=middle)
strategy = ADPStrategy(value_function_class=PWLDynamicFunction)
trainer = ADPStrategyTrainer(gamma=0.5, generator=generator)

# Plot
ion()
plotters = [PWLValueFunctionPlotter(i, strategy) for i in []] \
           + [FinalReturnPlotter(trainer, lengths=(10, 50)),
              # FinalPositionsPlotter(trainer),
              # SlopesNumberPlotter(V),
              # MeanSlopesPlotter(V),
              # MeanBreaksPlotter(V)
              GrossTestPlotter(trainer)
              ]

firstSlopeAx = FirstSlopeAx(strategy)
Ejemplo n.º 6
0
from adp.generator import GaussianGenerator
from adp.pwladp.trainer import ADPStrategyTrainer
from adp.strategy import ADPStrategy
from adp.value_function import PWLDynamicFunction
from data import Data, Returns
from markowitz.model import Markowitz

# Train
Returns_train = Returns['2015']

# Test
Returns_test = Data.asfreq('W-FRI', method='pad').pct_change()[1:]['2016']

strategy = ADPStrategy(value_function_class=PWLDynamicFunction)

# Process trainer
trainer = ADPStrategyTrainer(gamma=0.1, generator=GaussianGenerator(r=0.001))
test_perf = []

trainer.train(strategy)

adp_return = strategy.score(Returns_test + 1)

markowitz = Markowitz(mean=Returns_train.mean(), cov=Returns_train.cov())
port = markowitz.optimize().getPortfolio()

marko_return = ((Returns_test + 1).prod() * port).sum() - 1
print('Markowitz return: {:.1%}'.format(marko_return))
Ejemplo n.º 7
0
    print('\tMarkowitz')
    for RRR in np.arange(0.1, 0.5, 0.05):

        model = Markowitz(mean=Return_train.mean(),
                          cov=Return_train.cov(),
                          RRR=RRR)
        port = model.optimize().getPortfolio()
        # port.plot()

        # Testing
        perf = (Data_test.iloc[-1] / Data_test.iloc[0] * port *
                (1 - theta)).sum() - 1
        print('\t\t', '{:.2%} {:.1%}'.format(RRR, perf))

    g = GaussianGenerator(r=r, start=start, end=middle)

    print('\tSingle Period')
    # Scenarios Generator on the training data
    for gamma in [0, 0.2, 0.4, 0.6, 0.8, 1]:

        R = np.array([g.generate() for s in range(S)])
        h = singlePeriodModel(R, gamma)

        perf = (
            (1 + r) * h[0] +
            (Data_test.iloc[-1] / Data_test.iloc[0] * h[1:]).sum()) / init - 1
        print('\t\t{}: {:.1%}'.format(gamma, perf))

    m = 5
    print('\tMulti Period')