Search code examples
ruby-on-railsyahoo-finance

Rails 4 Set field value from API


I'm using the https://github.com/herval/yahoo-finance gem in an application. I'm trying to set inception_date field in the Security table whenever the show view loads (I'm still trying to just get my feet under me, I wouldn't mind this trigger on a button push either). Under the Security show in the securities_controller I have the action take place.

Security.set_inception_date(params[@security.ticker]) 

In the model I have the following:

def self.set_inception_date(ticker)
yahoo_client = YahooFinance::Client.new
data = yahoo_client.historical_quotes("AAPL")
ticker.inception_date = data[0].trade_date
save(true)
end

I'm getting the error "undefined method 'inception_date='"

What basic concept am I missing? I even hard coded the apple ticker "AAPL" instead of trying to pass the params[@security.ticker] which is also not working.

As always, thanks in advance for your expert advice and patience with us rookies.


Solution

  • Looking at the documentation, it looks like you need to pass an array of tickers, as well as fields you want returned

    yahoo_client = YahooFinance::Client.new
    data = yahoo_client.quotes(["BVSP", "NATU3.SA", "USDJPY=X"], [:ask, :bid, :last_trade_date])
    

    Try this:

    data = yahoo_client.historical_quotes(["AAPL"],[:last_trade_date])
    

    EDIT

    Based in the comments chat, you need to assign the value returned from the API to an object.

    eg:

    sec = Security.new
    sec.set_inception_date(ticker)
    
    def set_inception_date(ticker)
       yahoo_client = YahooFinance::Client.new
       data = yahoo_client.historical_quotes(["AAPL"])
       self.inception_date = data[0].trade_date
       self.save
    end
    

    It would probably be better to break the whole thing into 2 classes, something like.

    sec = Security.new
    sec.inception_date = YourYahooClass.get_inception_date(ticker)
    sec.save
    
    
    Class YourYahooClass
       def self.get_inception_date(ticker)   # class method, object not instantiated
          yahoo_client = YahooFinance::Client.new
          data = yahoo_client.historical_quotes(["AAPL"])
          return data[0].trade_date
       end
    end