Gamestudio Links
Zorro Links
Newest Posts
Zorro Trader GPT
by TipmyPip. 04/27/24 13:50
Trading Journey
by 7th_zorro. 04/27/24 04:42
Help with plotting multiple ZigZag
by M_D. 04/26/24 20:03
Data from CSV not parsed correctly
by jcl. 04/26/24 11:18
M1 Oversampling
by jcl. 04/26/24 11:12
Why Zorro supports up to 72 cores?
by jcl. 04/26/24 11:09
Eigenwerbung
by jcl. 04/26/24 11:08
MT5 bridge not working on MT5 v. 5 build 4160
by EternallyCurious. 04/25/24 20:49
AUM Magazine
Latest Screens
The Bible Game
A psychological thriller game
SHADOW (2014)
DEAD TASTE
Who's Online Now
2 registered members (AndrewAMD, 1 invisible), 770 guests, and 6 spiders.
Key: Admin, Global Mod, Mod
Newest Members
wandaluciaia, Mega_Rod, EternallyCurious, howardR, 11honza11
19049 Registered Users
Previous Thread
Next Thread
Print Thread
Rate Thread
Markowitz Approach #487686
07/24/23 21:14
07/24/23 21:14
Joined: Jan 2020
Posts: 32
L
leohermoso Offline OP
Newbie
leohermoso  Offline OP
Newbie
L

Joined: Jan 2020
Posts: 32
Hello Traders!

I want to share a code I am using to trade stocks in Brazil. My next steps is to introduce a new component to hedge market risk from portfolio! Any feedback is welcome

Code
#include "pch.h"
#include <vector>
#include "zorro.h"
#include "Markowitz.h"

#define DAYS   252

using std::vector;






DLLFUNC void run()
{
	BarPeriod = 1440;
	LookBack = DAYS;
	NumYears = 10;
	Verbose = 0;
	Capital = 39806;
	set(PRELOAD + LOG + PLOTNOW);
	assetList("history\\bovespa_yahoo.csv", 0);
	static vector<double> Pesos;
	static vector<string> Ativos;



	bool rebalancear = tdm(0) == 5 && (month(0) == 1 || month(0) == 5 || month(0) == 9);



	if (rebalancear )
	{
		RecalcularPesos(0.0, &Pesos, &Ativos);


	}
	string _Asset;
	while (_Asset = (loop(Assets)))
	{
		if (is(INITRUN))
			assetHistory(_Asset, FROM_YAHOO);
		asset(_Asset);

		if (rebalancear && NumOpenLong > 0)
		{

			bool foraDaLista = true;

			if (std::find(Ativos.begin(), Ativos.end(), _Asset) != Ativos.end())
			{
				foraDaLista = false;

			}

			if (foraDaLista)
				exitLong();
		}


	}

	int ativoIndex = 0;
	if (rebalancear)
	{
		for (auto& ativo : Ativos) {

			asset(ativo);


			int quantidade = Quantidade(&Pesos, ativoIndex);


			if (NumOpenLong > 0)
			{

				int quantidades_diff = LotsPool - quantidade;
				if (quantidades_diff > 0)
				{
					exitLong(0, 0, quantidades_diff);
				}
				else if (quantidades_diff < 0)
				{
					enterLong(-quantidades_diff);

				}

			}
			else if (quantidade > 0)
			{

				enterLong(quantidade);
			}



			++ativoIndex;


		}
	}

	if (is(EXITRUN)) {
		int ativoIndex = 0;
		double total = 0;
		for (auto& ativo : Ativos) {

			asset(ativo);


			int quantidade = Quantidade(&Pesos, ativoIndex);
			if (quantidade > 0)
			{
				int lot_size = LotAmount;
				total += quantidade * lot_size * priceClose(0);
				printf("%s - %i acoes a %.5f\n", ativo, quantidade * lot_size,priceClose(0));

					}
			++ativoIndex;
		}
		printf("Total Alocado: %.2f\n", total);


	}





}


Code
#include "pch.h"
#include <vector>
#include "zorro.h"
#include "Markowitz.h"

void RecalcularPesos(double PesoMaximo, std::vector<double>* Pesos, std::vector<string>* Ativos)
{
	std::vector<double*> Retornos;
	std::vector<double> MediaRetornos;
	std::vector<double> Covariancias;
	SelecionarAtivos(Ativos);
	CalcRetornos(&Retornos, Ativos);
	Pesos->clear();

	int numAtivos = Ativos->size();
	int i, j;

	for (i = 0; i < numAtivos; ++i)
	{
		Pesos->push_back(0);
		MediaRetornos.push_back(Moment(Retornos.at(i), LookBack, 1));
		for (j = 0; j < numAtivos; ++j)
		{
			Covariancias.push_back(Covariance(Retornos.at(i), Retornos.at(j), LookBack));
		}

	}
	if (numAtivos)
	{
		double MelhorVariancia = markowitz(&(Covariancias)[0], &(MediaRetornos)[0], numAtivos, PesoMaximo);
		markowitzReturn(&(*(Pesos))[0], MelhorVariancia);
	}


}

void SelecionarAtivos(std::vector<string>* Ativos)
{

	std::vector<double*> Retornos;
	std::vector<double> retornos;
	std::vector<double> variancia;
	CalcRetornos(&Retornos);
	Ativos->clear();
	int numAtivos = Retornos.size();
	int i;
	for (i = 0; i < numAtivos; ++i)
	{

		retornos.push_back(Moment(Retornos.at(i), LookBack , 1));
		variancia.push_back(Moment(Retornos.at(i), LookBack,  2));

	}

	double retorno_medio = Moment(&(retornos)[0], numAtivos, 1);
	double variancia_media = Moment(&(variancia)[0], numAtivos, 1);
	double std_retornos = Moment(&(retornos)[0], numAtivos  , 2);

	for (i = 0; i < numAtivos; ++i)
	{
		if (retornos.at(i) > retorno_medio + std_retornos *2  && variancia.at(i) < variancia_media)
		{
			Ativos->push_back(Assets[i]);

		}
	}

}

int Quantidade(std::vector<double>* Pesos, int AtivoIndex)
{
	double capital = Capital * sqrt(1 + (ProfitClosed / Capital)) * OptimalFLong;
	return round(Pesos->at(AtivoIndex) * capital / priceClose(0) / LotAmount);
}



void CalcRetornos(std::vector<double*>* Retornos)
{
	int ativoIndex = 0;
	int dayIndex = 0;
	Retornos->clear();

	while (asset(loop(Assets)))
	{
		Retornos->push_back(new double[LookBack]);
		for (dayIndex = 0; dayIndex < LookBack; ++dayIndex)
		{
			Retornos->at(ativoIndex)[dayIndex] = (priceClose(dayIndex) - priceClose(dayIndex + 1)) / priceClose(dayIndex + 1);

		}
		++ativoIndex;



	}

}


void CalcRetornos(std::vector<double*>* Retornos, std::vector<string>* Ativos)
{
	int ativoIndex = 0;
	int dayIndex = 0;
	Retornos->clear();

	for (auto& ativo : *Ativos)
	{
		asset(ativo);
		Retornos->push_back(new double[LookBack]);
		for (dayIndex = 0; dayIndex < LookBack; ++dayIndex)
		{
			Retornos->at(ativoIndex)[dayIndex] = (priceClose(dayIndex) - priceClose(dayIndex + 1)) / priceClose(dayIndex + 1);

		}
		++ativoIndex;



	}

}



Best regards,

Leo Hermoso

Re: Markowitz Approach [Re: leohermoso] #487687
07/24/23 21:21
07/24/23 21:21
Joined: Jan 2020
Posts: 32
L
leohermoso Offline OP
Newbie
leohermoso  Offline OP
Newbie
L

Joined: Jan 2020
Posts: 32
Attaching the bovespa_yahoo assetlist

Attached Files
bovespa_yahoo.csv (2 downloads)

Moderated by  Petra 

Gamestudio download | chip programmers | Zorro platform | shop | Data Protection Policy

oP group Germany GmbH | Birkenstr. 25-27 | 63549 Ronneburg / Germany | info (at) opgroup.de

Powered by UBB.threads™ PHP Forum Software 7.7.1