The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.

NAME

Finance::Shares::Sample - Price data on a single share

SYNOPSIS

    use Finance::Shares::Simple;
    use Finance::Shares::Simple qw(ymd_from_string
                                   string_from_ymd);

Simplest

Graph a series of stock quotes.

    my $db = new Finance::Shares::MySQL( user => 'me' );
    
    my $s = new Finance::Shares::Sample(
            mysql       => $db,
            epic        => 'GSK.L',
            start_date  => '2002-08-01',
            end_date    => '2002-08-31',
        );

    $s->output( 'Glaxo' );

Typical

Get a series of stock quotes and graph them using specific settings. Calculate some trend lines from the Finance::Shares::Sample data and superimpose them on the graph.

    my $psfile = new PostScript::File(
            landscape => 1,
            paper => 'A4',
        );
        
    my $s = new Finance::Shares::Sample(
            mysql => {
                user     => 'guest',
                password => 'a94Hq',
                database => 'London',
            },
            
            by           => 'weeks',
            epic         => 'GSK.L',
            start_date   => '2001-09-01',
            end_date     => '2002-08-31'
        );

    my $graph = $s->graph(
            file             => $psfile,
            heading          => 'GlaxoSmithKline',
            background       => [1, 1, 0.9],
            color            => [0, 0, 0.8],
            price_percent    => 50,
            volume_percent   => 20,
            analysis_percent => 30,
            analysis_low     => -100,
            analysis_high    => 100,
        );

    # construct data for lines
    $graph->add_price_line( $line1, 'Support' );
    $graph->add_volume_line( $line2, 'Average' );
    $graph->add_analysis_line( $line3, 'RSI' );
        
    $s->output( 'Glaxo' );
    

DESCRIPTION

This module is principally a data structure holding stock quotes. Price and volume data are held for a particular share over a specified period. It is possible to graph the data together with other, user-calculated lines.

All options can be given to the constructor, or to seperate fetch and graph functions. This module cooperates closely with Finance::Shares::MySQL and PostScript::Graph::Stock. See those manpages for further details.

CONSTRUCTOR

new( [options] )

options can be a hash ref or a list of hash keys and values (or omitted altogether). Recognized keys are:

by

Control how the data are stored. Suitable values are 'data', 'days', 'workdays', 'weeks', 'months'. (Default: 'data')

end_date

The last day of price data, in YYYY-MM-DD format. Only used if epic is given. See fetch.

epic

The market abbreviation for the stock. The data is fetched from Yahoo, so there probably should be a suffix indicating the stock exchange (e.g. BSY.L for BSkyB on the London Stock Exchange). If this is given, the stock data is fetched, so start_date, end_date and possibly table should also be considered. See fetch.

graph

If present, the contents is used in a call to new_graph. It should be a sub hash containing options suitable for a PostScript::Graph::Stock object. See PostScript::Graph::Stock,new.

mysql

This can be either a reference to a Finance::Shares::MySQL object or a hash ref filled with options for creating one.

Example 1

Using an existing MySQL object.

    my $db = new Finance::Shares::MySQL;            
    my $ss = new Finance::Shares::Sample (
                mysql => $db,
            );

Example 2

Creating our own MySQL connection.

    my $ss = new Finance::Shares::Sample (
                mysql => {
                    user     => 'wally',
                    password => '123jiM',
                    database => 'London',
                },
            );

start_date

The first day of price data, in YYYY-MM-DD format. Only used if epic is given. See fetch.

table

The MySQL table name for the stock. Only used if epic is given. See fetch.

tries

Specify the number of times an attempt is made to fetch the data from the internet. (Default: 3)

fetch( epic [,opts] [,start [,end [,table]]] )

epic

The market abbreviation for the stock. The data is fetched from Yahoo, so there probably should be a suffix indicating the stock exchange (e.g. BSY.L for BSkyB on the London Stock Exchange).

opts

If a hash ref is given here, it should be contain options for filtering dates. See PostScript::Graph::Stock,prepare_dates. Note that this overrides any 'dates' hash given to new.

For convenience, an additional key 'tries' is allowed. This is the same as (and overrides) the new option of the same name.

start

The first day of price data. Defaults to the earliest data already fetched (or today's date if none).

end

The last day of price data. Defaults to today's date.

table

The name of the MySQL table to use. By default this is the epic name in upper case with any non-word characters converted to underscores (e.g. BSY_L if the epic was 'bsy.l').

Three attempts are made to fetch the data from the internet (see Finance::Shares::MySQL,fetch_batch). Then the data is extracted from the MySQL database, filtered according to opts then stored as date, price and volume data.

graph( [options] )

options can be a hash ref or a list of hash keys and values. It should contain options suitable for a PostScript::Graph::Stock object, which is returned. See PostScript::Graph::Stock,new.

Example

    my $sample = new Finance::Shares::Sample(...);
    $sample->fetch( $epic, $start_date, $end_date );
    
    my $graph = $ss->new_graph(...);

    # perhaps add lines to graph
    $graph->add_price_line($data, $style, $key);

    $sample->output( $epic );

For details of constructing the line data see PostScript::Graph::Stock,add_price_line.

Note that the options given here override any given to the constructor. In particular, it is possible to get into a mess with the 'dates' or 'by' settings. The data is filtered for dates when it is fetched according to the constructor option, 'by'. Make sure that the 'dates' sub-hash given to graph, if used, has the same 'by' setting, otherwise there will either be unpredictable gaps in the graph or missing data.

Example

    my $sample = new Finance::Shares::Sample(
            by => 'days',
        );

    $sample->graph(
            dates => {
                by => 'days',
            },
        );

output( file [, dir] )

The graph is constructed and written out to a PostScript file. A suitable suffix (.ps, .epsi or .epsf) will be appended to the file name. This is a convenience method, identical to calling output on the PostScript::Graph::Stock object returned by graph. Both these examples do the same thing.

Example 1

    my $ss = new Finance::Shares::Sample(...);
    $ss->fetch( $epic, $start_date, $end_date );
    
    $sg->output( $epic );

Example 2

    my $ss = new Finance::Shares::Sample(
            ...
            epic        => $epic,
            start_date  => $start_date,
            end_date    => $end_date,
        );

    my $graph = $ss->graph();
    $graph->output();
    

SUPPORT METHODS

prepare_dates( data [,options] )

This splits raw CSV-style data into the date labels, prices and volumes needed for a stock graph. data should be a reference to an array of arrays. The inner arrays should hold a date in YYYY-MM-DD format, opening, high, low and closing prices followed by the volume. Either the prices or the volume may be omitted.

Example

    $data = [
    [2001-06-01,454.50,475.00,448.50,461.00,8535680],
    [2001-06-04,465.00,465.00,458.50,459.00,3254045],
    [2001-06-05,458.25,464.00,455.00,462.00,4615016],
    ];

options may either be a hashref or a list of hash keys and values. Recognized hash keys follow.

by

This string determines how the dates are distributed across the X axis.

data

The dates are those present in the data, in chronological order (the default).

days

Every day between the first and last day is listed, whether there is data for that day or not.

workdays

Every day except Saturdays and Sundays. Occasional holidays are ignored, just showing as days with no data.

weeks

Only the data for last trading day of each week is presented. No attempt is made to take the rest of the week into account - those days are just hidden. If any trading is recorded for that week, the latest day is given; if not the last working day is shown, with no data.

months

As weeks, but showing the last trading day of each month.

changes_only

The date labels are made up of weekday, day, month and year. Which sections are shown by default depends on the dates setting. If this is 1, each part is only shown if it has changed from the previous label. If 0, all the selected parts are shown. (Default: 1)

days

This allows the weekday abbreviations to be presented in a different language. It should be an array ref containing strings. Monday = 1, so there should probably be a dummy string for 0. (Defaults to English).

months

This allows the month abbreviations to be presented in a different language. It should be an array ref containing strings. January = 1, so there should probably be a dummy string for 0. (Defaults to English).

show_day

Show the date of day within the month. (Default: depends on dates)

show_month

Show the month. (Default: depends on dates)

show_weekday

Show the day of the week. (Default: depends on dates)

show_year

Show the month. (Default: depends on dates)

Values returned

order

A hash ref. Keyed by date, the integer values indicate the order of labelled dates. Used for locating valid dates within the dates array.

price

A hash ref. Keyed by the YYYY-MM-DD date, each entry points to a list of price data.

    [ Open, High, Low, Close ]
volume

A hash ref. If present the Volume (or averaged volume) of trades is keyed by the YYYY-MM-DD date.

dates

An array ref. Each date in this list (in YYYY-MM-DD format) represents a labelled point on the graph - typically a day, week or month. However, not all of these may be visible as labels if there is not enough room across the axis. This should be the 'X' value used in constructing all superimposed lines.

labels

An array ref. The labels to be printed.

labelmax

The length of the longest label.

EXPORTED FUNCTIONS

No export tags are defined and no functions are exported by default. The functions defined here must be specified by name before it can be used.

    use Finance::Shares::Sample qw(ymd_from_string
                                   string_from_ymd);

ymd_from_string( date )

Takes a string in the form YYYY-MM-DD and returns an array of integers (year, month, day).

string from_ymd( year, month, day )

Converts the three integer values into a YYYY-MM-DD string.

BUGS

Please report those you find to the author.

AUTHOR

Chris Willmot, chris@willmot.org.uk

SEE ALSO

Finance::Shares::Log, Finance::Shares::MySQL and PostScript::Graph::Stock.