Hi all!

I have been working on an implementation of MVO and the Markowitz portfolio theory similarly to MatPed's work here. My goal is to backtest an actual implementation including transaction costs.

There is a curious problem. I wrote a function current_position() to get the position in an Asset. Theoretically, open_position and oldLots[i] should be the same. However, as the check at the end of run() shows, this is not always the case.


Possible reasons:

1. current_position doesn't do what it is supposed to do. Should I use open_trades? Check if TradeIsOpen? Can someone confirm this function does what it is supposed to do? Is there a better way?

2. Zorro sells the positions from time to time. Why? According to which rule?

This would mean that the calls enterLong(newLot - oldLots[i]) and exitLong(0, 0, oldLots[i] - newLot) would need to be changed. According to my reading of the manual, they are correct (all defaults are 0).

(I am actually using a different asset list csv file, but this shouldn't matter at all.)


Currently, the backtesting doesn't work correctly, as Zorro reduces the positions and then the portfolio is not balanced according to the weights[]. Any help would be appreciated. I think this code is very close, but I guess I am missing some enterLong or exitLong magic.

Cheers

PS: I'd be happy to post improved versions if we can figure out the problem and if people are interested.

PPS: It seems as if the indentation gets messed up.



//////////////////////////////////////////////////////////////////////////////////////////////////////////////////

#define NN 50 // maximum number of assets

const var LEVERAGE = 4.0;
const bool verbose = FALSE;

function current_position(string asset_name) {
int sum = 0;
for (current_trades) {
if (TRUE) { // (TradeIsOpen) { //(0 == strcmp(Asset, asset_name)) {
sum += TradeLots;}}
return sum;}

function run() {
set(PRELOAD);
set(LOGFILE);
set(PLOTNOW);

AssetZone = WET;
NumYears = 7;
BarPeriod = 1440;
LookBack = 1 * 252; // 1 year
AssetList = "AssetsZ8.csv";

static int N = 0;
static string names[NN];
static int oldLots[NN];
vars returns[NN]; // series
var means[NN];
var covariances[NN][NN];
var weights[NN];

var totalCapital
= slider(1, 10000, 1000, 50000, "Capital", "Total capital to distribute");
var vFactor
= slider(2, 100, 0, 100, "Variance", "Variance factor, 0 = minimal variance, 100 = best variance");
var weightConstraintFactor
= slider(3, 50, 10, 90, "Max. w.", "maximum weight = (this value)/100");

if (is(INITRUN)) {
while (asset(loop(Assets))) {
names[N] = Asset;
printf("\nDownloading asset %d %s", N, names[N]);
assetHistory(Asset, FROM_YAHOO);
printf("\nAsset %d: name %s", N, names[N]);
oldLots[N] = 0;

if (++N >= NN) {
break;}}

printf("\n%d assets", N);}

int i;
for (i=0; i<N; i++) {
asset(names[i]);
returns[i] = series((priceClose(0)-priceClose(1)) / priceClose(1));
// printf("\nAsset %d %s: return %f", i, names[i], (returns[i])[0]);
}

if (1 == tdm() && !is(LOOKBACK)) {
int i, j;
for (i=0; i<N; i++) {
means[i] = Moment(returns[i], LookBack, 1);
for (j=0; j<N; j++) {
covariances[i*N + j] = Covariance(returns[i], returns[j], LookBack);}}

var bestVariance = markowitz(covariances, means, N, weightConstraintFactor/100.0);
var minVariance = markowitzReturn(0, 0);

markowitzReturn(weights, minVariance + (bestVariance-minVariance) * vFactor/100.0);

if (verbose) {
printf("\n\n%s", datetime());}
int i;
for (i=0; i<N; i++) {
asset(names[i]);
MarginCost = priceClose() / LEVERAGE;
int newLot = totalCapital * weights[i] / MarginCost;

if (verbose && (0 != oldLots[i] || 0 != newLot)) {
printf("\n%d %s: %d lots at %.2f$",
i, Asset, newLot, priceClose());
printf("\noldLots = %i, newLot = %i", oldLots[i], newLot);}

// if (verbose) {
// printf("\n%s: oldLots = %i, current_position = %i", Asset, oldLots[i], current_position(Asset));}

if (newLot > oldLots[i]) {
enterLong(newLot - oldLots[i]);}
if (newLot < oldLots[i]) {
exitLong(0, 0, oldLots[i] - newLot);}

oldLots[i] = newLot;}}

int i;
for (i=0; i<N; i++) {
asset(names[i]);
if (oldLots[i] != current_position(Asset)) {
printf("\n### %s: %s: oldLots = %i, current = %i", datetime(), Asset, oldLots[i], current_position(Asset));}}
}