Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- /*
- =================
- = DUAL MOMENTUM =
- =================
- Recommended Assets:
- - US: IVV or VOO or VTI
- - WORLD: VEU or VXUS or VEA (+CWI)
- - BONDS: AGG or BND or TLT
- - TBILLS: BIL or SHV (if IR near 0)
- */
- #include <profile.c>
- //Settings:
- #define DAYS 252 // comment out to use daily closing prices
- string asset_us = "IVV";
- string asset_world = "VEU";
- string asset_bonds = "AGG";
- string asset_tbills = "BIL";
- string current_position = "";
- // Function uset to exit the old position (if there's any) and enter the new one
- void changeAsset(string old_asset, string new_asset){
- // If there is no change skip the rest
- if(!strcmp(old_asset, new_asset)){
- print(TO_FILE, "No change in held asset (%s).", old_asset);
- return;
- }
- // Exit previous position
- print(TO_FILE, "Changing position from %s to %s.\n", old_asset, new_asset);
- if(strcmp(old_asset, "-")){
- asset(old_asset);
- exitLong();
- }
- // Enter new position
- asset(new_asset);
- enterLong();
- current_position = new_asset;
- }
- function run()
- {
- BarPeriod = 1440;
- LookBack = DAYS + 21;
- StartDate = 20070101;
- EndDate = 20180802;
- Verbose = 0;
- var return_us = 0;
- var return_world = 0;
- var return_tbills = 0;
- // If it is the last trading day of the month
- while(asset(loop(asset_us, asset_world, asset_tbills, 0)))
- {
- if(is(INITRUN)) {
- set(PRELOAD+LOGFILE);
- assetHistory(asset_us, FROM_AV);
- assetHistory(asset_world, FROM_AV);
- assetHistory(asset_bonds, FROM_AV);
- assetHistory(asset_tbills, FROM_AV);
- }
- // Calculate return always on the first trading day of the month
- if(tdm() == 1 && !is(LOOKBACK)){
- var *asset_return;
- if(!strcmp(Asset, asset_us)){
- asset_return = &return_us;
- }
- else if(!strcmp(Asset, asset_world)){
- asset_return = &return_world;
- }
- else if(!strcmp(Asset, asset_tbills)){
- asset_return = &return_tbills;
- }
- var old_price = priceClose(DAYS+1);
- *asset_return = (priceClose(1)-old_price)/old_price;
- print(TO_FILE, "\n%s return = (%f-%f)/%f = %f", Asset,
- priceClose(), old_price, old_price, *asset_return);
- }
- }
- // If it is the first trading day of the month and the returns were calculated
- if(tdm() == 1 && !is(LOOKBACK) && (abs(return_us) + abs(return_world) + abs(return_tbills) != 0)) {
- print(TO_FILE, "\nReturns (US, WORLD, TBILLS): %f, %f, %f\n",
- return_us, return_world, return_tbills);
- if(return_us - return_tbills >= 0){
- if(return_us > return_world)
- changeAsset(current_position, asset_us);
- else if(return_world - return_tbills >= 0)
- changeAsset(current_position, asset_world);
- else
- changeAsset(current_position, asset_bonds);
- }
- else {
- changeAsset(current_position, asset_bonds);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement