def simulate(tickers, baseline, start, end, cost): if baseline not in tickers: tickers += [baseline] dates = pd.date_range(start, end) data = process.Pipe( process.Baseline(baseline), process.FillMissing(), process.Range(dates), ).process(reader.CsvReader().read_column(tickers, ColumnName.ADJCLOSE)) simulator = Simulator(data, 252) allocations = [] for ticker in tickers: allocations += [Allocation(ticker, 1)] sim = process.Merge().process( # simulator.run(HoldMoney(cost), "Hold money"), simulator.run(HoldAllocation(cost, [Allocation(baseline, 1)]), "Hold only baseline"), simulator.run(MonthlyRebalance(HoldAllocation(cost, allocations)), "Hold equal allocation + mrb"), simulator.run( MonthlyRebalance( OptimizerAllocation( cost, trade.data.optimize.FitLine( trade.data.optimize.ReversSharpeRatio(), False))), "Optimizer allocation + mrb")) print(sim) plot.Plot(plot.Graph()).process(sim)
def test_too_long(self): allocations = [ Allocation("SPY", 30), Allocation("GOOG", 40), Allocation("GLD", 30) ] with self.assertRaises(ValueError) as context: Portfolio(allocations).process(self.df)
def __init__(self, allocations, total_cost=1.0): self.tickers = [allocation.ticker for allocation in allocations] parts = [allocation.number for allocation in allocations] total = np.sum(np.abs(parts)) parts = [float(part) / total for part in parts] self.costs = pd.Series([part * total_cost for part in parts], index=self.tickers) self.processor = Pipe( Filter(self.tickers), Lambda(lambda df: self.costs / df.iloc[-1]), Lambda(lambda s: AllocationSet([ Allocation(ticker, int(number)) for ticker, number in s.items() ])))
def _lists_to_allocations(columns, parts): return [Allocation(columns[i], parts[i]) for i in range(len(columns))]
def test_normal(self): allocations = [Allocation("SPY", 30), Allocation("GOOG", 70)] portfolio_set = PortfolioSet(allocations, 20000).process(self.df) self.assertEqual(portfolio_set.data["SPY"], 17) self.assertEqual(portfolio_set.data["GOOG"], 8)
def test_wrong_ticker(self): allocations = [Allocation("GLD", 30), Allocation("GOOG", 70)] with self.assertRaises(ValueError) as context: Portfolio(allocations).process(self.df)
def test_partial(self): allocations = [Allocation("SPY", 30)] portfolio = Portfolio(allocations).process(self.df) self.assertEqual(portfolio.shape[0], self.df.shape[0]) self.assertEqual(portfolio.shape[1], 1)
def test_order(self): allocations_a = [Allocation("SPY", 30), Allocation("GOOG", 70)] portfolio_a = Portfolio(allocations_a).process(self.df) allocations_b = [Allocation("GOOG", 70), Allocation("SPY", 30)] portfolio_b = Portfolio(allocations_b).process(self.df) self.assertTrue(portfolio_a.equals(portfolio_b))