ldc-groupe/crons/FinancialHistory.php

96 lines
2.8 KiB
PHP

<?php
/*
* Du début au 2020-02-28 données Worldtrading Datas
* Après 2020-02-28 données AlphaVantage (au 17/12/2020) datas moins sûres à priori
*/
require_once(__DIR__ . '/../public/wp/wp-load.php');
getFinancialHistoryData();
//Fonction pour récupérer les données historiques de l'action (A utiliser dans un cron toutes les nuits)
function getFinancialHistoryData()
{
global $wpdb;
$token = ALPHAVANTAGE_API_KEY;
//Get historical data for financial data
$url_historical = 'https://www.alphavantage.co/query?apikey=' . $token . '&function=TIME_SERIES_DAILY&symbol=LOUP.PA&outputsize=full';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_URL, $url_historical);
$response = curl_exec($ch);
if (!curl_errno($ch)) {
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code !== 200) {
email(MAIL_ADMIN, '[ERROR] Erreur "API" Alphavantage : getFinancialHistoryData', 'Code HTTP de l\'erreur : ' . $http_code);
die();
}
} else {
email(MAIL_ADMIN, '[ERROR] Erreur "API" Alphavantage : getFinancialHistoryData', 'Erreur cURL');
die();
}
curl_close($ch);
$history = json_decode($response, true);
if (!isset($history['Time Series (Daily)'])) {
return;
}
// Get last Day to byPass
$lastDate = $wpdb->get_results("SELECT date FROM wp_financialdata_history ORDER BY DATE DESC LIMIT 1");
if (!empty($lastDate))
$lastDate = strtotime($lastDate[0]->date);
else
$lastDate = strtotime('1995-01-01');
foreach ($history['Time Series (Daily)'] as $date => $day) {
$oDate = strtotime($date);
// Skip current day datas
if ($oDate === strtotime(date('Y-m-d')))
continue;
// Skip already in base datas
if ($oDate <= $lastDate)
continue;
$open = $day['1. open'];
$high = $day['2. high'];
$low = $day['3. low'];
$close = $day['4. close'];
$volume = $day['5. volume'];
$wpdb->insert(
'wp_financialdata_history',
[
'date' => $date,
'open' => $open,
'high' => $high,
'low' => $low,
'close' => $close,
'volume' => $volume
],
[
'%s',
'%f',
'%f',
'%f',
'%f',
'%f',
'%d'
]
);
}
}
function email($email, $subject, $message)
{
$headers[] = 'From: Groupe LDC <nepasrepondre@ldc.fr>';
wp_mail($email, $subject, $message, $headers);
}