Skip to content

Commit

Permalink
Merge pull request #22 from chris-hmmr/feature/add_market_state_to_ou…
Browse files Browse the repository at this point in the history
…tput

Feature/add market state to output
  • Loading branch information
chris-hmmr authored May 17, 2024
2 parents c46298c + 3b1e043 commit 136a2ce
Show file tree
Hide file tree
Showing 9 changed files with 50 additions and 9 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
node_modules
.vscode
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

All notable will be documented in this file.

## 1.0.18 - 2024-05-17
- Feature: Add optional market state property to modify output

## 1.0.17 - 2024-04-18
- Fix: Bump up node-yahoo-finance2 package

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,7 @@ terminal-stocks --help // to get help
terminal-stocks --version // to see the version
terminal-stocks -t [ticker] // to see current price information of the stock
terminal-stocks --ticker [ticker] // to see current price information of the stock
terminal-stocks --ticker -ms [ticker] // to see current price information of the stock, including market state (open/closed)
terminal-stocks -t [ticker] --historical [domain] // to see the historical price information of stock
terminal-stocks --tickers ITC.NS,INFY.NS // to get the current prices of the multiple stocks
terminal-stocks -m // to see the market summary
Expand Down
9 changes: 8 additions & 1 deletion app/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,17 @@ module.exports = function (app) {

app.get('/:tickers', function (req, res) {
const tickers = req.params.tickers.split(',').map((ticker) => ticker.trim());
const ms = req.query.ms ? req.query.ms.toLowerCase() : undefined;
var options = {};

// check to see if market state param was set
if (ms === 'true') {
options = { ms: true };
}

yahooService.getCurrentPrice(tickers)
.then((data) => {
res.send(responseTransformer.transformCurrentPrice(data));
res.send(responseTransformer.transformCurrentPrice(data, options));
}).catch((error) => {
res.send(responseTransformer.transformError(error));
});
Expand Down
8 changes: 8 additions & 0 deletions app/services/yahooService.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ function getCurrentPrice(tickers) {
var longName = (getLongName(entity)) ? getLongName(entity) : getShortName(entity);
var dayRange = getDayRange(entity);
var fiftyTwoWeekRange = getFiftyTwoWeekRange(entity);
var marketState = getMarketState(entity)

resolve({
ticker,
Expand All @@ -71,6 +72,7 @@ function getCurrentPrice(tickers) {
atTime,
dayRange,
fiftyTwoWeekRange,
marketState

})
} catch (err) {
Expand Down Expand Up @@ -163,4 +165,10 @@ function getFiftyTwoWeekRange(entity) {
if (entity.fiftyTwoWeekRange) {
return `${formatter.format(entity.fiftyTwoWeekRange.low)} - ${formatter.format(entity.fiftyTwoWeekRange.high)}`
}
}

function getMarketState(entity) {
if( entity.marketState) {
return (entity.marketState === "REGULAR") ? "open" : "closed"
}
}
24 changes: 20 additions & 4 deletions app/transformer/responseTransformer.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ module.exports = {
};

function transformChart(data) {
var time = data.timestamp.map((t) => { return new Date().toLocaleString('en-UK', {year: 'numeric', month: 'short', day: 'numeric'}) });
var time = data.timestamp.map((t) => { return new Date().toLocaleString('en-UK', { year: 'numeric', month: 'short', day: 'numeric' }) });

const screen = blessed.screen()
const line = contrib.line(
Expand Down Expand Up @@ -80,21 +80,25 @@ function transformMarketSummary(array) {
+ colors.yellow.dim(`[twitter: @imSPG] [Github: https://github.com/shweshi/terminal-stocks]\n\n`));
}

function transformCurrentPrice(data) {
function transformCurrentPrice(data, options) {
var table = new Table({
head: [
colors.yellow('Stock Name'),
colors.yellow('Current Price'),
colors.yellow('Change'),
colors.yellow('% Change'),
colors.yellow('Day Range'),
colors.yellow('52 Week Range')
colors.yellow('52 Week Range'),
],
style: {
head: []
},
});

if (options.ms === true) {
table.options.head.push(colors.yellow('Market State'))
}

for (let i = 0; i < data.length; i++) {
const hex = (data[i].change > 0) ? '008000' : 'FF0000';
table.push(
Expand All @@ -107,6 +111,11 @@ function transformCurrentPrice(data) {
showDefaultOutputIfEmpty(data[i].fiftyTwoWeekRange),
]
);

if (options.ms === true) {
table[i].push(
showMarketStateIfRequested(data[i]))
};
}

return '\n' + table.toString() + '\n' + colors.grey(colors.grey(data[0].atDate)) + '\n\n'
Expand Down Expand Up @@ -136,7 +145,7 @@ function transformHistoricalPrices(data) {
data.array.forEach((price) => {
table.push(
[
price.date.toLocaleString('en-UK', {year: 'numeric', month: 'short', day: 'numeric'}),
price.date.toLocaleString('en-UK', { year: 'numeric', month: 'short', day: 'numeric' }),
formatter.format(parseFloat(price.open).toFixed(2)),
formatter.format(parseFloat(price.high).toFixed(2)),
formatter.format(parseFloat(price.low).toFixed(2)),
Expand All @@ -162,6 +171,13 @@ function showDefaultOutputIfEmpty(data) {
return data
}

function showMarketStateIfRequested(data) {
if (!data)
return

return (data.marketState === "open") ? colors.green("open") : colors.red("closed")
}

function transformError(error) {
return `\nSorry, we couldn't find. Please check the stock ticker and provide correct one.\n\n ${error.message}`;
}
Expand Down
9 changes: 7 additions & 2 deletions bin/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
const stocksCli = require('../cli/stocksCli')

var argv = require('yargs/yargs')(process.argv.slice(2))
.usage('Usage: $0 -ticker [string] --historical [boolean]')
.example('$0 -ticker <ticker> --historical', 'returns the price information of given ticker')
.usage('Usage: $0 -ticker [string] --historical [boolean] --ms [boolean]')
.example('$0 -ticker <ticker> --historical', 'returns the price information of a given ticker')
.usage('Usage: $0 -market [boolean]')
.example('$0 -market', 'returns the market summary')
.usage('Usage: $0 --tickers [comma separated string]')
Expand All @@ -18,6 +18,7 @@ var argv = require('yargs/yargs')(process.argv.slice(2))
.describe('historical', 'To get historical price information of the stock')
.describe('json', 'To export the data as json')
.describe('csv', 'To export the data csv')
.describe('ms', 'To display the current state (open/closed) of the stock market for a ticker')
.help('h')
.alias('h', 'help')
.alias('v', 'version')
Expand All @@ -31,6 +32,10 @@ if (argv.json) {
options.export = 'csv';
}

if (argv.ms) {
options.ms = true;
}

if (argv.tickers) {
const tickers = argv.tickers.split(',');
stocksCli.fetchCurrentPrice(tickers, options);
Expand Down
2 changes: 1 addition & 1 deletion cli/stocksCli.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ function fetchCurrentPrice(tickers, options = {}) {
csvService.csvExport(data);
console.log(responseTransformer.transformExportCsvSuccess())
} else {
console.log(responseTransformer.transformCurrentPrice(data));
console.log(responseTransformer.transformCurrentPrice(data, options));
}
}).catch((error) => {
console.log(responseTransformer.transformError(error));
Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "terminal-stocks",
"version": "1.0.17",
"version": "1.0.18",
"description": "Fetch stock price information on terminal",
"main": "index.js",
"bin": {
Expand Down

0 comments on commit 136a2ce

Please sign in to comment.