本日のお題:日経会社情報から株式情報を
以下のTypeScriptを使うと
日本郵船株の
予想配当利回りを表示できます。
//TypeScript
import * as fs from 'fs';
import * as https from 'https';
const targetUrl = 'https://www.nikkei.com/nkd/company/?scode=9101'; // 検索対象URL
const searchString = '#6g'; // 検索文字列
const outputFilename = 'output.txt'; // 出力ファイル名
const precision = 2; // 小数点以下の桁数
async function GetData() {
try {
// URLのソースを取得してテキストファイルに書き出す
const source = await fetchUrlSource(targetUrl);
await writeFile(outputFilename, source);
// テキストファイルを読み込んで検索を実行
const fileContent = fs.readFileSync(outputFilename, 'utf8');
const searchResult = fileContent.search(searchString);
if (searchResult !== -1) {
// Extract the text after the search string and find the first number
const startIndex = searchResult + searchString.length;
const regex = /([\d.]+)(?:\b|$)/; // Regex for matching numbers with optional decimals
const match = fileContent.substring(startIndex).match(regex);
if (match) {
const number = parseFloat(match[1]); // Extract and parse the number
console.log(`Rate found after "${searchString}": ${number.toFixed(2)} % `); // Format with two decimal places
} else {
console.error('No number found after the search string.');
}
} else {
console.error(`"${searchString}" not found in the file.`);
}
} catch (error) {
console.error(error);
}
}
async function fetchUrlSource(url: string): Promise<string> {
return new Promise((resolve, reject) => {
https.get(url, (res) => {
if (res.statusCode !== 200) {
reject(new Error(`URL取得に失敗しました: ${res.statusCode}`));
return;
}
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
resolve(data);
});
});
});
}
async function writeFile(filename: string, content: string): Promise<void> {
return new Promise((resolve, reject) => {
fs.writeFile(filename, content, 'utf8', (err) => {
if (err) {
reject(err);
return;
}
resolve();
});
});
}
async function readFile(filename: string): Promise<string> {
return new Promise((resolve, reject) => {
fs.readFile(filename, 'utf8', (err, data) => {
if (err) {
reject(err);
return;
}
resolve(data);
});
});
}
GetData();
このTypeScript内の
9101を、ご希望の銘柄が持つ証券コードに
変更すれば、
その会社の予想配当利回りが
得られます。