Portfolio Index
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © CatalaniCD

//@version=4
study("Portfolio Index")
// input date
date = input(title = "Initial Date", type = input.time, defval=timestamp("01 Jan 2020 00:00 +0000"))
// input equity
equity = input(title = 'Equity', type = input.integer, defval = 10000, minval = 1)
// select portfolio components
// input portfolio tickers
// input percent
asset_0 = input(title = 'Portfolio 0', type = input.symbol, defval = "TSLA")
pct_0 = input(title = '%Holding', type = input.float, defval = 0.33)

asset_1 = input(title = 'Portfolio 1', type = input.symbol, defval = "AAPL")
pct_1 = input(title = '%Holding', type = input.float, defval = 0.33)

asset_2 = input(title = 'Portfolio 2', type = input.symbol, defval = "MSFT")
pct_2 = input(title = '%Holding', type = input.float, defval = 0.33)

// load prices
price_x = security(syminfo.ticker, resolution = timeframe.period, expression = close)
price_0 = security(symbol = asset_0, resolution = timeframe.period, expression = close)
price_1 = security(symbol = asset_1, resolution = timeframe.period, expression = close)
price_2 = security(symbol = asset_2, resolution = timeframe.period, expression = close)

log_returns(price) =>
    change(log(price))

sim_returns(price) =>
    exp(cum(change(log(price), 1)))

if time >= date
    price_x := sim_returns(price_x) * equity
    price_0 := sim_returns(price_0) * equity * pct_0
    price_1 := sim_returns(price_1) * equity * pct_1
    price_2 := sim_returns(price_2) * equity * pct_2
    
portfolio = array.avg(array.from(log_returns(price_0), log_returns(price_1), log_returns(price_2)))

index = cum(log_returns(price_x)) - cum(portfolio)

hline(price = 0.0, color = color.white)
plot(index)