C/C++ 布林通道指標 範例
C/C++ 布林通道指標 範例
資料來源: chatGPT35 for Chrome
Code
#include <stdio.h> #include <math.h> // 計算布林通道指標的函數 void calculateBollingerBands(double *prices, int n, int period, double *upperBand, double *lowerBand) { for (int i = 0; i < n; i++) { if (i < period - 1) { // 不足一個週期的價格數據 upperBand[i] = 0.0; lowerBand[i] = 0.0; } else { // 計算平均值和標準差 double sum = 0.0; for (int j = i - period + 1; j <= i; j++) { sum += prices[j]; } double mean = sum / period; sum = 0.0; for (int j = i - period + 1; j <= i; j++) { sum += pow(prices[j] - mean, 2); } double stdDev = sqrt(sum / period); // 計算布林通道上下限 upperBand[i] = mean + 2 * stdDev; lowerBand[i] = mean - 2 * stdDev; } } } int main() { // 假設有一組價格數據 double prices[] = {50.0, 55.0, 53.0, 60.0, 58.0, 62.0, 55.0, 48.0, 50.0, 52.0}; int n = sizeof(prices) / sizeof(prices[0]); // 設定布林通道的週期 int period = 5; // 創建用於存儲結果的陣列 double upperBand[n]; double lowerBand[n]; // 計算布林通道指標 calculateBollingerBands(prices, n, period, upperBand, lowerBand); // 輸出結果 printf("Day\tUpper Band\tLower Band\n"); for (int i = 0; i < n; i++) { printf("%d\t%f\t%f\n", i + 1, upperBand[i], lowerBand[i]); } return 0; }