将股票日K转换为年K的PHP代码
以下是将股票日K转换为年K的PHP代码示例:
<?php
// 股票日K数据
$dailyK = [
['date' => '2022-12-31', 'open' => 10, 'high' => 12, 'low' => 8, 'close' => 11],
['date' => '2022-12-30', 'open' => 9, 'high' => 11, 'low' => 8, 'close' => 10],
['date' => '2022-12-29', 'open' => 8, 'high' => 10, 'low' => 6, 'close' => 9],
['date' => '2022-12-28', 'open' => 6, 'high' => 9, 'low' => 5, 'close' => 8],
['date' => '2022-12-27', 'open' => 5, 'high' => 7, 'low' => 4, 'close' => 6],
// 其他日K数据...
];
// 将日K数据转换为年K数据
$yearlyK = [];
$year = '';
$open = 0;
$high = 0;
$low = PHP_INT_MAX;
$close = 0;
foreach ($dailyK as $data) {
$date = $data['date'];
$dataYear = substr($date, 0, 4);
// 如果年份发生变化,则将上一年的K线数据加入结果集
if ($year && $dataYear !== $year) {
$yearlyK[] = ['year' => $year, 'open' => $open, 'high' => $high, 'low' => $low, 'close' => $close];
$open = 0;
$high = 0;
$low = PHP_INT_MAX;
$close = 0;
}
if (!$year) {
$year = $dataYear;
$open = $data['open'];
}
// 记录最高价、最低价
$high = max($high, $data['high']);
$low = min($low, $data['low']);
// 记录最后一个交易日的收盘价
$close = $data['close'];
}
// 将最后一年的K线数据加入结果集
if (!empty($year)) {
$yearlyK[] = ['year' => $year, 'open' => $open, 'high' => $high, 'low' => $low, 'close' => $close];
}
// 输出年K数据
foreach ($yearlyK as $data) {
echo $data['year'] . ' ' . $data['open'] . ' ' . $data['high'] . ' ' . $data['low'] . ' ' . $data['close'] . "\n";
}
PHP
以上代码会把$dailyK中的日K数据转换为年K数据,并输出结果。你只需要将$dailyK替换为你所需要转换的股票日K数据即可。