Created
August 16, 2013 09:09
-
-
Save oz/6248414 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.
This file contains hidden or 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
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