调用Yahoo API监控外汇汇率
参考链接:
1, http://kuppalli.wordpress.com/2008/11/15/get-live-currency-value-using-yahoo-api/
2, http://www.gummy-stuff.org/Yahoo-data.htm
刚到墨尔本时, 我壮了壮胆子, 在 Subway 吃了一顿, 然后用我招商银行的信用卡结了账. 感觉还不错, 心想至少拿着人民币也饿不着了. 但回家一看账单, 招行先把账单上的澳元换美元, 再换人民币, 最后算给我的汇率就比当时的澳元/人民币汇率高的多了. 还是找个汇率低的时候多换点吧.
Yahoo! 上提供了各种金融数据的接口, 有股票/能源/期货自然也有外汇汇率. 我参考了一下API, 查询澳币/人民币汇率的方法是:
http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=AUDCNY=x
上面的链接在浏览器中可以得到如下数据:
"AUDCNY=X",6.7402,"3/5/2012","3:40am"
其实就是CSV格式了, 所以可以看出在URL里的"f=sl1d1t1"就分别指定了代号, 汇率, 日期, 时间这四个字段. 再往下就很简单了. 用 curl 获取数据, 再写入 MySQL 数据库就完成了采集功能. 而对比最近的几次汇率, 如果突破阈值就发送邮件, 也就完成了基本的监控功能了.
下面是我写的 PHP 文件, 用 Cron 设定间隔执行即可, 例如5分钟一次:
*/5 * * * * /usr/bin/php /home/raymond/path/to/cron-task.php
PHP 源码(写的很原始 ^o^):
<?php
$url = "http://download.finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s=AUDCNY=x+AUDUSD=x";
$trigger_low = 6.68;
$trigger_high = 6.93;$dbc = mysql_connect("localhost", "root", "blizzard");
if(!$dbc):
die("Error connecting to DB." . mysql_error());
endif;
?>
<?php
$handle = curl_init($url);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($handle);if(curl_errno($handle)):
echo "CURL Error: " . curl_error($handle);
else:
$sql = "insert into `forexrates` (`currencypair`, `rate`, `source-time`) values ";
$values = array();$rows = explode("\n", $result); //echo print_r($rows); echo print_r($result);
foreach($rows as $row):
//"AUDCNY=X",6.8059,"2/29/2012","7:54pm"
$cols = explode(",", $row);
if(count($cols) < 4):
continue;
endif;
$currency_pair = substr($cols[0], 1, 6);
$rate = $cols[1];
$t = trim($cols[2], '" ') . ' ' . trim(trim($cols[3]), '"'); //echo $t;$source_date = new DateTime($t);
$source_date_str = $source_date->format('Y-m-d H:i:s');$values[] = " ('$currency_pair', '$rate', '$source_date_str')";
endforeach;mysql_selectdb('falcon', $dbc);
$sql .= implode(',', $values); //echo $sql;
mysql_query($sql, $dbc);
if(mysql_errno($dbc)):
echo mysql_error($dbc);
endif;
endif;
curl_close($handle);
?>
<?php //notification for AUDCNY high and low rates
$sql = "select rate from forexrates where currencypair='AUDCNY' order by id desc limit 2";
$query = mysql_query($sql, $dbc);
$rate1 = (double)mysql_result($query, 0, 'rate');
$rate2 = (double)mysql_result($query, 1, 'rate'); echo $rate2 . ' --> ' . $rate1;$subject = '';
$to = 'raynix@gmail.com';
$body = (string)$rate1;
if($rate1 > $rate2 && $rate2 > $trigger_high):
$subject = 'The rate is getting HIGH!';
mail($to, $subject, $body);
elseif($rate1 < $rate2 && $rate2 < $trigger_low):
$subject = 'The rate is getting LOW!';
mail($to, $subject, $body);
endif;mysql_close($dbc);
?>