gpt4 book ai didi

Ruby:使用哈希跟踪股票交易

转载 作者:太空宇宙 更新时间:2023-11-03 18:08:42 25 4
gpt4 key购买 nike

我是 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

例如,我可以创建 Assets 并进行买卖:

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

到目前为止,还可以(但我认为有一种更清晰、更易读的方法来做到这一点……不确定)。

但是假设我想查看“SELL”类型的所有交易。我怎样才能做到这一点?如何查看具有哈希 :type 的 ciel3.transaction 数组?坦克

最佳答案

您可能需要一个 Transaction 类,而不是使用哈希。

如果你用数据库做后盾,用ActiveRecord,那么搜索就很简单了。

如果没有,您可以执行 ciel3.transactions.select{|t| t[:type] == '卖出'}

关于Ruby:使用哈希跟踪股票交易,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38512210/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com