Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • Home
  • SEARCH
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 876727
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 15, 20262026-05-15T11:28:48+00:00 2026-05-15T11:28:48+00:00

I’m performing a nested loop in python that is included below. This serves as

  • 0

I’m performing a nested loop in python that is included below. This serves as a basic way of searching through existing financial time series and looking for periods in the time series that match certain characteristics.

In this case there are two separate, equally sized, arrays representing the ‘close’ (i.e. the price of an asset) and the ‘volume’ (i.e. the amount of the asset that was exchanged over the period). For each period in time I would like to look forward at all future intervals with lengths between 1 and INTERVAL_LENGTH and see if any of those intervals have characteristics that match my search (in this case the ratio of the close values is greater than 1.0001 and less than 1.5 and the summed volume is greater than 100).

My understanding is that one of the major reasons for the speedup when using NumPy is that the interpreter doesn’t need to type-check the operands each time it evaluates something so long as you’re operating on the array as a whole (e.g. numpy_array * 2), but obviously the code below is not taking advantage of that.

Is there a way to replace the internal loop with some kind of window function which could result in a speedup, or any other way using numpy/scipy to speed this up substantially in native python?

Alternatively, is there a better way to do this in general (e.g. will it be much faster to write this loop in C++ and use weave)?

ARRAY_LENGTH = 500000
INTERVAL_LENGTH = 15
close = np.array( xrange(ARRAY_LENGTH) )
volume = np.array( xrange(ARRAY_LENGTH) )
close, volume = close.astype('float64'), volume.astype('float64')

results = []
for i in xrange(len(close) - INTERVAL_LENGTH):
    for j in xrange(i+1, i+INTERVAL_LENGTH):
        ret = close[j] / close[i]
        vol = sum( volume[i+1:j+1] )
        if ret > 1.0001 and ret < 1.5 and vol > 100:
            results.append( [i, j, ret, vol] )
print results
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-15T11:28:49+00:00Added an answer on May 15, 2026 at 11:28 am

    Update: (almost) completely vectorized version below in “new_function2″…

    I’ll add comments to explain things in a bit.

    It gives a ~50x speedup, and a larger speedup is possible if you’re okay with the output being numpy arrays instead of lists. As is:

    In [86]: %timeit new_function2(close, volume, INTERVAL_LENGTH)
    1 loops, best of 3: 1.15 s per loop
    

    You can replace your inner loop with a call to np.cumsum()… See my “new_function” function below. This gives a considerable speedup…

    In [61]: %timeit new_function(close, volume, INTERVAL_LENGTH)
    1 loops, best of 3: 15.7 s per loop
    

    vs

    In [62]: %timeit old_function(close, volume, INTERVAL_LENGTH)
    1 loops, best of 3: 53.1 s per loop
    

    It should be possible to vectorize the entire thing and avoid for loops entirely, though… Give me an minute, and I’ll see what I can do…

    import numpy as np
    
    ARRAY_LENGTH = 500000
    INTERVAL_LENGTH = 15
    close = np.arange(ARRAY_LENGTH, dtype=np.float)
    volume = np.arange(ARRAY_LENGTH, dtype=np.float)
    
    def old_function(close, volume, INTERVAL_LENGTH):
        results = []
        for i in xrange(len(close) - INTERVAL_LENGTH):
            for j in xrange(i+1, i+INTERVAL_LENGTH):
                ret = close[j] / close[i]
                vol = sum( volume[i+1:j+1] )
                if (ret > 1.0001) and (ret < 1.5) and (vol > 100):
                    results.append( (i, j, ret, vol) )
        return results
    
    
    def new_function(close, volume, INTERVAL_LENGTH):
        results = []
        for i in xrange(close.size - INTERVAL_LENGTH):
            vol = volume[i+1:i+INTERVAL_LENGTH].cumsum()
            ret = close[i+1:i+INTERVAL_LENGTH] / close[i]
    
            filter = (ret > 1.0001) & (ret < 1.5) & (vol > 100)
            j = np.arange(i+1, i+INTERVAL_LENGTH)[filter]
    
            tmp_results = zip(j.size * [i], j, ret[filter], vol[filter])
            results.extend(tmp_results)
        return results
    
    def new_function2(close, volume, INTERVAL_LENGTH):
        vol, ret = [], []
        I, J = [], []
        for k in xrange(1, INTERVAL_LENGTH):
            start = k
            end = volume.size - INTERVAL_LENGTH + k
            vol.append(volume[start:end])
            ret.append(close[start:end])
            J.append(np.arange(start, end))
            I.append(np.arange(volume.size - INTERVAL_LENGTH))
    
        vol = np.vstack(vol)
        ret = np.vstack(ret)
        J = np.vstack(J)
        I = np.vstack(I)
    
        vol = vol.cumsum(axis=0)
        ret = ret / close[:-INTERVAL_LENGTH]
    
        filter = (ret > 1.0001) & (ret < 1.5) & (vol > 100)
    
        vol = vol[filter]
        ret = ret[filter]
        I = I[filter]
        J = J[filter]
    
        output = zip(I.flat,J.flat,ret.flat,vol.flat)
        return output
    
    results = old_function(close, volume, INTERVAL_LENGTH)
    results2 = new_function(close, volume, INTERVAL_LENGTH)
    results3 = new_function(close, volume, INTERVAL_LENGTH)
    
    # Using sets to compare, as the output 
    # is in a different order than the original function
    print set(results) == set(results2)
    print set(results) == set(results3)
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Ask A Question

Stats

  • Questions 510k
  • Answers 510k
  • Best Answers 0
  • User 1
  • Popular
  • Answers
  • Editorial Team

    How to approach applying for a job at a company ...

    • 7 Answers
  • Editorial Team

    What is a programmer’s life like?

    • 5 Answers
  • Editorial Team

    How to handle personal stress caused by utterly incompetent and ...

    • 5 Answers
  • Editorial Team
    Editorial Team added an answer I think you can either roll your own, this tutorial… May 16, 2026 at 4:59 pm
  • Editorial Team
    Editorial Team added an answer Here's a complete solution that combines the two partial methods… May 16, 2026 at 4:59 pm
  • Editorial Team
    Editorial Team added an answer Answering my own question here, I found a solution documented… May 16, 2026 at 4:59 pm

Trending Tags

analytics british company computer developers django employee employer english facebook french google interview javascript language life php programmer programs salary

Top Members

Related Questions

Does anyone know how can I replace this 2 symbol below from the string
link Im having trouble converting the html entites into html characters, (&# 8217;) i
this is what i have right now Drawing an RSS feed into the php,
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have a French site that I want to parse, but am running into
Seemingly simple, but I cannot find anything relevant on the web. What is the
I'm trying to decode HTML entries from here NYTimes.com and I cannot figure out
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I ran into a problem. Wrote the following code snippet: teksti = teksti.Trim() teksti

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.