0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

[決算]株価収益率(PER)を計算する機能を設計 & 実装してみた

Posted at

前回 EPSの実装をしたので
今回はEPSと株価で算出できるPERという値をクラス化してみた

株価収益率(PER: Price Earnings Ratio)の計算方法

PER(倍) = 株価 / EPS

PERをざっくり説明すると「低いほど割安、高いほど割高」らしい

実装方針

EPSが株価をもらってPERを計算できるようにしてみる

まず株価クラスを作成

stock_price.rb
class StockPrice < NumericalValue
  # @param [BigDecimal] value (単位:円)
  def post_initialize(value)
    raise TypeError, '株価は1以上で指定してください' unless value.positive?
  end
end

次にPERクラスを作成

per.rb
class PER < NumericalValue
  # @param [BigDecimal] value (単位:倍)
  def post_initialize(value)
    # 特に無し
  end
end

最後にPERを返すメソッドをEPSに追加

eps.rb
class EPS < NumericalValue
  # 省略

  # @param [StockPrice] stock_price 株価
  # @return [PER]
  def per(stock_price)
    raise TypeError, 'StockPriceを指定してください' unless stock_price.kind_of?(StockPrice)

    PER.new(stock_price.to_d.div(to_d))
  end
end

EPSのテスト

eps_spec.rb
RSpec.describe EPS do
  describe 'PERを計算' do
    it do
      eps = described_class.new(23.11)
      stock_price = StockPrice.new(2620.0)
      per = eps.per(stock_price)
      expect(per.to_d).to be_within(0.01).of(113.37)
    end
  end
end

todo

本筋と関係ないがpost_initializeが不要なクラスには実装しなくて良い気がしてきた

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?