'Python: How to display the position of a counter in a variable range as a text bar (similar to the progress bar)?
I'm trying to have a dynamic display for a continuously changing positive number in a range that is also changing. For concrete example, lets imagine its representing the dynamic price of a stock where the range is its current daily range.
Say the symbol is X, which opened at $100 today, went unto $125 intra-day and is now trading at $112.5. So ideally I'd like to display it as a dynamic progress bar:
X [#### ] 112.5 [100, 125]
If the stock then goes to 130 in the same day, the same progress bar should now look like
X [########] 130 [100, 130]
(Note: I'm placing no restriction on whether the length of the progress bar should change with increase in range - all i'm asking is that the current price should be accurately represented as a percentage of the range visually.)
Any ideas what packages I should look at (I really would prefer not having to implement it from scratch!!)
Please suggest a python 3.x approach if possible as well.
Solution 1:[1]
This is a pretty simple example of how to make a status bar on the console:
import sys
import time
def progress(count, total, status=''):
bar_len = 60 # the lenght of the status bar
filled_len = int(round(bar_len * count / float(total)))
percents = round(100.0 * count / float(total), 1)
bar = '#' * filled_len + '-' * (bar_len - filled_len)
sys.stdout.write('[%s] %s%s ...%s\r' % (bar, percents, '%', status))
sys.stdout.flush()
a=0
while a < 50:
progress(a, 100)
a = a+5
time.sleep(2)
So, in the example above, the progress function is recalled in that while loop until variable a reaches 50. So, the important thing is the progress function.
I hope I helped you!
Solution 2:[2]
def progress_string(symbol, start, end, actual, bar_len=10):
fill = int(bar_len*(actual-start)/(end-start))
string = "#"*fill + " "*(bar_len-fill)
if actual<start:
string = " "*bar_len
if actual>end:
string = "#"*bar_len
return "%s [%s] %.2f [%i, %i]"%(symbol, string, actual, start, end)
### TEST ###
START = 100
END = 125
X = 100
while X<=END:
X+=.001
time.sleep(.001)
sys.stdout.flush()
print(progress_string("X", START, END, X, bar_len=25), end="\r")
This will also replace the progress bar each time.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | B. Bogdan |
| Solution 2 |
