バランスシートの簡易グラフ表示
財務諸表の中の1つのバランスシートのおおまかな様子を図示する
プログラムを試作しました。
これは [[流動資産、固定資産], [流動負債、固定負債、資金]]をパーセント表示するものです。
出力書式は png とsvg です。
画像生成には cairo ライブラリーを利用しました。(sudo gem install cairo でインストールすること)
ファイナンス系の web ページ, web-service や EDINET から バランスシートの上記の値を取得することは簡単だ。それらを図示するのに使おうと思っています。
以下の ruby でのソースコードを示します。
$ cat graph_bs.rb
# See http://jp.rubyist.net/magazine/?0019-cairo
# http://d.hatena.ne.jp/miyamuko/20070518/p1
# http://ashitani.jp/wiki/index.rb?p=rcairo
# 2008-05-18 katoy
require "rubygems"
require 'cairo'
def draw(surface, graph_data)
context = Cairo::Context.new(surface)
width = graph_data[:width] * 1.0
height = graph_data[:height] * 1.0
font_size = graph_data[:font_size] * 1.0
offset_x = font_size * 1.5
offset_y = font_size * 0.5
context.set_font_size(font_size)
context.select_font_face("Sans")
colors = [
[[0.0, 0.9, 0.0], [0.0, 0.9, 0.9], [0.9, 0.0, 0.0]],
[[0.9, 0.0, 0.0], [0.9, 0.9, 0.0], [0.9, 0.9, 0.9]],
[[0.0, 0.9, 0.0], [0.5, 0.9, 0.5], [0.5, 0.9, 0.0]],
]
col_num = graph_data[:data].size
graph_data[:data].each_with_index do |col, i|
total = col.to_a.inject(0){|t, a| t += a}
sub_total = 0
col.each_with_index do |val, j|
d0 = 1.0 * sub_total / total * height
d1= 1.0 * (sub_total + val) / total * height
w0 = 1.0 * width / col_num * i
w1 = 1.0 * width / col_num * (i + 1)
context.fill do
color = colors[ i % 3][j]
context.set_source_rgb(color[0],color[1],color[2])
context.rectangle(w0.round, d0.round, w1.round, d1.round)
end
context.stroke do
context.set_source_rgb(0, 0, 0) # black
context.set_line_width(1)
context.move_to(w0, d1)
context.line_to(w1, d1)
end
# text
context.set_source_rgb(0, 0, 0) # black
p = 100.0 * val / total
c = height * 0.5 * (sub_total + (sub_total + val)) / total
w = 0.5 * (w0 + w1)
context.move_to(w.round - offset_x, c + offset_y)
text = "#{"%.1f" % p} %"
context.show_text(text)
sub_total += val
end
end
context.set_source_rgb(0, 0, 0) # black
context.set_line_width(1)
# vertical line
context.stroke do
context.move_to(0, 0)
context.line_to(0, height)
(1..col_num).each do |i|
w0 = 1.0 * width / col_num * i
context.move_to(w0.round - 1, 0)
context.line_to(w0.round - 1, height)
end
end
# horizontal line
context.stroke do
context.move_to(0, 0)
context.line_to(width, 0)
end
end
def output(graph_data, file_name)
width = graph_data[:width] * 1.0
height = graph_data[:height] * 1.0
# PNG 出力
format = Cairo::FORMAT_ARGB32
Cairo::ImageSurface.new(format, width, height) do |surface|
draw(surface, graph_data)
surface.write_to_png("#{file_name}.png")
end
# SVG 出力
Cairo::SVGSurface.new("#{file_name}.svg", width, height) do |surface|
draw(surface, graph_data)
end
end
width = 100
height = 120
font_size = 10
rs = 100 # 流動資産の金額
ks = 60 # 固定試算の金額
rf = 70 # 流動負債の金額
kf = 50 # 固定負債の金額
si = (rs + ks) - (rf + kf) # 残りは資金
graph_data = {:width => width, :height => height, :font_size => 12,
:data => [[rs, ks], [rf, kf, si]]}
output(graph_data, "bs")
最近のコメント