Restarting every few minutes - python-3.x

I have the following code:
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt
import sys
def stockchart(symbol):
ts = TimeSeries(key='1ORS1XLM1YK1GK9Y', output_format='pandas')
data, meta_data = ts.get_intraday(symbol=symbol, interval='1min', outputsize='full')
print (data)
I wanted to know how can i 'keep alive' so to say so that there a new request every say 5 mins for data? Is while loop the most efficient way to do this?

You mean like:
import time
while True:
ts = TimeSeries(key='1ORS1XLM1YK1GK9Y', output_format='pandas')
data, meta_data = ts.get_intraday(symbol=symbol, interval='1min', outputsize='full')
print (data)
time.sleep(300)
To achieve infinite recursion: Python "while" loops
And to wait for 5 minutes: time.sleep
Hope that answers your question!

Related

loop over a python list

I have a python list of Ids which I am calling in my function. There are around 200 ids. I would like to know what will be the best way to call these ids in chunks like I call 10 or 20 ids at a time and in next call, I call the next 20 ids and so on.. I have used multithreading here to make it faster but it seems to take lot of time. Here is the code I managed:
from concurrent.futures import ThreadPoolExecutor
import numpy as np
import datetime as dt
df = pd.ExcelFile('ids.xlsx').parse('Sheet1')
x=[]
x.append(df['external_ids'].to_list())
def download():
#client is my python sdk
dtest_df = client.datapoints.retrieve_dataframe(external_id = x[0], start=0, end="now",granularity='1m')
dtest_df = dtest_df.rename(columns = {'index':'timestamp'})
client.datapoints.insert_dataframe(dtest_df,external_id_headers = True,dropna = True)
print(dtest_df)
with ThreadPoolExecutor(max_workers=20) as executor:
future = executor.submit(download)
print(future.result())

The python program with datetime mofule

I write this code in python in order to read the minute of windows clock and recognize weather it is even or odd and do it 10 times with random sleep time between 5 to 10 seconds:
from datetime import datetime
import random
import time
wait_time = random.randint(5,11)
time.sleep(wait_time)
for i in range(10):
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
But when I run it, sleep time works ok but it show the answer just one time. I think I should write the lines in other arrangement. But I don't know how to fix it.
You need to rearrange your lines according to your own description as below. Same lines but another ordering.
from datetime import datetime
import random
import time
even=[2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,
34,36,38,40,42,44,46,48,50,52,54,56,58]
for i in range(10):
m=datetime.today().minute
if m in even:
print("It is even")
else:
print("It is odd")
wait_time = random.randint(5,11)
time.sleep(wait_time)

How to properly stop a separate thread together with shutting down a bokeh server?

I'm trying to plot a 'real time' plotting streaming some sensor data using the bokeh server. Meanwhile I want to start a separate theread to 'manipulate' the same data with some file i/o operation to the hard drive.
From multiple sources here and here, I was able to assmeble a script shown below. However when I run bokeh serve --show test.py in the command prompt, the webpage never load. And the server is just frozen. Could anyone please point out what I should do? Thank you for any help.
For simplicity, the blocking_task for the separate thread contains only a time.sleep function. The plot will show up if the last three lines are commented out (they are for the separate thread).
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.models.widgets import Button
from bokeh.layouts import column, widgetbox
import time
import numpy as np
import datetime as dt
from threading import Thread
import sys
# the function to be called by the separate thread
def blocking_task():
while True:
if stop_threads:
print('thread killed')
sys.exit()
time.sleep(0.1)
# the 'stop' button under the plotting
def button_callback():
global stop_threads
stop_threads = True
def update():
data = np.random.rand()
source.stream(dict(time=[dt.datetime.now()], data=[data]), 100)
doc = curdoc()
stop_threads = False # a global flag used for stopping the separate thread
source = ColumnDataSource(dict(time=[], data=[]))
fig = figure(x_axis_type='datetime', plot_width=800, plot_height=400)
fig.line(x='time', y='data', source=source)
button = Button(label="Stop", button_type="success")
button.on_click(button_callback)
doc.add_root(column([fig, widgetbox(button, align="center")], sizing_mode='stretch_both'))
doc.add_periodic_callback(callback=update, period_milliseconds=100)
thread = Thread(target=blocking_task)
thread.start()
thread.join() # I can comment out this line to show the streaming plot, but there is no way to stop the separate thread together with shutting down the server.
join() waits for the thread to stop before continuing execution. bokeh serve wraps the whole script in a function that is expected to return, which never happens in your case.
Try removing just the last line and setting daemon=True in the Thread constructor.
I will avoid the daemon flag according to the documentation:
Daemon threads are abruptly stopped at shutdown. Their resources (such
as open files, database transactions, etc.) may not be released
properly. If you want your threads to stop gracefully, make them
non-daemonic and use a suitable signalling mechanism such as an Event.
I will instead check the threading.main_thread().is_alive() in the while loop of the child thread
from bokeh.io import curdoc
from bokeh.models import ColumnDataSource
from bokeh.plotting import figure
from bokeh.models.widgets import Button
from bokeh.layouts import column, widgetbox
import time
import numpy as np
import datetime as dt
import threading
import sys
def blocking_task():
while threading.main_thread().is_alive():
time.sleep(0.1)
else:
print('exiting child thread')
def button_callback():
sys.exit()
def update():
data = np.random.rand()
source.stream(dict(time=[dt.datetime.now()], data=[data]), 100)
doc = curdoc()
source = ColumnDataSource(dict(time=[], data=[]))
fig = figure(x_axis_type='datetime', plot_width=800, plot_height=400)
fig.line(x='time', y='data', source=source)
button = Button(label="Stop", button_type="success")
button.on_click(button_callback)
doc.add_root(column([fig, widgetbox(button, align="center")], sizing_mode='stretch_both'))
doc.add_periodic_callback(callback=update, period_milliseconds=100)
thread = threading.Thread(target=blocking_task)
thread.start()

Capture a terminal output in real time of an python module

The python 'yfinance' module downloads the quotes of many Financial Securities in a pandas dataframe and in the meanwhile it displays a progress bar in the console. In this way:
import yfinance as yf
Tickerlist = ["AAPL","GOOG","MSFT"]
quote = yf.download(tickers=Tickerlist,period='max',interval='1d',group_by='ticker')
I would like to capture the console progress bar in real time, and the code should be this:
import sys
import subprocesss
process = subprocess.Popen(["yf.download","tickers=Tickerlist","period='max'","interval='1d'","group_by='ticker'"],stdout=quote)
while True:
out = process.stdout.read(1)
sys.stdout.write(out)
sys.stdout.flush()
I make a big mess with subprocess. I need your help! Thanks.
I have already seen all the links that deal with this topic but without being able to solve my problem.
You need two python files to do what you want.
one is yf_download.py and second is run.py
The file code looks like this and you can run it through run.py
python run.py
yf_download.py
import sys
import yfinance as yf
Tickerlist = ["AAPL","GOOG","MSFT"]
def run(period):
yf.download(tickers=Tickerlist, period=period,interval='1d',group_by='ticker')
if __name__ == '__main__':
period = sys.argv[1]
run(period)
run.py
import sys
import subprocess
process = subprocess.Popen(["python", "yf_download.py", "max"],stdout=subprocess.PIPE)
while True:
out = process.stdout.read(1)
if process.poll() is not None:
break
if out != '':
sys.stdout.buffer.write(out)
sys.stdout.flush()

Python import pygame does not play an audio

the code just print the name of the song and dont stop after he finish
my code:
import glob
import os
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
songs = glob.glob("C:\\Users\zivsi\Music\\*.mp3")
import random
song = random.choice(songs)
song_name = song.replace("C:\\Users\zivsi\Music\\", "").replace(".mp3", "")
print("song: ", song_name)
pygame.init()
pygame.mixer.music.load(song)
pygame.mixer.music.play()
while pygame.mixer.music.get_busy():
pygame.time.Clock().tick(10)
I did not use from pygame import *
because it cannot be done in def
Use pygame.mixer.music.stop() when you want to stop the music. The pygame.time.Clock().tick(10) computes the time since it was last called and stalls the program until 1/framerate (in your case framerate=10) seconds have passed. Therefore, your code will run until the song is done playing. If instead you want to pause the program for a set amount of time and stop the music from playing, use time.sleep(), which takes seconds as an argument. Possible example:
import glob
import os
import time
os.environ['PYGAME_HIDE_SUPPORT_PROMPT'] = "hide"
import pygame
songs = glob.glob("C:\\Users\zivsi\Music\\*.mp3")
import random
song = random.choice(songs)
song_name = song.replace("C:\\Users\zivsi\Music\\", "").replace(".mp3", "")
print("song: ", song_name)
pygame.init()
pygame.mixer.music.load(song)
pygame.mixer.music.play()
time.sleep(10) #sleep for 10 seconds before moving on
pygame.mixer.music.stop()
thank you. i understand now. my mistake was:
pygame.init() -
i need
pygame.mixer.init()

Resources