NAME

Finance::Shares::Chart - construct shares graph

SYNOPSIS

use Finance::Shares::Chart;

my $fsc = new Finance::Shares::Chart( <options> );
$fsc->add_data($data);
$fsc->add_line($line);
$fsc->build();
$fsc->output($filename, $dir);

$fsc->add_graph($name, $opt_hash);
$fsc->set_period($start, $end);
my $data = $fsc->data();

DESCRIPTION

This module provides the output for Finance::Shares::Model. It builds a series of graphs on a single page, with a key panel indicating the role of any lines added. A Finance::Shares::data object may be declared, which provides stock price quotes and volume information. Any number of Finance::Shares::Line objects may be displayed as well. These are normally generated from Finance::Shares::Function objects (See Finance::Shares::Function for details).

There are four types of graphs. Each type may appear as often as you wish (or not at all), but the first of each type gets used if none other is specified.

price

Price data can be displayed using normal open-close-high-low marks, Japanese candles, or just the closing positions for each day. The Y axis is scaled for prices.

volume

Volume bars are displayed on this graph whose Y axis is typically scaled in millions.

analysis

There would typically be more than one 'analysis' graph on a chart. The Y axis is usually scaled to show price movements which may be negative as well as positive.

level

Several of the available functions compare two other lines or signal whether conditions are true or false. Their results would be shown on a 'level' graph. The Y axis is often scaled 0 to 100%.

As there is only one Key panel shared by all graphs, each line is typically displayed in a different colour by default. Like almost everything else, this behaviour is configurable.

All error, log and debug messages are controlled by Log::Agent. By default this does the expected thing, but it does mean they may be routed differently as required. See Log::Agent for details.

CONSTRUCTOR

new( options )

<options> must be a hash ref or a list of hash keys and values. There are a lot of them - up to 250 or more. Many are just listed here. See the indicated man pages for full details. The options fit within a hash tree structure like the following.

    my $fsc = new Finance::Shares::Chart(
	background => [0.9, 0.95, 0.95],
	stock      => 'MSFT',
	period => {
	    start  => '2003-01-01',
	    by     => 'weeks',
	},
	graphs => [
	    MACD => {
		percent => 40,
	    },
	    Tests => {
		gtype => 'level',
		show_dates => 1,
	    },
	],
    );

Colours can be a decimal from 0 (black) to 1 (brightest), or a triple within an array ref when each decimal represents the brightness of red, green and blue. Any measurements are in PostScript units (1/72"), so think point sizes.

Top level options

verbose

Controls the amount of feedback provided

0	silent
1	errors only (default)
2	slghtly more informative
3+	debugging
iname

A unique name assigned by Finance::Shares::Model. It identifies the chart and its associated data (if any).

background

The background colour for all the graphs. This can be a shade of grey (0.0 for black, 1.0 for brightest) or an array ref holding similar decimals for red, green and blue, e.g. [ 0.6, 0.4, 0 ] for a red-orange. (Default: 1.0)

bgnd_outline

By default the price and volume marks are drawn with a contrasting outline. Setting this to 1 makes this outline the same colour as the background. (Default: 0)

dpi

One of the advantages of PostScript output is that it can make the best use of each medium. Setting this to 72 produces output suitable for most computer monitors. Use a higher figure for hard copy, depending on you printer's capabilities. (Default: 300)

directory

Optional directory prepended to the output file name.

glyph_ratio

Generating PostScript is a one-way process. It is not possible to find out how much space will be taken up by a string using a proportional spaced font, so guesses are made. This allows that guess to be fine tuned. (Default: 0.44)

heading

Appears at the top of the page. Defaults to something suitable.

page

An optional string used as the PostScript page 'number'. Although this may be anything many programs expect this to be short like a page number, with no spaces.

smallest

The underlying PostScript::Graph::Paper module will sometimes generate more subdivisions and axis lines than needed, especially at high resolutions. smallest provides some control over this for the Y axes. It specifies the size of the smallest gap between lines; giving a larger number means fewer lines. The default produces 3 dots at the resolution given to dots_per_inch.

Note that the only way to control the line density on the X axis is to plot fewer dates. One way of doing this is to set the Finance::Shares::Sample contructor option by to 'weeks' or 'months'.

sequence

An internal PostScript::Graph::Sequence controls the different colours given to each line displayed. Assigning your own here gives you more control of how the lines appear. Not that it is possible to override this behaviour completely by specifying auto = 'none'> within each line style hash. See PostScript::Graph::Style.

stock

This would be a code indicating the particular stock being displayed. However, it could be anything as it is only used in constructing the default heading.

show_breaks

A value of 1 means that any undefined values show a break in the line, otherwise the line is continuous. (Default: 0)

period

The chart displays dates in a given range at a particular frequency - days, months etc. It does not show all the dates in the associated Finance::Shares::data object, as a certain lead time is often required to establish reliable calculations. The chart may also have an unfilled area after the end of the data to allow for a little extrapolation.

These details are given within a period sub-hash, which may have the following fields.

start

The first date to be displayed. It should be in YYYY-MM-DD format.

end

The last date on the chart. Again, in YYYY-MM-DD format.

by

Determines how the intervening dates are counted. Suitable values are

quotes	weekdays
days	weeks
months

file

This can be either a PostScript::File object or a hash ref holding parameters suitable for creating one. The default is to set up a landscape A4 page with half inch margins. The hash ref may contain the following keys. See PostScript::File for details.

paper	width
height	landscape
eps		dir
png		gs
left	right
top		bottom
clipping	clip_command
headings	reencode
debug	errors
errx	erry

heading_font

A sub-hash controlling how the heading appears. Recognized keys are:

font

The font family name which should be one of the following. (Default: 'Times-Bold')

Courier
Courier-Bold
Courier-BoldOblique
Courier-Oblique
Helvetica
Helvetica-Bold
Helvetica-BoldOblique
Helvetica-Oblique
Times-Roman
Times-Bold
Times-BoldItalic
Times-Italic
Symbol
size

Point size to use. (Default: 14)

color

The normal colour format: either a grey value or an array ref holding [<red>,<green>,<blue>]. (Default: 1.0)

normal_font

This controls the font used to label the graphs. The defaults are different ('Helvetica', 10pt) but the keys are the same as for heading_font.

key

This sub-hash controls the appearance of the Key panel. See PostScript::Graph::Key for details of these possible entries.

 background	    title
 outline_color   outline_width
 title_font	    text_font
 spacing	    glyph_ratio
 vert_spacing    horz_spacing
 icon_width	    icon_height
 text_width

x_axis

The dates axis is controlled by this sub-hash. The show_ options largely refer to how the date labels are built up. changes_only controls whether the full label is shown (0) or only those parts that have changed (1). Other options are explained in PostScript::Graph::Paper.

show_lines	    changes_only
show_weekday    show_day
show_month	    show_year
mark_min	    mark_max
color	    heavy_color
mid_color	    light_color
heavy_width	    mid_width
light_width

graphs

This is an exception. Where all the other headings describe hash refs, this is an array ref. The array lists descriptions for each of the graphs to be shown on the page. Each graph description is a hash ref keyed by the graph's title.

    graphs => [
	'Stock Prices' => {
		gtype => 'price',
		...
	    },
	'Trading Volumes' => {
		gtype => 'volume',
		...
	    },
	'Momentum' => {
		gtype => 'analysis',
		...
	    },
	'On-Balance Volume' => {
		gtype => 'analysis',
		...
	    },
	...
    ],

Graph options

Each graph hash ref may include any of the following values or sub-hashes.

percent

This is the proportion of space allocated to the graph. Specifying 0 hides it. It is not a strict percentage in that they don't all have to add up to 100, but it does give an idea of the sort of numbers to put here. There may be problems if the value is less than 10, or so small the graph cannot physically be drawn in the space.

Some graphs will become visible automatically (provided their percent is not 0) if data or lines should be shown there. They take a default value of 20.

gtype

Identifies the type of Y axis to use. Must be one of

price	volume
analysis	level
show_dates

True if the dates axis is to be shown under this chart. By default the dates are placed under the first graph that hasn't specified show_dates => 0.

bars

Only appropriate for the volume type graph, this sub-hash specifies how the volume bars look. See PostScript::Graph::Style.

color	    width
inner_color	    outer_color
inner_width	    outer_width

points

Only appropriate for the price type graph, this sub-hash specifies how the price marks look. Values for shape are as follows and NOT as described in PostScript::Graph::Style.

stock   stock2
candle  candle2
close   close2

The other options are as bars.

layout

See PostScript::Graph::Paper for details.

spacing
top_margin
right_margin

y_axis

See PostScript::Graph::Paper for details.

title	    color
heavy_color	    mid_color
light_color	    heavy_width
mid_width	    light_width
mark_min	    mark_max
label_gap	    si_shift

add_data( data )

Declare the stock quote data associated with this chart - there should only be one. data must be a Finance::Shares::data object.

add_line( line )

Register a line with this chart. line should be a Finance::Shares::Line derived object. It's graph is determined from its optional {graph} or mandatory {gtype} fields.

build( )

Once the resources are gathered, this method puts them all together. The chart is built in PostScript. If no PostScript::File object was given to the constructor one is created for this chart, otherwise the chart is written to the current page.

output( [filename [, directory]] )

The graphs are constructed and written out to a PostScript file. A suitable suffix (.ps, .epsi or .epsf) will be appended to the file name.

If no filename is given, the PostScript text is returned. This makes handling CGI requests easier.

ACCESS METHODS

name( )

Returns the canonical name for this chart.

data( )

Return the Finance::Shares::data object holding the stock quotes for this chart.

graph_for( line )

The most reliable way of determining which graph a particular Finance::Shares::Line object will appear on. A new graph is created if no existing graph is suitable. line must have at least a {gtype} field and optionally a {graph} field holding a graph name.

set_period( )

Used by the associated Finance::Shares::data object to ensure the dates used in the default title are correct.

hidden( )

Returns true if the chart is not to be displayed.

CLASS METHODS

The PostScript code is a class method so that it may be available to other classes that don't need a Stock object.

The useful functions in the 'gstockdict' dictionary draw a stock chart mark and a close mark in either one or two colours.

make_candle
make_candle2
make_stock
make_stock2
make_close
make_close2

The all consume 5 numbers from the stack (even if they aren't all used):

 x yopen ylow yhigh yclose

gstockdict

A few functions are defined in the gstockdict dictionary. These provide the code for the shapes drawn as price marks. These dictionary entries are defined:

make_stock	 Draw single price mark
make_stock2  Draw double price mark
make_candle	 Draw Japanese candle mark
make_candle2 Draw Japanese candle mark
make_close	 Draw single closing price mark
make_close2  Draw double closing price mark
yclose	 parameter
ylow	 parameter
yhigh	 parameter
yopen	 parameter
x		 parameter
dx		 working value
dy		 working value

A postscript function suitable for passing to the shape option to new must have 'make_' preprended to the name. It should take 5 parameters similar to the code for shape = 'stock'> which is called as follows.

x yopen ylow yhigh yclose make_stock

BUGS

Please do let me know when you suspect something isn't right. A short script working from a CSV file demonstrating the problem would be very helpful.

AUTHOR

Chris Willmot, chris@willmot.org.uk

LICENCE

Copyright (c) 2003 Christopher P Willmot

This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. A copy can be found at http://www.gnu.org/copyleft/gpl.html

SEE ALSO

Finance::Shares::Overview provides an introduction to the suite, and fsmodel is the principal script.

Modules involved in processing the model include Finance::Shares::Model, Finance::Shares::MySQL, Finance::Shares::Chart. Chart and file details may be found in PostScript::File, PostScript::Graph::Paper, PostScript::Graph::Key, PostScript::Graph::Style.

Functions are invoked from their own modules, all with lower-case names such as Finance::Shares::moving_average. The nitty-gritty on how to write each line specification are found there.

The quote data is stored in a Finance::Shares::data object. For information on writing additional line functions see Finance::Share::Function and Finance::Share::Line. Also, Finance::Share::test covers writing your own tests.