Skip to content

Instantly share code, notes, and snippets.

@gingerhot
Forked from oz/stock.hs
Created December 13, 2016 03:08
Show Gist options
  • Save gingerhot/4600060c2aed352d34347d06ff0849bb to your computer and use it in GitHub Desktop.
Save gingerhot/4600060c2aed352d34347d06ff0849bb to your computer and use it in GitHub Desktop.
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