Skip to content

Instantly share code, notes, and snippets.

@smerrill
Last active October 16, 2015 05:16
Show Gist options
  • Save smerrill/ccee0fa00aca9b6842f6 to your computer and use it in GitHub Desktop.
Save smerrill/ccee0fa00aca9b6842f6 to your computer and use it in GitHub Desktop.
defmodule Stocks.Mixfile do
use Mix.Project
def project do
[app: :stocks,
version: "0.0.1",
elixir: "~> 1.1",
build_embedded: Mix.env == :prod,
start_permanent: Mix.env == :prod,
deps: deps]
end
def application do
[applications: [:logger, :httpoison]]
end
defp deps do
[
{:httpoison, "~> 0.7.2"},
{:csv, "~> 1.2.0"}
]
end
end
HTTPoison.start
defmodule StocksTest do
def getClosingPrice(symbol, year) do
resp = HTTPoison.get!("http://ichart.finance.yahoo.com/table.csv?s=#{symbol}&a=11&b=01&c=#{year}&d=11&e=31&f=#{year}&g=m")
case resp.status_code do
200 -> {:ok, {symbol, parseBody(resp.body)}}
_ -> {:error, "Could not fetch the stock."}
end
end
def parseBody(body) do
body
|> String.split("\n") # Convert the string into a Stream for the CSV library to parse.
|> CSV.decode
|> Enum.fetch!(1)
|> Enum.fetch!(4)
|> String.to_float
end
# Use the map/reduce idiom to remove any errors.
def fetchMultiple(symbols, year) do
Enum.map(symbols, &getClosingPrice(&1, year))
|> Enum.reduce [], fn(f, acc) ->
case f do
{:ok, x} -> [x|acc]
{:error, _} -> acc
end
end
end
def getHighestStock(symbols, year) do
fetchMultiple(symbols, year)
|> Enum.max_by fn({_, x}) -> x end # Use pattern matching on the tuple to grab the second (float) element.
end
end
stocks = ['AAPL', 'GOOGL', 'IBM', 'ORCL', 'MSFT']
# Use pattern matching to grab the result out of the returned tuple.
{symbol, price} = StocksTest.getHighestStock(stocks, 2008)
IO.puts("The highest closing price was #{symbol} at $#{price}.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment