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