2016-07-10
I recently released a Haskell wrapper for the Yahoo Finance API. You can use it to get real-time stock quotes.
NOTE: Yahoo disabled the API this package was using, so this package has been updated to support a different API. The following code may not work. But check out the linked blog post for an example of how to use the updated package.
Yahoo provides three different APIs for obtaining different kinds of stock data, but this library currenly only supports the Yahoo Finance webservice API.
Usage
One function is provided in the Web.Yahoo.Finance.API.JSON
module to get stock quotes, getQuote
:
If you pass in a list of StockSymbol
s, it will return a Quotelist
. A StockSymbol
is just a newtype wrapper around Text
, and a QuoteList
is a newtype wrapper around a list of Quote
s.
Here is an example of how to use getQuote
:
import Control.Monad.Except (runExceptT)
import Control.Monad.Reader (runReaderT)
import Network.HTTP.Client.TLS (getGlobalManager) -- from package "http-client-tls"
import Servant.Client (ServantError) -- from package "servant-client"
import Web.Yahoo.Finance.API.JSON (QuoteList(unQuoteList), getQuote)
example :: IO ()
example = do
-- get a 'Manager' for performing the HTTPS connection.
(manager :: Manager) <- getGlobalManager
(eitherQuoteList :: Either ServantError QuoteList) <-
runExceptT $ runReaderT (getQuote ["VGTSX", "GOOG"]) manager
show $ unQuoteList <$> eitherQuoteList
This gets stock quotes for two different stocks: VGTSX (Vanguard Total International Stock Index Fund Investor Shares) and GOOG (Alphabet Inc Class C). Here is the result of the previous code:
Right
[ Quote
{ quoteChange = "0.050000"
, quoteChangePercent = "0.350141"
, quoteDayHigh = "0.000000"
, quoteDayLow = "0.000000"
, quoteIssuerName = "Vanguard Total Intl Stock Index Inv"
, quoteIssuerNameLang = "Vanguard Total Intl Stock Index Inv"
, quoteName = "Vanguard Total International St"
, quotePrice = "14.330000"
, quoteSymbol = "VGTSX"
, quoteTS = "1467413100"
, quoteType = "mutualfund"
, quoteUTCTime = 2016-07-01 22:45:00 UTC
, quoteVolume = "0"
, quoteYearHigh = "16.330000"
, quoteYearLow = "12.760000"
}
, Quote
{ quoteChange = "7.110046"
, quoteChangePercent = "1.027315"
, quoteDayHigh = "700.650024"
, quoteDayLow = "692.130127"
, quoteIssuerName = "Alphabet Inc."
, quoteIssuerNameLang = "Alphabet Inc."
, quoteName = "Alphabet Inc."
, quotePrice = "699.210022"
, quoteSymbol = "GOOG"
, quoteTS = "1467403200"
, quoteType = "equity"
, quoteUTCTime = 2016-07-01 20:00:00 UTC
, quoteVolume = "1344710"
, quoteYearHigh = "789.870000"
, quoteYearLow = "515.180000"
}
]
Conclusion
This library was made using servant-client. servant-client
makes it very easy to wrap APIs and provide a type-safe methods to access them.
If you're interested in accessing the other Yahoo Finance APIs, don't hesitate to submit an issue or send a pull-request.
tags: haskell