class Screener

Public Class Methods

new(agent, auth, *params) click to toggle source
# File lib/finviz_rails/screener.rb, line 2
def initialize(agent, auth, *params)
  @agent = agent
  @auth = auth
  @params = params.first
  @stocks = []
end

Public Instance Methods

run() click to toggle source
# File lib/finviz_rails/screener.rb, line 9
def run
  @agent.get(url)
  set_pagination_count
  set_found_stock_count
  add_stocks_from_page(@agent.page.parser)
  if @pagination_count
    (2..@pagination_count).each do |page_num|
      break if max_stock_count && @stocks.count >= max_stock_count
      @agent.get url(page_num)
      add_stocks_from_page(@agent.page.parser)
    end
  end
  results
end

Private Instance Methods

add_stocks_from_page(html) click to toggle source
# File lib/finviz_rails/screener.rb, line 57
def add_stocks_from_page(html)
  rows = html.css('#screener-content > table > tr:nth-child(4) tr')
  headers = rows.shift
  stocks = rows.map do |row|
    stock = {}
    row.css('td').each_with_index do |td, index|
      header = format_header(headers.css('td')[index].text)
      stock[header] = td.text
    end
    stock
  end
  @stocks.concat stocks
end
format_header(header) click to toggle source
# File lib/finviz_rails/screener.rb, line 71
def format_header(header)
  header.gsub('.','').gsub('/','_').gsub(' ','').downcase
end
max_stock_count() click to toggle source
# File lib/finviz_rails/screener.rb, line 46
def max_stock_count
  @params[:max_stock_count]
end
results() click to toggle source
# File lib/finviz_rails/screener.rb, line 26
def results
  {
    found_stock_count: @found_stock_count,
    returned_stock_count: returned_stocks.count,
    stocks: returned_stocks
  }
end
returned_stocks() click to toggle source
# File lib/finviz_rails/screener.rb, line 34
def returned_stocks
  max_stock_count ? @stocks.first(max_stock_count) : @stocks
end
row_limit() click to toggle source
# File lib/finviz_rails/screener.rb, line 75
def row_limit
  found_count = @agent.page.content.match(/var portfolioRowsLimit=(\d+)/)
  found_count ? found_count[1].to_i : nil
end
set_found_stock_count() click to toggle source
# File lib/finviz_rails/screener.rb, line 38
def set_found_stock_count
  @found_stock_count = begin
    text = @agent.page.parser.css('.count-text').text
    match = text.match /Total: (\d+)/
    match[1]
  end
end
set_pagination_count() click to toggle source
# File lib/finviz_rails/screener.rb, line 50
def set_pagination_count
  @pagination_count ||= begin
    pages = @agent.page.parser.css('a.screener-pages')
    pages.any? ? pages.last.text.to_i : nil
  end
end
url(page=nil) click to toggle source
# File lib/finviz_rails/screener.rb, line 80
def url(page=nil)
  UrlFormatter.new(@auth, page, @params, row_limit).run
end