baharak Al
baharak Al

Reputation: 71

how to schedule a python code to run daily?

def job():
# Define variables 
  tickers = "AAPL GOOGL"
  start = "2021-08-01"
  end = date.today()
  tickers_split = tickers.split()
  df = pd.DataFrame()
  tickers_split
  for ticker in tickers_split:
      data = pdr.get_data_yahoo(ticker, start=start, end=end, interval='d')
      df[ticker] = data['Adj Close']
  print(df.shape)
  display(df)
  df.to_csv(r'path.csv')

schedule.every().day.at("11:10").do(job)
while True:
   schedule.run_pending()
   time.sleep(1)

I have the above code to pull stock data and then save it on my local path and would like to make it run daily at specific time automatically. I am using schedule but it dsnt do what it is supposed to do. Do I need to have the code open for it to run? If thats the case, what the options are to execute python codes wo having them open or have my computer keep awake all the time?

Upvotes: 0

Views: 5874

Answers (3)

David Webster
David Webster

Reputation: 2321

The prescribed way is to put the python code in AWS Lambda and then have an AWS Cloudwatch event with a cron expression invoke the AWS Lambda on a schedule and then save the results in S3 or some data store.

Above is the cheapest option both operationally and from a cost perspective as you are only paying for it when the AWS Lambda executes.

Upvotes: 2

Kaia
Kaia

Reputation: 893

Your OS probably provides a job scheduler (an application that runs in the background and can perform these scheduling tasks for you) for this purpose.

The typical tools are cron for Mac and Linux, and windows task scheduler for Windows. You can also look into other ones, or easier-to-use wrappers that may be available.

Important to note that a job scheduler can only run when your computer is turned on. If you need a thing that can run 24/7, you might look into a cloud provider or the like, which usually provide scheduling services of their own.

Upvotes: 1

Vollkornbrot3
Vollkornbrot3

Reputation: 9

This video helped me with the same problem:

https://www.youtube.com/watch?v=aqnJvXOIr6g&ab_channel=KeithGalli

As I didn't want to keep my Laptop running I used the AWS setup. But I think this could also work with other hosting options where you can install your sheduler.

Upvotes: -1

Related Questions