HiveBrain v1.2.0
Get Started
← Back to all entries
patternrubyMinor

Scraping and analyzing recent articles on bitcoin

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
recentanalyzingscrapingarticlesandbitcoin

Problem

This script scrapes recent articles on bitcoin, does sentiment analysis, and does some mock trading based on the sentiment of the articles. I'm looking for advice on code style, and I would love to learn how to write beautiful Ruby.

```
require 'coinbase'
require 'sanitize'
require 'cgi'
require 'htmlentities'
require 'sentimental'
require 'simple-rss'
require 'open-uri'
require 'sqlite3'
require 'date'

@db = SQLite3::Database.open('instructions.db')
@db.execute("CREATE TABLE IF NOT EXISTS instructions2(Id INTEGER PRIMARY KEY AUTOINCREMENT, Date TEXT, Do_now TEXT, Do_later TEXT, Buy_price TEXT, Sell_price TEXT)")
@rss = SimpleRSS.parse(open('http://fulltextrssfeed.com/news.google.com/news?pz=1&cf=all&ned=us&hl=en&q=Bitcoin&output=rss'))
@coinbase = Coinbase::Client.new(ENV['COINBASEKEY'])
@coder = HTMLEntities.new
Sentimental.load_defaults
@analyzer = Sentimental.new
@ran_today = false
@scores_today = []
@log = File.open('log.txt', 'w')

def write_log(me)
@log 3.0
do_now = :buy
do_later = :sell
elsif avg sell " + sell_price
end
elsif do_now == "sell"
if check_sell > buy_price.to_f
sell
else
puts "want to sell, sell " + sell_price + " > buy " + buy_price
end
end
@db.execute("DELETE * FROM instructions2 WHERE Date=?", Date.today.to_s)
end
end
end

def buy
write_log("would buy at " + check_buy.to_s + " at " + Date.today.to_s)
end

def sell
write_log("would sell at " + check_sell.to_s + " at " + Date.today.to_s)
end

def nothing
write_log("would do nothing at " + Date.today.to_s)
end

def check_sell
@coinbase.sell_price(1)
end

def check_buy
@coinbase.buy_price(1)
end

def clean(stuff)
Sanitize.clean(CGI.unescapeHTML(stuff).to_s.force_encoding('UTF-8'))
end

check_sentiment
read_instructions
@ran_today = true
while true
if Time.now.hour == 23 and not @ran_today
check_sentiment
elsif Time.now.hour == 1
read_instructions
elsif Time.now.hour == 24
@ran

Solution

The @ variable prefix should only be used inside a class to denote instance variables. That said, for a script like this, you might like to wrap all the logic in a class (or rather a module since you don't need multiple instances).

Use string interpolation. So instead of

DateTime.now.to_s + " : " + me.to_s


you can write

"#{DateTime.now} : #{me}"

Code Snippets

DateTime.now.to_s + " : " + me.to_s
"#{DateTime.now} : #{me}"

Context

StackExchange Code Review Q#41234, answer score: 5

Revisions (0)

No revisions yet.