What is the most effective method for identifying the initial timestamp for each day, week, or month within a collection of timestamps?

I am dealing with a lengthy array of sorted timestamps representing stock price quotes. These timestamps have minimal resolution, meaning that each timestamp is at least 1 minute bigger than the previous one. However, there can be gaps during the day, especially in pre/after-hours sessions, and no data exists for weekends and holidays. My goal is to efficiently find the timestamps that mark the start of new intervals (e.g., daily, weekly, or monthly) for charting purposes.

Currently, my approach involves looping through the array, creating a Date object from each timestamp, and comparing the .getDay() values between the previous and current array elements.

let rangeSecs = data[data.length-1] - data[0];
let rangeDays = rangeSecs / 86400;  
let spt=[]; 
const minInterval = data.slice(0,9).reduce((ac,x,i,ar)=>Math.min(ac,x-ar[i-1]))

let prevdate = new Date(data[0]*1000)

for(let i=1; i < data.length; i++){
    const curDate = new Date(data[i]*1000)
    if(rangeDays > 70 && prevdate.getMonth() != curDate.getMonth()){  
        spt.push(i)
    } else if(rangeDays <= 70 && rangeDays > 14 && prevdate.getDay() > curDate.getDay()){
        spt.push(i)
                                
    } else if(rangeDays <= 14 && prevdate.getDay() != curDate.getDay()){
        spt.push(i)
    }
    prevdate = curDate;

}

The current implementation works but is slow. I am looking for suggestions on how to optimize its performance.

I have tried skipping a certain number of "safe" timestamps based on assumptions about daily trading hours. However, this optimization is not efficient as I cannot accurately predict the number of data points per day beyond regular trading hours.

SAMPLE DATA:

[1625572800,1625573700, ... , 1627676100]

Answer №1

Forget about converting each timestamp to a Date object. Instead, pinpoint the next important date by calculating the timestamp value for it (the current date plus a week, month, or day) and avoid checking timestamps that are before that value. Make sure to check the comments on the question for more insights.

In the code snippet below, I've included some assumptions that you can modify as needed — such as ensuring the next minimum timestamp aligns with a Monday when the interval is weekly, and always starting at midnight regardless of the time increment.

For detailed insight, refer to the comments:

// Function to identify indexes of significant dates in the given data
function findIndexes(data) {
    let rangeSecs = data[data.length-1] - data[0];
    let rangeDays = rangeSecs / 86400;  // timestamps in seconds, not milliseconds
    let spt = []; // array of indexes of "timestamps of interest"

    const scaleMin = 0;
    const scaleMax = data.length - 1;

    const interval = rangeDays > 70 ? "month" : rangeDays <= 14 ? "day" : "week";
    
    /* 
    console.log(`${displayString(data[0])} to ${displayString(data[data.length-1])}, rangeDays = ${rangeDays}, interval = ${interval}`);
    */

    spt.push(scaleMin);
    let prevdate = new Date(data[0] * 1000);
    
    let minNext = getMinNext(interval, prevdate);

    for (let i = scaleMin + 1; i <= scaleMax; ++i) {
        const value = data[i];
        
        if (value >= minNext) {
            spt.push(i);
            prevdate = new Date(value * 1000);
            minNext = getMinNext(interval, prevdate);
        }
    }

    return spt;
}

// Subroutine of `findIndexes`
function getMinNext(interval, prevdate) {
    let nextTime;

    if (interval === "month") {
        nextTime = new Date(+prevdate);
        nextTime.setMonth(nextTime.getMonth() + 1);
        nextTime.setHours(0, 0, 0, 0);
    } else {
        const intervalLength = interval === "day" ? 86400 : 7 * 86400;
        nextTime = new Date(+prevdate + (intervalLength * 1000));
        nextTime.setHours(0, 0, 0, 0);
        
        if (interval === "week") {
            while (nextTime.getDay() !== 1) {
                nextTime.setDate(nextTime.getDate() - 1);
            }
        }
    }
    
    const minNext = Math.floor(nextTime / 1000);
    
    /*
    console.log(`minNext for ${displayString(prevdate)} is ${displayString(minNext)}`);
    */
    
    return minNext;
}

Try out the functionality with random data:

// Implement the examples with different intervals
let indexes;
console.log("Days:");
const daysData = getRandomData(3 * 60 * 60); // Up to 4 hour intervals
indexes = findIndexes(daysData);
console.log(indexes.map(index => new Date(daysData[index] * 1000).toLocaleString()));
/* Continue with other intervals like weeks and months... */

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Javascript - Could anyone provide a detailed explanation of the functionality of this code snippet?

Ever since joining a new company 9 months ago, I've been encountering this line of code in JavaScript. It seems to work fine and I've been incorporating it into my coding style to align with the previous developers. However, I'm not entirely ...

Modifying the size of an element with D3 when hovering with the mouse

In a previous project, I created a stacked bar chart with some interesting mouseover effects. Now, I want to take it a step further by changing the size of the rectangle that the user hovers over, returning it to its original size once they move away. My ...

Using jQuery UI to dynamically add a widget based on a specific class, rather than relying on

Exploring the world of Apache Cordova and jQueryUI is a new adventure for me. I am currently experimenting with formatting the layout of my index.html using jQueryUI. As mentioned in this section of the jQueryUI tutorial, a widget can be added using the f ...

How can React Components be imported into a website that is not built with React?

After developing a site with Node and Express, I am looking to incorporate a page built with React and JSX. As part of this process, I have installed Babel as an npm package and included React in the index.html file like so: <script src="https://un ...

Creating a form with multiple checkboxes using Material-UI components where only a single checkbox can be selected

Creating a simple form using Material-UI with checkboxes to select one option and push data to the backend on submit is the goal. The Form component structure includes: multiple options represented by checkboxes only one checkbox can be selected at a time ...

What's the best way to implement a conditional header in React?

I am looking to create a conditional display of the Header based on different pages. Specifically, I want the Header to be hidden on the Home page and shown on other pages like posts page, projects page, etc. I have been brainstorming possible solutions f ...

"Streamlining data entry with an uncomplicated HTML form input that accepts multiple values from a

As I understand it, a barcode scanner functions as nothing more than a keyboard that transmits keycode 13 after each scan. My task is straightforward: I have a basic form with only one input field and I want the ability to scan numerous barcodes and then c ...

Tabbed horizontal slider

I am trying to combine two scripts in order to create a tab-based system with a scrollbar located at the bottom of the content. I have merged the following Ajax tabs: with this slider: However, when I open the slider's tab, I am unable to move the s ...

The value stored in $_POST['valuename'] is not being retrieved

Having recently delved into ajax, I am encountering some difficulties in making it function properly. The objective of the code is to send two variables from JavaScript to PHP and then simply echo them back as a string. However, instead of receiving the e ...

How to Set Up a Simple Gulp Uglify Configuration

My objective is to compress all .js files within my project and save a minified version in the same directory. Assuming this is the structure of my project directory: project/ gulpfile.js basic.js Project/ Project.js Toolbelt. ...

Update the content of a div and refresh it when a key on the keyboard is pressed

I need to hide the images in a div when I press a key on the keyboard. How can I achieve this? <div> <span role="checkbox" aria-checked="true" tabindex="0"> <img src="checked.gif" role="presentation" alt="" /> ...

Is there a way to position one DIV behind another?

Hey, I'm working on my first project and running into some trouble with divs. I'm trying to position the firework behind the central text but can't figure it out. Can anyone lend a hand? I need to add more details in order to submit the que ...

Ensure that the three.js script remains in a fixed position on a page that can be

Is there a way to make a 3D model created with three.js have a fixed position on a scrollable page, like a background while the rest of the content scrolls normally? Are there any CSS techniques or additional script elements that can be used to achieve thi ...

Issue with Mouse Hover not functioning properly across various 3D objects

Trying to create a 3D line chart? Check it out Here Currently, the points and lines are working fine. However, I only want to detect mouse hover on the points (spheres) and not on the lines or grid. To achieve this, I have segregated all elements into dif ...

What are the additional costs associated with pthread mutexes?

I am currently working on developing a thread-safe C++ API for Linux and Solaris. My strategy involves using pthread mutexes to safeguard member variables from concurrent access by different threads. This approach requires locking and unlocking the mutex e ...

Basic AngularJS application, however I am receiving {{this is supposed to be the information}}

Building an angularjs app I have set up an asp.net mvc4 application and integrated the angularjs package using nuget. The Layout.cshtml file has been updated to look like this: <!DOCTYPE html> <html ng-app="myApp"> <head> <meta ...

Can Javascript (PWA) be used to detect fake GPS or mock GPS in applications?

Looking for a solution to prevent users from using Fake Location tools in my PWA application that gathers absence location data. Is there a method or package in JavaScript to detect the presence of Fake GPS installed on the device? ...

Steps to select an option from a drop-down menu that does not have an ID assigned

How can I interact with a drop-down element that appears after clicking on an item? <div class="field loan-selection"> <label class="field__body"> <div class="field__label">Nettokreditbetrag <!-- -->&nbs ...

Tips on how to connect the scope from a controller to a custom directive in Angular

Currently, I am delving into the world of Angular and finding myself immersed in directive lessons. However, as I engage in some practice exercises, I have encountered a stumbling block. Specifically, I have developed a custom directive with the intention ...

What is the best way to use ReactJS to remove the last 3 characters from a selected text?

How can I display text on a webpage while cutting off the last 3 characters? For example, Python%22 should be displayed as Python I attempted to use substring() but it doesn't seem to be working correctly. Any help would be greatly appreciated! rende ...