2016-07-21 34 views
1

我是Ruby的新手,我試圖編寫一個「簡單」系統,以便跟蹤股票交易。計算平均價格,並在未來我會嘗試獲取股息信息。Ruby:跟蹤使用哈希的股票交易

到目前爲止,我的代碼如下所示(請隨時提出更好的方法做我的代碼,正如我所說,我是新的)。

require 'money' 
require 'money/bank/google_currency' 
require 'monetize' 
require 'date' 
require 'ystock' 
require 'ostruct' 

# (optional) 
# set the seconds after than the current rates are automatically expired 
# by default, they never expire 
Money::Bank::GoogleCurrency.ttl_in_seconds = 86400 
I18n.enforce_available_locales = false #erro no formatting... 
# set default bank to 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 it is South America. 
      asset_info = OpenStruct.new asset_temp # organize it. 
      @spotprice = asset_info.price.to_money(:BRL) # get the price. And transform it to Money, local currency 
     rescue => @error #Is there an 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 the average price that we 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 is the 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 

例如,我可以創造財富,使購買和銷售:

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 

到目前爲止,這是確定的(但我認爲有一個更清潔,更可讀的方式做它......不確定)。

但是讓我們假設我要瀏覽的類型「沽售」的所有交易。 我該怎麼做?如何查看ciel3.transaction數組,裏面有散列:type ?? TNKS

回答

3

而不是使用哈希,你可能要一個Transaction類。

如果用DB支持它,並使用ActiveRecord,然後搜索將是非常簡單的。

如果沒有,你可以做ciel3.transactions.select{|t| t[:type] == 'SELL'}

+0

B.七,謝謝!這十分完美。我還不知道有關交易課程。我會看一下。你會給我的代碼提供任何其他提示嗎? –

+0

我無法找到Ruby的Transaction類。只有Rails,它是一樣的嗎? –

+0

你會自己創建'Transaction'類:'class Transaction'。 –