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

  • SEARCH
  • Home
  • 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 6943825
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 27, 20262026-05-27T13:12:24+00:00 2026-05-27T13:12:24+00:00

So far this is my solution. I wonder if there is some more elegant/efficient

  • 0

So far this is my solution. I wonder if there is some more elegant/efficient way?

import datetime as dt

example = {dt.datetime(2008, 1, 1) : 5, dt.datetime(2008, 1, 2) : 6, dt.datetime(2008, 1, 3) : 7, dt.datetime(2008, 1, 4) : 9, dt.datetime(2008, 1, 5) : 12, 
dt.datetime(2008, 1, 6) : 15, dt.datetime(2008, 1, 7) : 20, dt.datetime(2008, 1, 8) :     22, dt.datetime(2008, 1, 9) : 25, dt.datetime(2008, 1, 10) : 35} 

def calculateMovingAverage(prices, period):
    #calculates the moving average between each datapoint and two days before (usually 3! datapoints     included)
    average_dict = {}
    for price in prices:
        pricepoints = [prices[x] for x in prices.keys() if price - dt.timedelta(period) <= x <= price]
        average = reduce(lambda x, y: x + y, pricepoints) / len(pricepoints)
        average_dict[price] = average
    return average_dict

print calculateMovingAverage(example, 2)

I am not sure, if I should use list-comprehension here.

There is probably some function for this somewhere, but I didn’t find it.

  • 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-27T13:12:24+00:00Added an answer on May 27, 2026 at 1:12 pm

    If you’re looking for other interesting ways to solve the problem, here is an answer using itertools:

    import datetime as dt
    from collections import deque
    from itertools import tee, islice, izip
    
    def dayiter(start, end):
        one = dt.timedelta(days=1)
        day = start
        while day <= end:
            yield day
            day += one
    
    def moving_average(mapping, window, dft=0):
        n = float(window)
        t1, t2 = tee(dayiter(min(mapping), max(mapping)))
        s = sum(mapping.get(day, dft) for day in islice(t2, window))
        yield s / n
        for olddate, newdate in izip(t1, t2):
            oldvalue = mapping.get(olddate, dft)
            newvalue = mapping.get(newdate, dft)
            s += newvalue - oldvalue
            yield s / n
    
    example = {dt.datetime(2008, 1, 1) : 5, dt.datetime(2008, 1, 2) : 6, dt.datetime(2008, 1, 3) : 7, dt.datetime(2008, 1, 4) : 9, dt.datetime(2008, 1, 5) : 12,
    dt.datetime(2008, 1, 6) : 15, dt.datetime(2008, 1, 7) : 20, dt.datetime(2008, 1, 8) :     22, dt.datetime(2008, 1, 9) : 25, dt.datetime(2008, 1, 10) : 35}
    
    for ma in moving_average(example, window=3):
        print ma
    

    The ideas involved are:

    • Use a simple generator to make a date iterator that loops over consecutive days from the lowest to the highest.

    • Use itertools.tee to construct a pair of iterators over the oldest data and the newest data (the front of the data window and the back).

    • Keep a running sum in a variable s. On each iteration, update s by subtracting the oldest value and adding the newest value.

    • This solution is space efficient (it keeps no more than window values in memory) and it is time efficient, one addition and one subtraction for each day regardless of the size of the window.

    • Handle missing days by defaulting to zero. There are other strategies that could be used for missing days (like using the current moving average as a default or adjusting n up and down to reflect the number of actual data points in the window).

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I wonder if someone knows if there is a pre-made solution for this: I
Thanks to everyone out there helping newbies like me. So far I have this:
I'm kind of new to Python and I wonder if there is a way
I need some help to tweak this regular expression: $content = 'more <a href=http://www.test.com>test</a>
I wonder if there exists another solution, to insert localized extension meta-tags automatically without
I've been looking for solutions to this problem for far too long considering how
I need a variable to hold results retrieved from the database. So far this
I got this far: :~ curl -u username:password -d status=new_status http://twitter.com/statuses/update.xml Now, how can
After cobbling together a few questions I've managed to get this far to showing
I tried this so far: <?php $error = ; $conn = pg_connect(host=localhost dbname=brittains_db user=brittains

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.