首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

基於 pChart 實現 PHP 股票趨勢圖與成交量柱狀圖生成

     編輯:PHP 相關知識

基於 pChart 實現 PHP 股票趨勢圖與成交量柱狀圖生成

利用強大的 pChart 圖表庫,從資料庫讀取股票歷史數據,動態生成專業級 K 線趨勢圖與成交量柱狀圖,支援中英文切換、時間範圍篩選、自適應縮放等功能。

核心功能特性

  • 雙圖表模式:趨勢線圖(股價)+ 柱狀圖(成交量)
  • 多語言支援:繁體/簡體中文字體自動切換
  • 參數化查詢:股票代碼、時間區間、顯示模式全可控
  • 智能坐標軸:自動計算價格區間、時間標籤稀疏顯示避免重疊
  • 視覺增強:昨日收盤價基準線、透明度區域填充、圖例說明

關鍵實作邏輯

1. 參數解析與資料查詢

$type = $_GET['type'] ?? 'line';      // line|bar
$showTxt = ($_GET['txt'] ?? 0) == 1;
$lang = in_array($_GET['lang'] ?? '', ['cn','hk']) ? $_GET['lang'] : 'hk';
$id = (int)($_GET['id'] ?? 1);

$where = "WHERE stock_no = $id";
if (!empty($_GET['min'])) $where .= " AND created >= " . (int)$_GET['min'];
if (!empty($_GET['max'])) $where .= " AND created <= " . (int)$_GET['max'];
$where .= " ORDER BY created";

$sth = $dbh->prepare("SELECT * FROM $tb_name $where");
$sth->execute();
$results = $sth->fetchAll(PDO::FETCH_ASSOC);

2. 數據預處理:時間標籤稀疏化

foreach ($results as $k => $v) {
    $prices[] = $v['current_price'];
    $volumes[] = $v['volume'];
    // 僅每 4 個點顯示時間標籤,避免 X 軸擁擠
    $times[] = ($k % 4 === 0) ? $v['created'] : null;
}

3. 趨勢線圖繪製核心

$myData = new pData();
$myData->addPoints(array_fill(0, $count, 130), 'BaseLine'); // 昨日收盤價基準線
$myData->addPoints($prices, 'Price');
$myData->setPalette('BaseLine', ['R'=>51,'G'=>114,'B'=>178]);
$myData->setPalette('Price', ['R'=>0,'G'=>255,'B'=>0]);

$myData->addPoints($times, 'Time');
$myData->setAbscissa('Time');
$myData->setXAxisDisplay(AXIS_FORMAT_TIME, 'H:i');

$picture = new pImage(480, 300, $myData);
$picture->setGraphArea(10, 40, 440, 260);

// 手動設定 Y 軸範圍(最小-2 到 最大+2)
$picture->drawScale([
    'Mode' => SCALE_MODE_MANUAL,
    'ManualScale' => [0 => ['Min' => $minPrice-2, 'Max' => $maxPrice+2]],
    'GridR' => 200, 'GridG' => 200, 'GridB' => 200,
]);

$picture->drawLineChart();  // 繪製價格線
$myData->setSerieDrawable('BaseLine', false);
$picture->drawAreaChart(['ForceTransparency' => 15]); // 填充區域

4. 成交量柱狀圖繪製

$myData->addPoints($volumes, 'Volume');
$myData->setPalette('Volume', ['R'=>51,'G'=>114,'B'=>178]);
$picture = new pImage(480, 200, $myData);
$picture->setGraphArea(50, 20, 450, 180);
$picture->drawScale(['Mode' => SCALE_MODE_START0, 'GridR'=>200,'GridG'=>200,'GridB'=>200]);
$picture->drawBarChart();

// 總成交量圖例
$totalVol = array_sum($volumes);
$myData->setSerieDescription('Volume', "總成交量:$totalVol");
$picture->drawLegend(300, 9, ['Style'=>LEGEND_NOBORDER, 'Mode'=>LEGEND_HORIZONTAL]);

部署注意事項

  • 需安裝 php-gd 擴展並確保 FreeType 支援
  • 字體文件:fonts/zh_hk.ttc、fonts/zh_cn.ttf、fonts/en_us.ttf 需實際存在
  • 資料表結構需含 stock_no、current_price、volume、created 欄位
  • 生產環境建議加入快取機制(如 Redis 存圖片二進制),避免重複渲染
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved