Created
April 19, 2018 18:29
-
-
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
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
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