Skip to content

Instantly share code, notes, and snippets.

@oz oz/stock.hs
Created Aug 16, 2013

Embed
What would you like to do?
Playing with Yahoo's stock API in Haskell, use this little program to quickly check stock prices, or change currencies.
import Prelude
import System.Environment
import Network.HTTP
import Control.Monad
showUsage :: IO ()
showUsage = do
putStrLn "Usage: stock <options...>\n"
putStrLn " - get a quote: stock <symbol>"
putStrLn " - change money: stock <from> <to> <amount>"
baseUrl :: String
baseUrl = "http://download.finance.yahoo.com/d/quotes.csv"
-- See http://www.gummy-stuff.org/Yahoo-data.htm
buildStockUrl :: String -> String
buildStockUrl symbol = baseUrl ++ "?s=" ++ (urlEncode symbol) ++ "&f=a"
fetchStockPrice :: String -> IO (Float)
fetchStockPrice url = do
rsp <- Network.HTTP.simpleHTTP (getRequest url)
fmap (read . take 256) (getResponseBody rsp) :: IO (Float)
getQuote :: [String] -> IO (Float)
getQuote (symbol:[]) = fetchStockPrice $ buildStockUrl symbol
getQuote (from:to:x:[]) = do
price <- fetchStockPrice url
return (price * amount)
where
url = buildStockUrl $ from ++ to ++ "=X"
amount = read x :: Float
main :: IO ()
main = do
args <- getArgs
if length args == 1 || length args == 3
then getQuote args >>= print
else showUsage
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.