parse_google_financeDo you need to retrieve stock market historical data from Google Finance (for example http://www.google.com/finance/historical?q=goog&output=csv) to do some calculation (for example calculate the average of last 20 days) ?

So, in this lesson, you will learn how to:
1. Parse a CSV file to a Rebol’s block (similar to other’s programming languages’ array)
2. Manipulate Rebol’s block’s item

We will use the parse function we already encountered (how to extract html webpage without using Regular Expressions) but in a different form.

Start Rebol’s Console and type:


stock-data: read http://www.google.com/finance/historical?q=goog&output=csv
type? stock-data


Note that the type is string.

Do it again by adding the /lines refinement to the read function (you can use the up arrow twice to retrieve the previous command and use the left arrow to go to the beginning of the line).


stock-data: read/lines http://www.google.com/finance/historical?q=goog&output=csv
type? stock-data


Note that the type is block.

You can now retrieve each element of the block with:


stock-data/1
stock-data/2
stock-data/3

Let’s parse last quote (stock-data/2) and retrieve the close (5th column):


last-quote: parse stock-data/2 ","
close: pick last-quote 5



To parse the whole stock-data we have to iterate through it :


close-block: []
foreach element stock-data [
    last-quote: parse/all element ","
    append close-block pick last-quote 5
]

You can now calculate the 20 days moving average:


cum: 0
for i 2 21 1 [cum: cum + to-decimal close-block/:i]
average: cum / 20

This is the whole program for any stock symbol


Rebol[
  title: "Parse google finance csv file"
  author: "http://reboltutorial.com/blog/parse-csvparse-csv/"
  version: 1.0.0
]

symbol: ask "symbol: "
url: rejoin [http://www.google.com/finance/historical?q= symbol "&output=csv"]
stock-data: read/lines url
close-block: []
foreach element stock-data [
    last-quote: parse/all element ","
    append close-block pick last-quote 5
]
cum: 0
for i 2 21 1 [cum: cum + to-decimal close-block/:i]
average: cum / 20

References:
1. http://www.rebol.net/cookbook/recipes/0018.html
2. http://snippets.dzone.com/posts/show/1281

Bookmark and Share