Created
January 5, 2023 20:29
-
-
Save 18182324/1f5d800ca42f0f9a56bd040c1f2fdb3f to your computer and use it in GitHub Desktop.
Tactical Asset Allocation Optimized
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include <vector> | |
#include <algorithm> | |
using namespace std; | |
// Define a class for a portfolio asset | |
class Asset { | |
public: | |
string name; | |
double price; | |
double weight; | |
Asset(string name, double price, double weight) : name(name), price(price), weight(weight) {} | |
}; | |
// Define a class for a portfolio | |
class Portfolio { | |
private: | |
vector<Asset> assets; | |
double total_value; | |
public: | |
Portfolio(vector<Asset> assets, double total_value) : assets(assets), total_value(total_value) {} | |
// Rebalance the portfolio to match the target asset weights | |
void rebalance() { | |
// Calculate the total value of the portfolio | |
total_value = 0; | |
for (auto& asset : assets) { | |
total_value += asset.price * asset.weight; | |
} | |
// Calculate the target value for each asset | |
for (auto& asset : assets) { | |
double target_value = total_value * asset.weight; | |
// Calculate the number of shares needed to achieve the target value | |
double shares = target_value / asset.price; | |
// Round the number of shares to the nearest whole number | |
long long int rounded_shares = round(shares); | |
// Update the asset weight based on the number of shares | |
asset.weight = rounded_shares / total_value; | |
} | |
} | |
}; | |
int main() { | |
// Create a portfolio with three assets | |
vector<Asset> assets = {{"Stock A", 100, 0.5}, {"Stock B", 50, 0.3}, {"Stock C", 200, 0.2}}; | |
Portfolio portfolio(assets, 1000); | |
// Rebalance the portfolio | |
portfolio.rebalance(); | |
// Print the resulting asset weights | |
for (auto& asset : portfolio.assets) { | |
cout << asset.name << ": " << asset.weight << endl; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment