1 |
#!/usr/local/bin/perl -w |
2 |
|
3 |
use LWP::UserAgent; |
4 |
use strict; |
5 |
use DBI; |
6 |
|
7 |
my $debug=0; |
8 |
|
9 |
$debug++ if (lc($ARGV[0]) eq "-d"); |
10 |
|
11 |
sub print_debug { |
12 |
return if (! $debug); |
13 |
open(DEBUG,">> debug") || warn "can't open debug file!"; |
14 |
print DEBUG "###",@_; |
15 |
print @_; |
16 |
close(DEBUG); |
17 |
} |
18 |
|
19 |
print_debug("debug level $debug"); |
20 |
|
21 |
my $dbh = DBI->connect("DBI:Pg:dbname=corp","","") || die $DBI::errstr; |
22 |
|
23 |
my $ua = new LWP::UserAgent; |
24 |
$ua->agent("pliva_harvester 0.0"); |
25 |
$ua->timeout(60); |
26 |
$ua->env_proxy(); |
27 |
$ua->proxy(['http', 'ftp'], 'http://proxy.pliva.hr:8080/'); |
28 |
|
29 |
my @val; |
30 |
|
31 |
my $close_time='21:21:21 CET'; |
32 |
|
33 |
sub insert { |
34 |
my ($date,$curr,$change,$change_pcnt,$high,$low,$open) = @val; |
35 |
my $sth = $dbh->prepare("select count(date) from stocks where date='$date'"); |
36 |
$sth->execute(); |
37 |
my ($nr) = $sth->fetchrow_array; |
38 |
if ($nr == 0) { |
39 |
my $sql="insert into stocks values ('$date','LSE',$curr,$change,$high,$low,$open)"; |
40 |
$sql=~s/,\+(\d)/,$1/g; # nuke + which pgsql doesn't like |
41 |
$dbh->do("$sql") || die "$sql\n".$DBI::errstr; |
42 |
print_debug("sql: $sql\n"); |
43 |
} else { |
44 |
print_debug("skip: $date\n"); |
45 |
} |
46 |
} |
47 |
|
48 |
my $req = HTTP::Request->new(GET =>'http://custom.marketwatch.com/custom/alliance/ftmw/invrel.asp?siteid=!plivadd-0773-4F6D-DHID-QN1112NFTD0X&symb=PLVD'); |
49 |
|
50 |
my $res = $ua->request($req); |
51 |
if ($res->is_success) { |
52 |
print_debug("html: ".$res->content."\n"); |
53 |
foreach (split(/[\n\r]+/, $res->content)) { |
54 |
chomp; |
55 |
print_debug("line: $_\n"); |
56 |
if (m,class="ft-quotedate">(\d+):(\d+) (\d+)/(\d+)/(\d+),i) { |
57 |
my ($h,$m,$dd,$mm,$yy) = ($1,$2,$3,$4,$5); |
58 |
my $date=($yy+2000)."-$mm-$dd"; |
59 |
my (undef,undef,$local_h) = localtime(time); |
60 |
$h += 12 if ($local_h - $h > 12); |
61 |
my $time="$h:$m"; |
62 |
print_debug("time: $time date: $date"); |
63 |
insert() if (@val); |
64 |
undef @val; |
65 |
push @val,"$date $time"; |
66 |
# $dbh->do("delete from stocks where date='$date $close_time'"); |
67 |
} |
68 |
if (m,class="ft-quote[^"]+".*<nobr>(\d+\.\d+)</nobr>,i) { |
69 |
push @val,$1; |
70 |
print_debug("val: $1"); |
71 |
} elsif (m,<nobr>([+-]*\d+\.\d+)</nobr>,i) { |
72 |
push @val,$1; |
73 |
print_debug("val: $1"); |
74 |
} |
75 |
|
76 |
} |
77 |
insert(); |
78 |
} else { |
79 |
warn "can't fetch stock data"; |
80 |
} |
81 |
|
82 |
$dbh->disconnect; |