Python Forum

Full Version: How to write this better?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
    
x = 50
list_of_gains = []
    while x < len(stock['Returns']) - 4:
        
        if stock['Returns'][x] > 0 and stock['Returns'][x + 1] > 0 and \
                stock['Returns'][x + 2] > 0 and stock['Returns'][x + 3] > 0:
            if stock['Volume'][x] > stock['Avg'][x] and stock['Volume'][x + 1] > stock['Avg'][x + 1] and \
                    stock['Volume'][x + 2] > stock['Avg'][x + 2] and stock['Volume'][x + 3] > stock['Avg'][x + 3]:
                    #  stock['Signals'][x + 4] = 1
                    list_of_gains.append(stock['Returns'][x + 4])
        else:
            pass
        x += 1
    return list_of_gains
Im trying to work with pandas and tried to write a way that would find if a stock was increasing 4 days in a row and has above average volume. I have the minus four in the while loop condition to keep it in range. x starts at 50 because the stock['Avg'] is a 50 day moving average of volume. I tried finding ways to write this better for a while but nothing seemed to work.
I'd start with a helper function that returns the first few items of a sublist, since that looks like a huge chunk of your code:
def take(items, n):
    return items[:n]
Then I'd start rewriting the function to use it, and use the builtin functions all and zip to compare the different metrics to try to make it clearer what I meant:
x = 50
while x < (len(stock["Returns"]) - 4):
    returns = take(stock["Returns"], x+4)
    if all(ret > 0 for ret in returns):
        volume = take(stock["Volume"], x+3)
        avg_vol = take(stock["Avg"], x+3)
        if all(vol > avg for vol, avg in zip(volume, avg_vol)):
            yield returns[-1]
    x += 1