how to calculate weekly average stock starting on monday? in python

main.py
def calculate_weekly_avg(stocks):
    if len(stocks) % 7 != 0:
        return "Invalid number of stock entries"

    weekly_avg = []
    start = 0

    while start < len(stocks):
        weekly_avg.append(sum(stocks[start:start+7]) / 7)
        start += 7

    return weekly_avg

# Example usage
stocks = [10, 12, 13, 15, 17, 19, 20, 22, 21, 20, 23, 25, 24, 26, 27, 29]
print(calculate_weekly_avg(stocks))
406 chars
17 lines

This function calculate_weekly_avg takes a list of stock values and calculates the weekly average starting with Monday as the beginning of the week. The function first checks if the number of stock entries is divisible by 7 to ensure that there are complete weeks of data. It then calculates the average of each week's stock prices and returns a list of weekly averages.

related categories

gistlibby LogSnag