1:- module(croxstock, [crstock_stats/4]).

Stock market stats (just the DJIA opening) from crox.net

*/

    5:- use_module(library(http/http_client)).    6
    7:- dynamic stock_stat/4.
 crstock_stats(+Market:atom, +Stat:atom, +Date:term, -Value:float) is semidet
@Market must be djia @Stat must be opening @Date is of the form yy-mm-dd where mm, dd, and yy are ints @Value bound to the value of the DJIA opening for that day

fails if the dow wasn't open, or hasn't opened yet for that day, or the server's down.

Note - while this server is open, the owner notes:

No technical restrictions, users are expected to use common sense, when in doubt, ask.

*/

   25crstock_stats(djia, opening, YY - MM - DD, _) :-
   26	stock_stat(djia, opening, YY - MM - DD, error(Stamp)),
   27	get_time(Now),
   28	Now < Stamp + 900,
   29	!,fail.
   30crstock_stats(djia, opening, YY - MM - DD, Value) :-
   31	stock_stat(djia, opening, YY - MM - DD, Value),
   32	number(Value),
   33	!.
   34crstock_stats(djia, opening, YY - MM - DD, Value) :-
   35	debug(crstock, 'getting value for ~d ~d ~d', [YY, MM, DD]),
   36	(   YY < 100 -> YYYY is YY + 2000 ; YYYY = YY),
   37	format(atom(URL), 'http://geo.crox.net/djia/~d/~d/~d', [YYYY, MM, DD]),
   38	http_get(URL, Reply, []),
   39	atom_number(Reply, Value),  % fails if crox returns 'error'
   40	asserta(stock_stat(djia, opening, YY - MM - DD, Value)),!.
   41crstock_stats(djia, opening, YY - MM - DD, _) :-
   42	get_time(Stamp),
   43	asserta(stock_stat(djia, opening, YY - MM - DD, error(Stamp))),!,fail