Problem Description
Solution
To set your algorithm to run on New York time in QuantConnect, you must use the set_time_zone method within the initialize function of your algorithm class.
By default, LEAN algorithms run in Coordinated Universal Time (UTC). Changing the time zone will adjust the self.time property, log timestamps, and scheduled event triggers to match the specified zone.
Implementation
You can set the time zone using the TimeZones constant or a standard IANA time zone string (e.g., "America/New_York").
from AlgorithmImports import *
class TimeZoneAlgorithm(QCAlgorithm):
def initialize(self):
# Set the start and end dates
self.set_start_date(2023, 1, 1)
self.set_end_date(2023, 12, 31)
# Set the algorithm time zone to New York
self.set_time_zone(TimeZones.NEW_YORK)
# Alternatively, you can use the string representation:
# self.set_time_zone("America/New_York")
self.add_equity("SPY", Resolution.MINUTE)
def on_data(self, data):
# self.time will now reflect New York time
if self.time.hour == 9 and self.time.minute == 31:
self.log(f"Market Open at: {self.time}")
Key Considerations
- Default Behavior: If you do not call
set_time_zone, the algorithm defaults to UTC. - Data Time vs. Algorithm Time: This setting changes the algorithm's clock (
self.time). However, financial data is still stored and accessed based on the exchange's time zone or UTC depending on the data source, though LEAN handles the synchronization automatically. - Scheduled Events: When using
self.schedule.on(...), the time rules will be evaluated relative to the time zone you have configured.
Q&A
Q: Does setting the time zone affect how data is imported?
A: No, the underlying data is stored in its native format (often UTC or exchange time). set_time_zone only affects the "wall clock" time of your algorithm loop and logging.
Q: Can I change the time zone in the middle of a backtest?
A: No, the time zone must be set once inside the initialize method and cannot be changed during execution.
Q: What is the difference between TimeZones.NEW_YORK and TimeZones.NewYork?
A: In the new PEP8 Python API, constants are generally capitalized (e.g., TimeZones.NEW_YORK). However, the older C#-style TimeZones.NewYork is often still supported for backward compatibility. It is recommended to use the PEP8 style for new Python projects.