Skip to content

Instantly share code, notes, and snippets.

@miguelmota
Created April 19, 2018 18:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelmota/777270a7b1164d2350f68ef44f959cac to your computer and use it in GitHub Desktop.
Save miguelmota/777270a7b1164d2350f68ef44f959cac to your computer and use it in GitHub Desktop.
Golang Volume-Weighted Average Price (VWAP) https://play.golang.org/p/qa99s7q-8JN
package main
import (
"fmt"
)
func main() {
// [[volume, price], ...]
positions := [][]float64{
[]float64{2.5, 268},
[]float64{7.5, 269},
}
fmt.Println(vwap(positions...)) // 268.75
}
// vwap calculates the volume-weighted average price
// formula: sum(num shares * share price)/(total shares)
// input: [[volume, price], ...]
func vwap(positions ...[]float64) float64 {
var sum float64
for _, x := range positions {
sum = sum + x[0] * x[1]
}
var total float64
for _, x := range positions {
total = total + x[0]
}
return sum / total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment