Skip to content

Commit

Permalink
feat: add assertions to weight functions
Browse files Browse the repository at this point in the history
  • Loading branch information
crhntr committed Jul 17, 2024
1 parent 04c5f69 commit c9ff8ad
Showing 1 changed file with 24 additions and 0 deletions.
24 changes: 24 additions & 0 deletions calculate/weights.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,10 @@ func EqualWeights(ws []float64) {
}

func InverseVarianceWeights(ws []float64, vols []float64) {
if len(ws) != len(vols) {
panic("length of weights and volatilizes must be equal")
}

inverseVars := make([]float64, len(vols))
for i := range vols {
inverseVars[i] = 1.0 / Variance(vols[i])
Expand All @@ -28,6 +32,18 @@ func InverseVarianceWeights(ws []float64, vols []float64) {
}

func EqualRiskContributionWeights(ctx context.Context, ws []float64, vols []float64, correlations [][]float64) error {
if len(ws) != len(vols) {
panic("length of weights and volatilizes must be equal")
}
if len(ws) != len(correlations) {
panic("length of weights and correlations must be equal")
}
for _, row := range correlations {
if len(row) != len(correlations) {
panic("correlations must be a square matrix")
}
}

target := 1.0 / float64(len(vols))
return optWeights(ctx, ws, func(ws []float64) float64 {
riskWeights := RiskWeights(PortfolioVolatility(vols, ws, correlations))
Expand All @@ -40,6 +56,10 @@ func EqualRiskContributionWeights(ctx context.Context, ws []float64, vols []floa
}

func EqualInverseVolatilityWeights(ws []float64, vols []float64) {
if len(ws) != len(vols) {
panic("length of weights and volatilizes must be equal")
}

inverseVols := make([]float64, len(vols))
for i := range vols {
inverseVols[i] = 1.0 / vols[i]
Expand All @@ -56,6 +76,10 @@ func EqualInverseVolatilityWeights(ws []float64, vols []float64) {
}

func EqualVolatilityWeights(ws []float64, vols []float64) {
if len(ws) != len(vols) {
panic("length of weights and volatilizes must be equal")
}

sum := 0.0
for i := range vols {
sum += vols[i]
Expand Down

0 comments on commit c9ff8ad

Please sign in to comment.