In this post, I am going to use this observable module to implement a program that allow me follow stocks prices, and also calculate the average over time.
Assume that the stock market allow me to read current stock price with a function call "get_current_price(stock_symbol)". With this method, I can implement a simple class, SimpleStockWatcher, to read the current price and calculate the average as follow:
Assume that the stock market allow me to read current stock price with a function call "get_current_price(stock_symbol)". With this method, I can implement a simple class, SimpleStockWatcher, to read the current price and calculate the average as follow:
class SimpleStockWatcher
def initialize(symbol)
@symbol = symbol
@sum = 0
@count = 0
end
def update
price = get_current_price(@symbol)
@sum += price
@count += 1
show(price)
end
def show(price)
puts "Symbol #{@symbol}"
puts " Time: #{Time.now}"
puts " Current Price: #{price}"
puts " Average: #{@sum/@count}"
end
end
If I want to monitor Bank of America (BOA), and Google (GOOG), I implement the following loop:stocks = [ SimpleStockWatcher("BOA"), SimpleStockWatcher("GOOG") ]
loop do
stocks.each(&:update)
sleep(1)
end
This loop will print the stocks price and average very second.Now, I want to add more analysis, say 30 or 100 days moving average. No problem, I add more code into the SimpleStockWatcher. Then every second we get the stock prices, average, 30-day moving average, and 100-days moving average.
Let get a bit more complicate, I want to show only current price and 30-days moving average for stock "BOA". For "GOOG", I want to show current price, the average, and 100-days moving average. How do I satisfy this requirement?




