Average Price Script 0.0.1

This entry is part 1 of 2 in the series Average Price Script

So I made a small Perl script again. The script polls data from Google Finance and calculates the average price for a given symbol. The first parameter of the script is the Google Finance symbol that starts with the name of the exchange followed by a colon like ‘NYSE:IBM’. The script expects an optional second parameter an integer number indicating the poll interval, 1 by default. Data is retrieved with curl. The response is in the JSON format. I get the current price with a regex from the response. All the prices are stored in an array and averaged. I also do some rudimentary logging.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#!/usr/bin/perl
 
# This script polls data from Google Finance and calculates the average price for a given symbol.
#
# Parameters:
#  symbol         The Google Finance symbol like 'NYSE:IBM'.
#  secondsSleep   Integer number indicating the poll interval, 1 by default.
#
$symbol = $ARGV[0];
print "$symbol\n";
 
while(1) {
   $data=`curl -s "http://finance.google.com/finance/info?client=ig&q=$symbol"`;
   $data =~ m/l_cur" : "(.*)"/;
   $td=`date +'%Y%m%d %H:%M - '`;
   push(@prices, $1);
   $num = scalar @prices;
   $sum = 0;
 
   for( $i = 0; $i < $num; $i++) {
      $sum += $prices[$i];
   }
 
   $average = $sum / $num;
   print "$num elements, average $average\n";
   print "$1 $td";
   sleep $ARGV[1];
}

Possible improvements

Here is a list of improvements I have been thinking about.

  • Use a proper JSON library.
  • Calculate standard deviation as well.
  • Calculate a time weighted average, where recent values have a higher weight.
  • Improve logging.

Random links of interest

Series NavigationStackrumban Scrumban StackOverflow style
By the author of NumPy Beginner's Guide, NumPy Cookbook and Instant Pygame. If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.
Share
This entry was posted in programming and tagged . Bookmark the permalink.