Building a stock price script with Go

published February 26, 2022

I remember when Facebook first came out, there was this game you could play to paper trade the stock market. My friends and I would talk about the trades we'd made, why we picked different stocks, and where we thought the price action would go. I don't use Facebook anymore, and I'm a lot less wealthy in reality than I was in that paper trading game.

The stock market has always been an interesting thing to me. There are so many approaches to playing it, different strategies prescribed by varying parties, and myriad opinions on how best to leverage it so one can come out on top.

In thinking about what sort of project I wanted to attempt for February, I thought to myself: "Why not marry two of my interests in an effort to produce something I'd actually use?" With that, I chose to write a program that would return to me the price of a security, and potentially its percent change from previous close.

I chose to write the little program in Go, as it's a language I've been wanting to learn and this seemed like the perfect opportunity to get my feet wet.

In my initial research, I discovered an API called finhub.io which would suit my needs perfectly as it includes an endpoint for fetching a stock price. You can read the docs here

With this, my task really just became about wrapping this API call in a program that allowed me to pass in command line arguments. Go makes this relatively easy to do with packages like bufio and os:

reader := bufio.NewReader(os.Stdin)
fmt.Print("Enter ticker: ")
symbol, err := reader.ReadString('\n')

A gotcha I ran into was that reader.ReadString includes the delimiter passed to it. Had I read the docs on it more carefully, I would have realized this sooner and not spent an hour and a half debugging. Here is the documentation on ReadString

Once that issue had been resolved, it was pretty easy to finish the rest of the script. You can look at the thing here.

Overall, I do think I like Go as a programming language, though it's certainly one I need to spend more time in. Coming from Javascript, the idea of strong types is something I'm just not accustomed to. I like that Go is fairly opinionated in how to write Go code. A thing that's plagued Javascript for years is that there really haven't been many enforced or agreed upon standards for how people should write it. This has gotten better with things like Prettier, but it's a continual topic of discussion.

In conclusion, I really enjoyed learning more about Go and how it works, and will definitely be spending more time in it from here on out. I think the plan for this little stock price project is to continue fiddling with it, add more features to it, and potentially roll it into my daily workflow for trading.


← back