Код: Выделить всё
function trend($currency, $offset, $time) {
$query = "SELECT `close`, `date` FROM `history_forex_h` WHERE `currency` = '$currency' AND `date` < '$time' AND `date` > DATE_SUB('$time', INTERVAL $offset DAY) ORDER BY `date`";
$set = select($query);
$sum_w = 0;
$sum_t = 0;
$t = 0;
$sum_t2 = 0;
$sum_tw = 0;
while ($row = mysql_fetch_array($set)) {
$t++;
$sum_t = $sum_t + $t;
$sum_t2 = $sum_t2 + $t*$t;
$sum_w = $sum_w + $row[close];
$sum_tw = $sum_tw + $row[close]*$t;
}
$b = ($sum_tw - $sum_t2*$sum_w/$sum_t)/($sum_t - $t*$sum_t2/$sum_t);
$a = ($sum_w - $t*$b)/$sum_t;
$sum_w_x = 0;
$n=0;
$query = "SELECT `close`, `date` FROM `history_forex_h` WHERE `currency` = '$currency' AND `date` < '$time' AND `date` > DATE_SUB('$time', INTERVAL $offset DAY) ORDER BY `date`";
$set = select($query);
while ($row = mysql_fetch_array($set)) {
$n++;
$w = $a*$n + $b;
$y = $row[close] - $w;
$sum_w_x = $sum_w_x + pow($y, 2);
}
$s = sqrt($sum_w_x/($n-1));
$return[0] = $w;
$return[1] = $s;
$return[2] = $a;
$return[3] = $b;
return $return;
}
$offset - временной сдвиг;
$time - точка отсчёта времени;
$w - средняя;
$s - отклонение;
$a - в зависимости от знака, определяем направление тренда "-" вниз, "+" вверх.
Для получения данных использовалась БД на MySQL. Ну а так, можно модифицировать под любой случай.