Google Colab、Google Sheets、ロリポップを使用した為替予測サイトの作成:初心者向けガイド

IT

こんにちは!今回は、Google Colab、Google Sheets、そしてロリポップのレンタルサーバーを使って、為替予測の結果を表示するウェブサイトを作成する方法を、初心者の方にも分かりやすく解説します。

 

1. システム概要

まず、私たちが作成するシステムの概要を理解しましょう:

1. Google Colabで為替予測モデルを実行し、その結果をGoogle Sheetsに保存します。
2. ロリポップのレンタルサーバー上のPHPスクリプトが、Google Sheetsから最新の予測結果を取得します。
3. 取得した結果をウェブページに表示します。
4. このプロセスは毎日22時から23時59分の間で1分ごとに更新されます。

それでは、各ステップを詳しく見ていきましょう!

 

2. Google Colab側の設定

2.1 Google Colabの準備

1. Googleアカウントにログインし、Google Colabを開きます(https://colab.research.google.com/)。
2. 新しいノートブックを作成します。

 

2.2 必要なライブラリのインストールとインポート

以下のコードをColabのセルに貼り付けて実行します:

 

# Google Driveをマウント
from google.colab import drive
drive.mount('/content/drive')

# 必要なライブラリのインストール
!pip install pandas numpy scikit-learn tensorflow matplotlib requests tqdm joblib
!pip install --upgrade --no-cache-dir git+https://github.com/rongardF/tvdatafeed.git
!pip install mplfinance

# ライブラリのインポート
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import MinMaxScaler
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import LSTM, Dense, Dropout
import matplotlib.pyplot as plt
import requests
import zipfile
import os
from datetime import datetime, timedelta
from tqdm import tqdm
import logging
import joblib

 

2.3 為替データの取得と前処理

為替データを取得し、前処理を行うための関数を定義します:

def download_extract_and_convert_hst(currency_pair, hst_dir, force_download=False):
# ... (この関数の詳細は長いため、省略します。必要に応じて完全なコードを提供できます。)

def read_csv_file(file_path, start_date, end_date):
# ... (同上)

def calculate_rsi(prices, window=14):
# ... (同上)

def create_sequences(X, y, time_steps=10):
# ... (同上)

 

2.4 モデルの構築と訓練

LSTMモデルを構築し、訓練を行います:

# データの準備
currency_pair = 'GBPJPY'
hst_dir = '/content/drive/MyDrive/forex_data'
start_date = '2023-01-01'
end_date = '2023-12-31'

csv_file = download_extract_and_convert_hst(currency_pair, hst_dir)
df = read_csv_file(csv_file, start_date, end_date)

# 特徴量エンジニアリング
df['returns'] = df['close'].pct_change()
df['ma5'] = df['close'].rolling(window=5).mean()
df['ma20'] = df['close'].rolling(window=20).mean()
df['rsi'] = calculate_rsi(df['close'])
df['target'] = np.where(df['close'].shift(-3) > df['close'], 1, 0)

# データの準備
features = ['returns', 'ma5', 'ma20', 'rsi']
X = df[features].dropna().values
y = df['target'].dropna().values

scaler = MinMaxScaler()
X_scaled = scaler.fit_transform(X)

time_steps = 10
X_seq, y_seq = create_sequences(X_scaled, y, time_steps)

# データの分割
X_train, X_test, y_train, y_test = train_test_split(X_seq, y_seq, test_size=0.2, random_state=42)

# モデルの構築
model = Sequential([
LSTM(50, return_sequences=True, input_shape=(time_steps, len(features))),
Dropout(0.2),
LSTM(50, return_sequences=False),
Dropout(0.2),
Dense(1, activation='sigmoid')
])

model.compile(optimizer='adam', loss='binary_crossentropy', metrics=['accuracy'])

# モデルの訓練
history = model.fit(
X_train, y_train,
epochs=10,
batch_size=32,
validation_split=0.2,
callbacks=[tf.keras.callbacks.EarlyStopping(patience=3, restore_best_weights=True)]
)

# モデルの評価
test_loss, test_accuracy = model.evaluate(X_test, y_test)
print(f"Test accuracy: {test_accuracy:.4f}")

 

2.5 結果のGoogle Sheetsへの保存

訓練したモデルを使用して予測を行い、結果をGoogle Sheetsに保存します:

from google.colab import auth
from google.auth import default
from googleapiclient.discovery import build

# Google認証
auth.authenticate_user()
creds, _ = default()

# Google Sheetsサービスの初期化
service = build('sheets', 'v4', credentials=creds)

# Google SheetsのIDとレンジを設定
SPREADSHEET_ID = 'あなたのスプレッドシートID'
RANGE_NAME = 'Sheet1!A:F'

# 予測結果をGoogle Sheetsに書き込む関数
def write_to_sheets(results):
body = {
'values': results
}
service.spreadsheets().values().append(
spreadsheetId=SPREADSHEET_ID, range=RANGE_NAME,
valueInputOption='USER_ENTERED', body=body).execute()

# 予測と結果の保存
latest_data = get_latest_data('GBPJPY', 'FX_IDC', Interval.in_1_minute, 180)
# ... (予測ロジックを実装)
results = [['GBPJPY', last_time, f'{last_close:.3f}', f'{prediction:.4f}', prediction_result, now.strftime('%Y-%m-%d %H:%M:%S')]]
write_to_sheets(results)

 

3. Google Sheets側の設定

1. Google Driveで新しいスプレッドシートを作成します。
2. 以下のカラムを設定します:
A: 予測銘柄
B: 予測起点時間
C: 最終確定足の終値
D: 予測確率
E: 予測結果(上昇/下降)
F: 予測実行時間
3. スプレッドシートのIDをコピーし、上記のPythonスクリプトの`SPREADSHEET_ID`変数に設定します。

 

4. ロリポップのレンタルサーバー側の設定

4.1 PHPスクリプトの作成

以下の内容で`index.php`ファイルを作成します:

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

require_once __DIR__ . '/vendor/autoload.php';

use Google\Client;
use Google\Service\Sheets;

try {
$client = new Client();
$client->setApplicationName('Google Sheets API PHP Quickstart');
$client->setScopes([Sheets::SPREADSHEETS_READONLY]);
$client->setAuthConfig(__DIR__ . '/credentials.json');
$client->setAccessType('offline');

$service = new Sheets($client);
$spreadsheetId = 'あなたのスプレッドシートID';
$range = 'Sheet1!A2:F';
$response = $service->spreadsheets_values->get($spreadsheetId, $range);
$values = $response->getValues();

if (empty($values)) {
throw new Exception('データが見つかりません。');
}

$latest_prediction = end($values);
$total_predictions = count($values);
$correct_predictions = 0;

date_default_timezone_set('Asia/Tokyo');

foreach ($values as $row) {
if (count($row) >= 6) {
$prediction_time = new DateTime($row[1]);
$actual_time = new DateTime($row[5]);
$time_diff = $prediction_time->diff($actual_time);

if ($time_diff->i >= 3) {
$predicted_direction = $row[4] === '上昇' ? 1 : 0;
$actual_direction = $row[2] < $latest_prediction[2] ? 1 : 0;

if ($predicted_direction === $actual_direction) {
$correct_predictions++;
}
}
}
}

$accuracy = $total_predictions > 0 ? ($correct_predictions / $total_predictions) * 100 : 0;

} catch (Exception $e) {
$error_message = 'エラーが発生しました: ' . $e->getMessage();
}
?>

<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>為替予測結果</title>
<style>
body { font-family: Arial, sans-serif; line-height: 1.6; margin: 0; padding: 20px; }
.container { max-width: 800px; margin: 0 auto; }
h1 { color: #333; }
.prediction-info { background: #f4f4f4; padding: 20px; border-radius: 5px; }
.prediction-info p { margin: 10px 0; }
.accuracy-info { margin-top: 20px; }
</style>
</head>
<body>
<div class="container">
<h1>為替予測結果</h1>
<?php if (isset($error_message)): ?>
<p style="color: red;"><?php echo htmlspecialchars($error_message); ?></p>
<?php else: ?>
<div class="prediction-info">
<p>予測銘柄: <?php echo htmlspecialchars($latest_prediction[0]); ?></p>
<p>予測起点時間: <?php echo htmlspecialchars($latest_prediction[1]); ?></p>
<p>最終確定足の終値: <?php echo htmlspecialchars($latest_prediction[2]); ?></p>
<p>予測結果: <?php echo htmlspecialchars($latest_prediction[4]); ?></p>
<p>予測確率: <?php echo htmlspecialchars($latest_prediction[3]); ?></p>
<p>予測実行時間: <?php echo htmlspecialchars($latest_prediction[5]); ?></p>
</div>
<div class="accuracy-info">
<h2>予測精度統計</h2>
<p>予測回数: <?php echo $total_predictions; ?></p>
<p>正解率: <?php echo number_format($accuracy, 2); ?>%</p>
</div>
<?php endif; ?>
</div>
<script>
setTimeout(function(){ location.reload(); }, 60000); // 1分ごとにページを更新
</script>
</body>
</html>

 

4.2 Google Sheets APIの設定

1. Google Cloud Consoleでプロジェクトを作成し、Google Sheets APIを有効にします。
2. サービスアカウントを作成し、JSONキーをダウンロードします。
3. ダウンロードしたJSONキーを`credentials.json`としてサーバーにアップロードします。
4. Google SheetsのIAM設定で、サービスアカウントのメールアドレスに閲覧権限を付与します。

 

4.3 必要なライブラリのインストール

ローカル環境で以下のコマンドを実行し、必要なライブラリをインストールします:

composer require google/apiclient:^2.0

4.4 ファイルのアップロード

FTPクライアント(FileZillaなど)を使用して、以下のファイルをサーバーにアップロードします:

– index.php
– credentials.json
– vendor/ ディレクトリ(Composerでインストールされた依存関係)
– composer.json
– composer.lock

 

4.5 .htaccessファイルの作成

以下の内容で`.htaccess`ファイルを作成し、サーバーにアップロードします:

AddHandler application/x-httpd-php74 .php
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule ^$ index.php [L]
</IfModule>
<Files credentials.json>
Order allow,deny
Deny from all
</Files>

 

5. トラブルシューティング

PHPファイルが実行されずにダウンロードされる場合は、以下の手順を試してください:

1. .htaccessファイルに以下の行を追加:

AddType application/x-httpd-php .php

2. PHPのエラー表示を有効にする:

ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

3. シンプルなテストファイル(test.php)を作成:

<?php
phpinfo();
?>

4. ファイルのパーミッションを確認(644が推奨)

5. ロリポップのコントロールパネルでPHPが有効になっているか確認

6. サーバーのエラーログを確認

問題が解決しない場合は、ロリポップのサポートに連絡してください。

 

6. セキュリティ上の注意点

– credentials.jsonファイルはウェブルートの外に配置し、.htaccessで保護することをお勧めします。
– 本番環境では、エラー表示を無効にしてください。

以上で、Google Colab、Google Sheets、そしてロリポップのレンタルサーバーを使用した為替予測サイトの作成手順が完了しました。ここからは、さらに詳細な説明と追加のヒントを提供します。

 

7. サイトの動作確認

サイトをアップロードした後、以下の手順で動作を確認してください:

  1. ブラウザでサイトにアクセスします(例:http://あなたのドメイン.com/index.php)。
  2. 為替予測結果が正しく表示されているか確認します。
  3. 1分後にページが自動更新されるか確認します。
  4. エラーメッセージが表示される場合は、そのメッセージを注意深く読み、問題を特定します。

8. 定期的な更新の設定

Google Colabは無料版では自動実行ができないため、以下の方法で擬似的に定期実行を実現します:

  1. Google Colabのスクリプト最後に以下のコードを追加:
import time

while True:
main() # メイン処理を行う関数
time.sleep(60) # 1分待機
  1. 毎日22時頃に手動でスクリプトを開始し、0時前に停止します。

より自動化したい場合は、Google Cloud FunctionsやAWS Lambdaなどのサーバーレスサービスの利用を検討してください。

 

9. パフォーマンスの最適化

サイトのパフォーマンスを向上させるために、以下の点を考慮してください:

  1. PHP OpCache の有効化: ロリポップの管理画面でOpCacheを有効にします。
  2. ブラウザキャッシュの活用: .htaccessファイルに以下の行を追加:
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType text/css "access plus 1 week"
ExpiresByType application/javascript "access plus 1 week"
ExpiresByType image/gif "access plus 1 month"
ExpiresByType image/jpeg "access plus 1 month"
ExpiresByType image/png "access plus 1 month"
</IfModule>
  1. GZip圧縮の有効化: .htaccessファイルに以下の行を追加:
<IfModule mod_deflate.c>
AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css application/javascript
</IfModule>

10. セキュリティの強化

  1. HTTPS の使用: ロリポップの管理画面でSSL証明書を有効にし、HTTPSを使用します。
  2. Content Security Policy (CSP) の設定: index.phpファイルのヘッダーに以下を追加:
header("Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline';");
  1. クロスサイトスクリプティング (XSS) 対策: すべてのユーザー入力に対してhtmlspecialchars()関数を使用していることを確認します。
  2. SQL インジェクション対策: データベースを使用する場合は、プリペアドステートメントを使用します。

 

11. コードの保守性向上

  1. 設定ファイルの分離: データベース接続情報やAPIキーなどの設定を別ファイル(例:config.php)に分離します。
  2. 関数の分離: 共通で使用する関数を別ファイル(例:functions.php)にまとめます。
  3. エラーログの活用: PHPのエラーログを有効にし、定期的にチェックします。
ini_set('log_errors', 1);
ini_set('error_log', '/path/to/error.log');

12. ユーザビリティの向上

  1. レスポンシブデザインの適用: CSSメディアクエリを使用して、モバイルデバイスでも見やすいデザインにします。
  2. データの可視化: Chart.jsなどのライブラリを使用して、予測結果をグラフ化します。
  3. 多言語対応: PHPのgettextを使用して、複数言語に対応させます。

 

13. 今後の拡張性

  1. ユーザー認証システムの追加: 予測結果を登録ユーザーのみに公開する機能を実装します。
  2. APIの提供: 予測結果をJSON形式で提供するAPIを実装します。
  3. 機械学習モデルの改善: 定期的にモデルを再学習し、精度を向上させます。

 

結論

これで、Google Colab、Google Sheets、ロリポップを使用した為替予測サイトの作成手順が完了しました。この過程で、データ分析、機械学習、ウェブ開発、APIの利用など、多岐にわたる技術を学ぶことができました。

サイトの運用を始めたら、定期的にパフォーマンスと精度をチェックし、必要に応じて改善を行ってください。また、為替予測は不確実性を伴うため、この結果を投資判断の唯一の基準にしないよう、ユーザーに注意を促すことも重要です。

今後も継続的に学習と改善を重ね、より高度で信頼性の高いシステムを目指してください。頑張ってください!

コメント

タイトルとURLをコピーしました