i new ruby, , trying code "simple" system, can keep track of stock transaction. calculating average price, , in future try dividends information.
so far, code looks (please feel free propose better ways code, said, new).
require 'money' require 'money/bank/google_currency' require 'monetize' require 'date' require 'ystock' require 'ostruct' # (optional) # set seconds after current rates automatically expired # default, never expire money::bank::googlecurrency.ttl_in_seconds = 86400 i18n.enforce_available_locales = false #erro no formatting... # set default bank instance of googlecurrency money.default_bank = money::bank::googlecurrency.new class stock attr_accessor :code, :quantity, :price, :transactions, :spotprice def initialize(code:) @code = code @quantity =00 @price = 00.to_money(:brl) @transactions = [] @spotprice = 0.to_money(:brl) end def spotprice begin asset_temp = ystock.quote(@code.to_s + ".sa") # since south america. asset_info = openstruct.new asset_temp # organize it. @spotprice = asset_info.price.to_money(:brl) # price. , transform money, local currency rescue => @error #is there tcp/ip error? @spotprice = 0.to_money(:brl) end end def buy (quantity:, price:, fees:, date:0) transactions.push type: "buy", date: date.strptime(date.to_s, '%d/%m/%y'), quantity: quantity, price: price.to_money(:brl), fees: fees.to_money(:brl) #lets calculate average price bought: new_price = (((@quantity * @price.to_money(:brl))) + ((quantity * price.to_money(:brl)) + fees.to_money(:brl))) / (@quantity + quantity) @quantity += quantity @price = new_price.to_money(:brl) # new price average price. end def sell (quantity:,price:, fees:, date:) transactions.push type: "sell", date: date.strptime(date.to_s, '%d/%m/%y'), quantity: quantity, price: price.to_money(:brl), fees: fees.to_money(:brl) @quantity -= quantity end end
for example, can create asset, , make buys , sells:
ciel3 = stock.new(code: "ciel3") ciel3.buy(quantity: 100, price: 9.00, fees: 21.5, date: "12/05/2015") p ciel3 ciel3.buy(quantity: 100,price: 12, fees: 21.7, date: "12/06/2015") ciel3.sell(quantity: 50,price: 11.5,fees: 20.86, date: "20/06/2015") p ciel3 ciel3.buy(quantity: 200,price: 15,fees: 23.6, date: "12/07/2015") puts ciel3.price.format puts puts # puts ciel3.spotprice.format p ciel3.transactions
so far, ok (but think there cleaner , more readable way it... not sure).
but lets suppose want view transactions of type "sell". how can this? how inside ciel3.transaction array, has hash :type ?? tnks
instead of using hash, want transaction
class.
if db , use activerecord, searching simple.
if not, can ciel3.transactions.select{|t| t[:type] == 'sell'}
Comments
Post a Comment