portfolio

package module
v0.7.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Oct 12, 2024 License: MIT Imports: 20 Imported by: 1

README

Portfolio Go Reference Continuous Integration

This module contains quantitative portfolio analysis equations, portfolio back-testing, and asset data organization/cleaning data structures.

This module will continue to work on Windows, MacOS, and Linux.

While our main focus is our website. We value community engagement and will put effort into reviewing contributions and fixing issues on this repository.

Note, the API is not stable and will continue to change without notice until version v1.0

Getting Started

  1. Make sure you have a sufficiently new Go SDK installed installed (see the module file for the minimum required version)
  2. Get the package by running go get github.com/portfoliotree/portfolio in your terminal

DISCLAIMER

Please remember, investing carries inherent risks including but not limited to the potential loss of principal. Past performance is no guarantee of future results. The data, equations, and calculations in these docs and code are for informational purposes only and should not be considered financial advice. It is important to carefully consider your own financial situation before making any investment decisions. You should seek the advice of a licensed financial professional before making any investment decisions. You should seek code review of an experienced software developer before consulting this library (or any library that imports it) to inform investment decisions.

Documentation

Index

Examples

Constants

View Source
const (
	// ServerURLEnvironmentVariableName is used in testing to override the host
	//  and scheme for server calls.
	ServerURLEnvironmentVariableName = "PORTFOLIO_TREE_URL"

	// DefaultURL is the scheme and host for the API calls.
	DefaultURL = "https://portfoliotree.com"
)
View Source
const (
	ComponentTypeSecurity   = "Security"
	ComponentTypePortfolio  = "Portfolio"
	ComponentTypeEquity     = "Equity"
	ComponentTypeETF        = "ETF"
	ComponentTypeFactor     = "Factor"
	ComponentTypeMutualFund = "Mutual Fund"
)
View Source
const (
	ReturnsURLPath = "/api/returns"
)

Variables

This section is empty.

Functions

func ComponentTypes added in v0.6.0

func ComponentTypes() []string

Types

type Component

type Component struct {
	Type  string `yaml:"type,omitempty"  json:"type,omitempty"  bson:"type"`
	ID    string `yaml:"id,omitempty"    json:"id,omitempty"    bson:"id"`
	Label string `yaml:"label,omitempty" json:"label,omitempty" bson:"label"`
}

func ParseComponentsFromURL added in v0.4.0

func ParseComponentsFromURL(values url.Values, prefix string) ([]Component, error)

func (*Component) UnmarshalYAML

func (component *Component) UnmarshalYAML(value *yaml.Node) error

func (*Component) Validate

func (component *Component) Validate() error

type ComponentReturnsProvider

type ComponentReturnsProvider interface {
	ComponentReturnsList(ctx context.Context, component Component) (returns.List, error)
	ComponentReturnsTable(ctx context.Context, component ...Component) (returns.Table, error)
}

ComponentReturnsProvider is currently used for tests.

type Document added in v0.4.0

type Document struct {
	ID       Identifier    `json:"_id"      yaml:"_id"      bson:"_id"`
	Type     string        `json:"type"     yaml:"type"     bson:"type"`
	Metadata Metadata      `json:"metadata" yaml:"metadata" bson:"metadata"`
	Spec     Specification `json:"spec"     yaml:"spec"     bson:"spec"`
}

func ParseDocuments added in v0.4.0

func ParseDocuments(r io.Reader) ([]Document, error)

ParseDocuments decodes the contents of in to a list of Specifications The resulting Specification may have default values for unset fields.

func ParseOneDocument added in v0.4.0

func ParseOneDocument(in string) (Document, error)

ParseOneDocument decodes the contents of in to a Specification It supports a string containing YAML. The resulting Specification may have default values for unset fields.

func ParseSpecificationFile

func ParseSpecificationFile(specificationFilePath string) ([]Document, error)

ParseSpecificationFile opens a file and parses the contents into a Specification It supports YAML files at the moment but may support other encodings in the future.

func WalkDirectoryAndParseSpecificationFiles

func WalkDirectoryAndParseSpecificationFiles(dir fs.FS) ([]Document, error)

func (Document) Validate added in v0.4.0

func (d Document) Validate() error

type Identifier added in v0.4.0

type Identifier = primitive.ObjectID

type Metadata added in v0.4.0

type Metadata struct {
	Name        string      `json:"name,omitempty"        yaml:"name,omitempty"        bson:"name,omitempty"`
	Benchmark   Component   `json:"benchmark,omitempty"   yaml:"benchmark,omitempty"   bson:"benchmark,omitempty"`
	Description string      `json:"description,omitempty" yaml:"description,omitempty" bson:"description,omitempty"`
	Privacy     string      `json:"privacy,omitempty"     yaml:"privacy,omitempty"     bson:"privacy,omitempty"`
	Factors     []Component `json:"factors,omitempty"     yaml:"factors,omitempty"     bson:"factors,omitempty"`
}

type Policy

type Policy struct {
	RebalancingInterval backtestconfig.Interval `yaml:"rebalancing_interval,omitempty"                    bson:"rebalancing_interval"`

	Weights                  []float64               `yaml:"weights,omitempty"                            bson:"weights"`
	WeightsAlgorithm         string                  `yaml:"weights_algorithm,omitempty"                  bson:"weights_algorithm"`
	WeightsAlgorithmLookBack backtestconfig.Window   `yaml:"weights_algorithm_look_back_window,omitempty" bson:"weights_algorithm_look_back_window"`
	WeightsUpdatingInterval  backtestconfig.Interval `yaml:"weights_updating_interval,omitempty"          bson:"weights_updating_interval"`
}

type Specification

type Specification struct {
	Assets []Component `yaml:"assets"`
	Policy Policy      `yaml:"policy"`
}

Specification models a portfolio.

func (*Specification) Algorithm added in v0.4.0

func (pf *Specification) Algorithm(algorithmOptions []allocation.Algorithm) (allocation.Algorithm, error)

func (*Specification) AssetReturns

func (pf *Specification) AssetReturns(ctx context.Context) (returns.Table, error)

func (*Specification) Backtest

func (pf *Specification) Backtest(ctx context.Context, assets returns.Table, alg allocation.Algorithm) (backtest.Result, error)
Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/portfoliotree/portfolio"
)

func main() {
	// language=yaml
	portfolioSpecYAML := `---
type: Portfolio
metadata:
  name: 60/40
  benchmark: BIGPX
spec:
  assets: [ACWI, AGG]
  policy:
    weights: [60, 40]
    weights_algorithm: ConstantWeights
    rebalancing_interval: Quarterly
`

	pf, err := portfolio.ParseOneDocument(portfolioSpecYAML)
	if err != nil {
		panic(err)
	}

	ctx := context.Background()
	assets, err := pf.Spec.AssetReturns(ctx)
	if err != nil {
		panic(err)
	}
	result, err := pf.Spec.Backtest(ctx, assets, nil)
	if err != nil {
		panic(err)
	}

	portfolioReturns := result.Returns()
	fmt.Printf("Annualized Risk: %.2f%%\n", portfolioReturns.AnnualizedRisk()*100)
	fmt.Printf("Annualized Return: %.2f%%\n", portfolioReturns.AnnualizedArithmeticReturn()*100)
	fmt.Printf("Backtest start date: %s\n", result.ReturnsTable.FirstTime().Format(time.DateOnly))
	fmt.Printf("Backtest end date: %s\n", result.ReturnsTable.LastTime().Format(time.DateOnly))

}
Output:

Annualized Risk: 11.46%
Annualized Return: 5.10%
Backtest start date: 2008-03-31
Backtest end date: 2023-06-14

func (*Specification) BacktestWithStartAndEndTime

func (pf *Specification) BacktestWithStartAndEndTime(ctx context.Context, start, end time.Time, assets returns.Table, alg allocation.Algorithm) (backtest.Result, error)

func (*Specification) RemoveAsset

func (pf *Specification) RemoveAsset(index int) error

func (*Specification) Validate

func (pf *Specification) Validate() error

Validate does some simple validations. Server you should do additional validations.

Directories

Path Synopsis
Package backtest calculates portfolio returns and asset weights from historic asset returns.
Package backtest calculates portfolio returns and asset weights from historic asset returns.
Package calculate implements various finance equations used in the rest of the package.
Package calculate implements various finance equations used in the rest of the package.
internal
Package returns implements data structures and convenience methods for interacting with a list of returns or sets of date-aligned returns.
Package returns implements data structures and convenience methods for interacting with a list of returns or sets of date-aligned returns.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL