GeniusTrader/DB/CSV.pm untested

filter: Statementstmt 0.0% 0 / 309 Branchbran 0.0% 0 / 98 Conditioncond 0.0% 0 / 44 MC/DCmcdc 0.0% 0 / 23 Subroutinesub 0.0% 0 / 35 Podpod 0.0% 0 / 23 totaltotal 0.0% 0 / 532 CC 50 SCAR 41.6
CC
50
Cov
0%
merge_from_source
272.0
update_from_source
56.0
edit
30.0
CRAP 64.0
1 package Finance::GeniusTrader::DB::CSV;
2  
3 # Copyright 2003 Oliver Bossert
4 # This file is distributed under the terms of the General Public License
5 # version 2 or (at your option) any later version.
6  
7 use strict;
8 use vars qw(@ISA);
9  
10 use Finance::GeniusTrader::DB;
11 use Finance::GeniusTrader::Prices;
12 use Finance::GeniusTrader::Conf;
13 use Finance::GeniusTrader::DateTime;
14 use Time::Local;
15  
16 use DBI;
17  
18 @ISA = qw(Finance::GeniusTrader::DB);
19  
20 =head1 NAME
21  
22 Finance::GeniusTrader::DB::CSV - Access to a text files by DBI::CSV
23  
24 =head1 DESCRIPTION
25  
26 This module handels the access to textfiles by using the
27 DBI:File-module.
28  
29 =head2 Configuration
30  
31 You can put some configuration items in ~/.gt/options to indicate where
32 the database is.
33  
34 =over
35  
36 =item DB::csv::database : the type of the database ("CSV" by default)
37  
38 =item DB::csv::dbname : the name of the database ("cours" by default)
39  
40 =item DB::csv::dbhost : the host of the database ("" = localhost by default)
41  
42 =item DB::csv::dbuser : the user account on the database
43  
44 =item DB::csv::dbpasswd : the password of the user account
45  
46 =back
47  
48 =head2 Functions
49  
50 =over
51  
52 =item C<< Finance::GeniusTrader::DB::csv->new() >>
53  
54 Creates a new database-object
55  
56 =cut
57  
58 sub new {
59 my $type = shift;
60 my $class = ref($type) || $type;
61  
62 Finance::GeniusTrader::Conf::default("DB::csv::database", "CSV");
63 Finance::GeniusTrader::Conf::default("DB::csv::dbname", "/home/olf/ablage/private/finalize/GT/database");
64 Finance::GeniusTrader::Conf::default("DB::csv::dbhost", ""); #aka localhost
65 Finance::GeniusTrader::Conf::default("DB::csv::dbuser", ""); #aka current user
66 Finance::GeniusTrader::Conf::default("DB::csv::dbpasswd", ""); #aka user is already identified
67  
68 my $self = { 'database' => Finance::GeniusTrader::Conf::get("DB::csv::database"),
69 'dbname' => Finance::GeniusTrader::Conf::get("DB::csv::dbname"),
70 'dbhost' => Finance::GeniusTrader::Conf::get("DB::csv::dbhost"),
71 'dbuser' => Finance::GeniusTrader::Conf::get("DB::csv::dbuser"),
72 'dbpasswd' => Finance::GeniusTrader::Conf::get("DB::csv::dbpasswd"),
73 @_
74 };
75  
76 if ( $self->{'database'} eq "CSV" ) {
77 Finance::GeniusTrader::Conf::default("DB::csv::connectstring", "DBI:CSV:f_dir=" . $self->{'dbname'} . ";csv_sep_char=\t" );
78 } else {
79 my $addstring = "";
80 if ($self->{'dbhost'}) {
81 $addstring .= ";host=" . $self->{'dbhost'};
82 }
83 Finance::GeniusTrader::Conf::default("DB::csv::connectstring", "DBI:" . $self->{'database'} .
84 ":database=" . $self->{'dbname'} . $addstring );
85 }
86
87 my $connect_string = Finance::GeniusTrader::Conf::get("DB::csv::connectstring");
88 $self->{'_dbh'} = DBI->connect($connect_string, $self->{'dbuser'},
89 $self->{'dbpasswd'}) or die "Couldn't connect to database !\n";
90  
91 return bless $self, $class;
92 }
93  
94 =item C<< $db->disconnect >>
95  
96 Disconnects from the database.
97  
98 =cut
99 sub disconnect {
100 my $self = shift;
101 $self->{'_dbh'}->disconnect;
102 delete $self->{'prices'};
103 delete $self->{'dates'};
104 }
105  
106  
107 =item C<< $db->init_table($code) >>
108  
109 Creates the table of stock $code.
110  
111 =cut
112 sub init_table {
113 my ($self, $code) = @_;
114  
115 # If we use a CVS-Database, create the directory
116 if ( $self->{'database'} eq "CSV" ) {
117 my $DB_DIR = $self->{'dbname'};
118 if (! -d $DB_DIR) {
119 mkdir($DB_DIR, 0755) ||
120 die "Could not create directory $DB_DIR.";
121 }
122 }
123  
124 $self->{'_dbh'}->do("
125 CREATE TABLE PRICES_$code (
126 open REAL,
127 close REAL,
128 high REAL,
129 low REAL,
130 volume REAL,
131 date CHAR(10)
132 )") or die "Could not create table PRICES_$code.";
133 }
134  
135 =item C<< $db->init_add_info() >>
136  
137 Creates the addinfo-table.
138  
139 =cut
140 sub init_add_info {
141 my $self = shift;
142  
143 # If we use a CVS-Database, create the directory
144 if ( $self->{'database'} eq "CSV" ) {
145 my $DB_DIR = $self->{'dbname'};
146 if (! -d $DB_DIR) {
147 mkdir($DB_DIR, 0755) ||
148 die "Could not create directory $DB_DIR.";
149 }
150 }
151  
152 $self->{'_dbh'}->do(<<'EOT') or die "Could not create table addinfo.";
153 CREATE TABLE addinfo (
154 info CHAR(60),
155 code CHAR(15),
156 date CHAR(10),
157 value CHAR(100)
158 )
159 EOT
160 }
161  
162 =item C<< $db->init_add_info() >>
163  
164 Creates the shares-table.
165  
166 =cut
167 sub init_shares {
168 my $self = shift;
169  
170 # If we use a CVS-Database, create the directory
171 if ( $self->{'database'} eq "CSV" ) {
172 my $DB_DIR = $self->{'dbname'};
173 if (! -d $DB_DIR) {
174 mkdir($DB_DIR, 0755) ||
175 die "Could not create directory $DB_DIR.";
176 }
177 }
178  
179 $self->{'_dbh'}->do(<<'EOT') or die "Could not create table addinfo.";
180 CREATE TABLE shares (
181 name CHAR(100),
182 code CHAR(15)
183 )
184 EOT
185 }
186  
187 =item C<< $db->get_prices($code) >>
188  
189 Returns a Finance::GeniusTrader::Prices object containing all known prices for the symbol $code.
190  
191 =cut
192 sub get_prices {
193 return get_last_prices(@_, -1);
194 }
195  
196 =item C<< $db->get_last_prices($code, $limit) >>
197  
198 Returns a Finance::GeniusTrader::Prices object containing the $limit last known prices for
199 the symbol $code.
200  
201 =cut
202 sub get_last_prices {
203 my ($self, $code, $limit) = @_;
204  
205 my $q = Finance::GeniusTrader::Prices->new($limit);
206 $q->set_timeframe($DAY);
207  
208 my $sql = qq{ SELECT open, high, low, close, volume, date
209 FROM PRICES_$code ORDER BY date DESC };
210 if ($limit > 0) {
211 $sql .= "LIMIT $limit";
212 }
213  
214 my $ref = $self->{'_dbh'}->selectall_arrayref( $sql )
215 or die $self->{'_dbh'}->errstr();
216  
217 my @prices = @{$ref};
218 @prices = sort { $b->[5] cmp $a->[5] } @prices;
219  
220 my $res;
221 foreach $res (reverse @prices)
222 {
223 $q->add_prices($res);
224 }
225 return $q;
226 }
227  
228  
229 # Now some basic management functions
230 # ###################################
231  
232 =item C<< $db->insert($code) >>
233  
234 Creates the table of stock $code.
235  
236 =cut
237 sub insert {
238 my $self = shift;
239 my %values = @_;
240 no strict "refs";
241  
242 # Exit if the Primary Key is not defined
243 my @INDEX_FIELDS = qw/date/;
244 foreach my $f (@INDEX_FIELDS) {
245 return if ( !defined($values{$f}) );
246 }
247  
248 my @names = ();
249 my @vals = ();
250 while ( my ($key, $value) = each %values) {
251 if ($key ne 'code') {
252 push @names, $key;
253 push @vals, $value;
254 }
255 }
256  
257 for (my $i=0; $i<=$#vals; $i++) {
258 return if ( $vals[$i] !~ /^[\d\.-]+$/ ); # Somtimes a "n/a" occurs
259 $vals[$i] = "'" . $vals[$i] . "'";
260 }
261  
262 $self->{'_dbh'}->do( "INSERT INTO PRICES_" .$values{'code'} . " (" . join(", ", @names) .
263 ") VALUES (" . join(", ", @vals) . ")" )
264 or warn $self->{'_dbh'}->errstr();
265  
266 }
267  
268 =item C<< $db->get( parameters ) >>
269  
270 Get the datasets where all the parameters match
271  
272 =cut
273 sub get {
274 my $self = shift;
275 no strict "refs";
276 my %values = @_;
277  
278 my @wheres = ();
279 while ( my ($key, $value) = each %values) {
280 push @wheres, "$key = '$value'" if ($key ne 'code');
281 }
282 my $where = join(" AND ", @wheres);
283 $where = "WHERE " . $where if ( $where ne "" );
284  
285 my $ref = $self->{'_dbh'}->selectall_arrayref( "SELECT open, high, low, close, volume, date FROM PRICES_" .$values{'code'} . " " . $where );
286 # or die $self->{'_dbh'}->errstr();
287  
288 return @{$ref};
289 }
290  
291 =item C<< $db->available( $code, $date ) >>
292  
293 Returns 1 if a dataset for the corresponding day is available.
294  
295 =cut
296 sub available {
297 my ($self, $code, $date) = @_;
298 my @data = $self->get( "date" => $date, "code" => $code );
299 my $res = ( $#data >= 0 ) ? 1 : 0;
300 return $res;
301 }
302  
303 =item C<< $db->get( parameters ) >>
304  
305 Delete the datasets where all the parameters match
306  
307 =cut
308 sub del {
309 my $self = shift;
310 my %values = @_;
311 no strict "refs";
312  
313 my @wheres = ();
314 while ( my ($key, $value) = each %values) {
315 push @wheres, "$key = '$value'" if ($key ne 'code');
316 }
317 my $where = join(" AND ", @wheres);
318 $where = "WHERE " . $where if ( $where ne "" );
319  
320 $self->{'_dbh'}->do( "DELETE FROM PRICES_" .$values{'code'} . " " . $where )
321 or die $self->{'_dbh'}->errstr();
322  
323 }
324  
325 =item C<< $db->edit( parameters ) >>
326  
327 Edit the dataset where the date and the code matches
328  
329 =cut
330 sub edit {
331 my $self = shift;
332 my %values = @_;
333 no strict "refs";
334 my @INDEX_FIELDS = qw/date/;
335  
336 # Define what field to update
337 my @wheres = ();
338 foreach my $f (@INDEX_FIELDS) {
339 if ( defined($values{$f}) ) {
340 push @wheres, "$f = '" . $values{$f} . "'";
341 delete($values{$f});
342 }
343 }
344 my $where = join(" AND ", @wheres);
345 $where = "WHERE " . $where if ( $where ne "" );
346  
347 return if ( $where eq "" );
348  
349 # What is to be updated?
350 my @sets = ();
351 while ( my ($key, $value) = each %values) {
352 push @sets, "$key = '$value' " if ($key ne 'code');
353 }
354 my $set = "SET " . join(", ", @sets);
355  
356 my $ref = $self->{'_dbh'}->do( "UPDATE PRICES_" .$values{'code'} . " " . $set . $where )
357 or die $self->{'_dbh'}->errstr();
358  
359 }
360  
361 =item C<< $db->table_exists($code) >>
362  
363 Test if a table for stock $code already exists
364  
365 =cut
366 sub table_exists {
367 my $self = shift;
368 my $code = shift;
369 my $test = $self->get( "code" => $code );
370 my $ret = 0;
371 $ret = 1 if ( defined($test) );
372 return ( $ret );
373 }
374  
375  
376 # Management of shares (code, name)
377 # #################################
378  
379 =item C<< $db->get_db_name($code) >>
380  
381 Returns the name of the stock designated by $code.
382  
383 =cut
384 sub get_db_name {
385 my ($self, $code) = @_;
386 my $sql = "SELECT name FROM shares WHERE code = '$code'";
387 my $sth = $self->{'_dbh'}->prepare($sql) || die $self->{'_dbh'}->errstr;
388 $sth->execute(); # || warn $self->{'_dbh'}->errstr;
389 my $res = $sth->fetchrow_arrayref;
390 $res->[0] =~ s/^\s*//s;
391 $res->[0] =~ s/\s*$//s;
392 return $res->[0];
393 }
394  
395 =item C<< $db->get_db_code($name) >>
396  
397 Returns the code of the stock designated by $name.
398  
399 =cut
400 sub get_db_code {
401 my ($self, $name) = @_;
402 my $sql = "SELECT code, name FROM shares";
403 my $ref = $self->{'_dbh'}->selectall_arrayref( $sql )
404 or die $self->{'_dbh'}->errstr();
405 my @codes = @{$ref};
406 my $res = $name;
407 foreach my $code (@codes)
408 {
409 $res = $code->[0] if ($code->[1] =~ /$name/i);
410 }
411 $res =~ s/^\s*//s;
412 $res =~ s/\s*$//s;
413 return $res;
414 }
415  
416  
417 # Management of additional Informations
418 # #####################################
419  
420 =item C<< $db->get_add_info($code,$date) >>
421  
422 Returns an additional information about the stock
423  
424 =cut
425 sub get_add_info {
426 my ($self, $info, $code, $date) = @_;
427  
428 my $sql = "SELECT value FROM addinfo WHERE info = '$info' AND code = '$code'";
429 $sql .= " AND date = '$date'" if (defined($date));
430  
431 my $sth = $self->{'_dbh'}->prepare($sql) || die $self->{'_dbh'}->errstr;
432 $sth->execute() || die $self->{'_dbh'}->errstr;
433 my $res = $sth->fetchrow_arrayref;
434 $res->[0] =~ s/^\s*//;
435 $res->[0] =~ s/\s*$//;
436 return $res->[0];
437 }
438  
439 =item C<< $db->get_add_info($code,$date) >>
440  
441 Returns an additional information about the stock
442  
443 =cut
444 sub set_db_name {
445 my ($self, $code, $name) = @_;
446  
447 # Check if the dataset is available
448 my $res = $self->get_db_name($code);
449  
450 if ( defined($res) ) {
451 my $sql = "UPDATE shares SET name = '$name' WHERE code = '$code'";
452 my $sth = $self->{'_dbh'}->do($sql) || die $self->{'_dbh'}->errstr;
453 } else {
454 my $sql = "INSERT INTO shares (code, name) VALUES ('$code', '$name')";
455 my $sth = $self->{'_dbh'}->do($sql) || die $self->{'_dbh'}->errstr;
456 }
457 }
458  
459  
460 =item C<< $db->set_add_info($value, $info, $code, $date) >>
461  
462 Set an additional information about the stock
463  
464 =cut
465 sub set_add_info {
466 my ($self, $value, $info, $code, $date) = @_;
467  
468 # Check if the dataset is available
469 my $res = $self->get_add_info($info, $code, $date);
470  
471 if ( defined($res) ) {
472 my $sql = "UPDATE addinfo SET value = '$value' WHERE info = '$info' AND code = '$code'";
473 $sql .= " AND date = '$date'" if (defined($date));
474 my $sth = $self->{'_dbh'}->do($sql) || die $self->{'_dbh'}->errstr;
475 } else {
476 $date = "-" if ( !defined($date) );
477 my $sql = "INSERT INTO addinfo (info, code, date, value) VALUES ('$info', '$code', '$date', '$value')";
478 my $sth = $self->{'_dbh'}->do($sql) || die $self->{'_dbh'}->errstr;
479 }
480  
481 }
482  
483  
484 # Communication with other databases/sources
485 # ##########################################
486  
487 =item C<< $db->update_from_source($code) >>
488  
489 This function is getting the actual information from the web.
490  
491 =cut
492 sub update_from_source {
493 my $self = shift;
494 my ($source, $code) = @_;
495  
496 my $newtable = 0;
497 if ( !$self->table_exists( $code ) ) {
498 $self->init_table( $code );
499 $newtable = 1;
500 }
501  
502 my ($sec, $min, $hour, $d, $m, $y, $wd, $yd) = localtime;
503 my $today = sprintf("%04d-%02d-%02d", $y + 1900, $m + 1, $d);
504  
505 # Return if the current day is already available
506 return if ( $self->available($code, $today) == 1 );
507  
508 # Check for the update-cycle
509 Finance::GeniusTrader::Conf::default("DB::Source::$source::UpdateCycle", "12"); # 12h
510 my $update = Finance::GeniusTrader::Conf::get("DB::Source::$source::UpdateCycle");
511 my $lastupdate = $self->get_add_info( "Update_$source", $code );
512 my $now = timelocal($sec, $min, $hour, $d, $m, $y);
513 $update = $update * 60 * 60; # --> seconds
514  
515 print ">>" . $lastupdate . "<<\n";
516  
517 if ( $lastupdate eq "" || ( $lastupdate + $update < $now ) ) {
518 my $prices = $self->get_last_prices($code, 1);
519 my $latest_date = $prices->find_nearest_date($today);
520  
521 # return if ( !defined($prices->at_date($latest_date)) );
522 my $last_date;
523 if ( !defined($prices->at_date($latest_date)) ) {
524 $last_date = "1960-01-01";
525 } else {
526 $last_date = $prices->at_date($latest_date)->[$DATE];
527 }
528 # Decrement the month
529 my @last_dat = split /-/, $last_date;
530 #$last_dat[1]--;
531 $last_date = join("-", @last_dat);
532 print $last_date . " to " . $today . "\n";
533 my @data = ();
534 my $getstring = "use Finance::GeniusTrader::DB::$source; my \$s = Finance::GeniusTrader::DB::$source->new();
535 \@data = \$s->get_price_interval('$code', '$last_date', '$today');";
536  
537 eval $getstring;
538 if ($@) {
539 warn "$@ : $getstring";
540 return;
541 }
542
543 for (my $d=0; $d <= $#data; $d++) {
544  
545 if ( $self->available($code, $data[$d][5]) == 1 ) {
546 $self->edit( code => $code,
547 date => $data[$d][5],
548 open => $data[$d][0],
549 high => $data[$d][1],
550 low => $data[$d][2],
551 close => $data[$d][3],
552 volume => $data[$d][4]
553 );
554 } else {
555 $self->insert( code => $code,
556 date => $data[$d][5],
557 open => $data[$d][0],
558 high => $data[$d][1],
559 low => $data[$d][2],
560 close => $data[$d][3],
561 volume => $data[$d][4]
562 );
563 }
564 }
565  
566 }
567  
568 # New update-information
569 $self->set_add_info("$now" ,"Update_$source", $code);
570  
571 }
572  
573 =item C<< $db->get_all_prices($code) >>
574  
575 Dummy function. Need to define a clear interface for the exchange.
576  
577 =cut
578 sub get_all_prices {
579 my $self = shift;
580 my $code = shift;
581 return ( $self->get( code => $code) );
582 }
583  
584 =item C<< $db->merge_from_source($source, $code) >>
585  
586 Merges the content of an other database/source into the current db.
587 This needs to be updated with a "ranking" algorithm.
588  
589 =cut
590 sub merge_from_source {
591 my $self = shift;
592 my ($source, $code) = @_;
593  
594 # Create the table ?!?!
595 $self->init_table( $code ) if ($self->table_exists("$code") == 0);
596  
597 my @data = ();
598 my $getstring = "use Finance::GeniusTrader::DB::$source; my \$s = Finance::GeniusTrader::DB::$source->new();
599 \@data = \$s->get_all_prices('$code');\$s->disconnect();";
600  
601 eval $getstring;
602 if ($@) {
603 warn "$@ : $getstring";
604 return;
605 }
606  
607 for (my $d=0; $d <= $#data; $d++) {
608  
609 my ($open, $high, $low, $close, $volume, $date) = ($data[$d][0], $data[$d][1], $data[$d][2], $data[$d][3], $data[$d][4], $data[$d][5]);
610  
611 #print $date . "\n";
612 #print "NEW: " . join( "\t", ($open, $high, $low, $close, $volume, $date) ) . "\n";
613  
614 my @data2 = ( [] );
615 if ( $self->available($code, $date) == 1 ) {
616  
617 @data2 = $self->get( code => $code, date => $date );
618 #print "OLD: " . join( "\t", @{$data2[0]} ) . "\n";
619  
620 if ( $open != $data2[0][0] ) {
621 if ( $open - $data2[0][0] <= 0.01 ) {
622 $open = $data2[0][0];
623 } else {
624 print STDERR " $code $date differs : OPEN $open != " . $data2[0][0] . "\n"
625 }
626 }
627 if ( $high != $data2[0][1] ) {
628 if ( $high - $data2[0][1] <= 0.01 ) {
629 $high = $data2[0][1];
630 } else {
631 print STDERR " $code $date differs : HIGH $high != " . $data2[0][1] . "\n"
632 }
633 }
634 if ( $low != $data2[0][2] ) {
635 if ( $low - $data2[0][2] <= 0.01 ) {
636 $low = $data2[0][2];
637 } else {
638 print STDERR " $code $date differs : LOW $low != " . $data2[0][2] . "\n"
639 }
640 }
641 if ( $close != $data2[0][3] ) {
642 if ( $close - $data2[0][3] <= 0.01 ) {
643 $close = $data2[0][3];
644 } else {
645 print STDERR " $code $date differs : CLOSE $close != " . $data2[0][3] . "\n"
646 }
647 }
648 if ( $volume != $data2[0][4] ) {
649 if ( $volume == 0 ) {
650 $volume = $data2[0][4];
651 } elsif ( $data2[0][4] == 0 ) {
652 } else {
653 print STDERR " $code $date differs : VOLUME $volume != " . $data2[0][4] . "\n" unless (abs($volume != $data2[0][4]) <= 1);
654 }
655 }
656  
657 $self->edit( code => $code,
658 date => $date,
659 open => $open,
660 high => $high,
661 low => $low,
662 close => $close,
663 volume => $volume
664 );
665  
666 } else {
667 $self->insert( code => $code,
668 date => $date,
669 open => $open,
670 high => $high,
671 low => $low,
672 close => $close,
673 volume => $volume
674 );
675  
676 }
677  
678 ##print "x" x 60 . "\n";
679  
680 }
681  
682 }
683  
684 =item C<< $db->merge_all_from_source($source) >>
685  
686 Merges the content of all shares in an other database/source into the current db.
687  
688 =cut
689 sub merge_all_from_source {
690 my $self = shift;
691 my ($source) = @_;
692 my $ref = $self->{'_dbh'}->selectall_arrayref( "SELECT code FROM shares" );
693 my @codes = @{$ref};
694 for (my $i=0; $i<=$#codes; $i++) {
695 $codes[$i][0] =~ s/ *$//;
696 print $codes[$i][0] . "\n";
697 $self->merge_from_source($source, $codes[$i][0]);
698 }
699 }
700  
701 =item C<< $db->update_all_from_source($source) >>
702  
703 Updates all shares from a source.
704  
705 =cut
706 sub update_all_from_source {
707 my $self = shift;
708 my ($source) = @_;
709 my $ref = $self->{'_dbh'}->selectall_arrayref( "SELECT code FROM shares" );
710 my @codes = @{$ref};
711 for (my $i=0; $i<=$#codes; $i++) {
712 $codes[$i][0] =~ s/ *$//;
713 print $codes[$i][0] . "\n";
714 $self->update_from_source($source, $codes[$i][0]);
715 }
716 }
717  
718 =pod
719  
720 =back
721  
722 =cut
723 1;