Python Forum
How to write this better?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to write this better?
#1
    
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.
Reply
#2
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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020