louisnw01 / lightweight-charts-python

Python framework for TradingView's Lightweight Charts JavaScript library.
MIT License
1.1k stars 204 forks source link

Converting chart UTC time zone to market Eastern time zone EST #418

Closed ahmedacoding closed 6 days ago

ahmedacoding commented 3 months ago

Question

Hi, in (lightweight_charts/polygon.py) when I add the conversion of UTC time to EST time zone to show it in chart it doesn't. however if I take the (get_bar_data) function and just run it to check the data , i see the data in EST but the chart still showing UTC time?! I also change it in (async def _handle_tick(ticker, data) function , but still chart showing UTC time zone.

Code example

def get_bar_data(ticker: str, timeframe: str, start_date: str, end_date: str, limit: int = 5_000):
    end_date = dt.datetime.now().strftime('%Y-%m-%d') if end_date == 'now' else end_date
    mult, span = _convert_timeframe(timeframe)
    if '-' in ticker:
        ticker = ticker.replace('-', '')

    query_url = f"/v2/aggs/ticker/{ticker}/range/{mult}/{span}/{start_date}/{end_date}?limit={limit}"
    results = _polygon_request(query_url)
    if not results:
        return None

    df = pd.DataFrame(results)
    df['t'] = pd.to_datetime(df['t'], unit='ms').dt.tz_localize('UTC')

    # Convert to Eastern Time
    eastern = pytz.timezone('US/Eastern')
    df['t'] = df['t'].dt.tz_convert(eastern)

    rename = {'o': 'open', 'h': 'high', 'l': 'low', 'c': 'close', 't': 'time'}

    if not ticker.startswith('I:'):
        rename['v'] = 'volume'

    return df[rename.keys()].rename(columns=rename)

async def _handle_tick(ticker, data):
    async def _handle_tick(ticker, data):
    lasts = _lasts[ticker]
    sec_type = _get_sec_type(ticker)

    if data['ev'] in ('Q', 'V', 'C', 'XQ'):
        if sec_type == 'forex':
            data['bp'] = data.pop('b')
            data['ap'] = data.pop('a')
        price = (data['bp'] + data['ap']) / 2 if sec_type != 'indices' else data['val']
        if abs(price - lasts['price']) < (1/(10**lasts['precision'])):
            return
        lasts['price'] = price

        if sec_type != 'indices':
            lasts['volume'] = 0

        if 't' not in data:
            lasts['time'] = pd.to_datetime(data.pop('s'), unit='ms').dt.tz_localize('UTC')
        else:
            lasts['time'] = pd.to_datetime(data['t'], unit='ms').dt.tz_localize('UTC')

        # Convert to Eastern Time
        eastern = pytz.timezone('US/Eastern')
        lasts['time'] = lasts['time'].dt.tz_convert(eastern)

    elif data['ev'] in ('A', 'CA', 'XA'):
        lasts['volume'] = data['v']
        if not lasts.get('time'):
            return
    lasts['symbol'] = ticker
    for func, args in lasts['funcs']:
        func(pd.Series(lasts), *args)
jamesbal2015 commented 3 months ago

Trying to get the program to work / run

Kind Regards

James 0432 290 300

On Sat, 6 Jul 2024 at 5:17 AM, ahmedacoding @.***> wrote:

Question

Hi, in (lightweight_charts/polygon.py) when I add the conversion of UTC time to EST time zone to show it in chart it doesn't. however if I take the (get_bar_data) function and just run it to check the data , i see the data in EST but the chart still showing UTC time?! I also change it in (async def _handle_tick(ticker, data) function , but still chart showing UTC time zone. Code example

def get_bar_data(ticker: str, timeframe: str, start_date: str, end_date: str, limit: int = 5_000): end_date = dt.datetime.now().strftime('%Y-%m-%d') if end_date == 'now' else end_date mult, span = _convert_timeframe(timeframe) if '-' in ticker: ticker = ticker.replace('-', '')

query_url = f"/v2/aggs/ticker/{ticker}/range/{mult}/{span}/{start_date}/{end_date}?limit={limit}"
results = _polygon_request(query_url)
if not results:
    return None

df = pd.DataFrame(results)
df['t'] = pd.to_datetime(df['t'], unit='ms').dt.tz_localize('UTC')

# Convert to Eastern Time
eastern = pytz.timezone('US/Eastern')
df['t'] = df['t'].dt.tz_convert(eastern)

rename = {'o': 'open', 'h': 'high', 'l': 'low', 'c': 'close', 't': 'time'}

if not ticker.startswith('I:'):
    rename['v'] = 'volume'

return df[rename.keys()].rename(columns=rename)

async def _handle_tick(ticker, data): async def _handle_tick(ticker, data): lasts = _lasts[ticker] sec_type = _get_sec_type(ticker)

if data['ev'] in ('Q', 'V', 'C', 'XQ'):
    if sec_type == 'forex':
        data['bp'] = data.pop('b')
        data['ap'] = data.pop('a')
    price = (data['bp'] + data['ap']) / 2 if sec_type != 'indices' else data['val']
    if abs(price - lasts['price']) < (1/(10**lasts['precision'])):
        return
    lasts['price'] = price

    if sec_type != 'indices':
        lasts['volume'] = 0

    if 't' not in data:
        lasts['time'] = pd.to_datetime(data.pop('s'), unit='ms').dt.tz_localize('UTC')
    else:
        lasts['time'] = pd.to_datetime(data['t'], unit='ms').dt.tz_localize('UTC')

    # Convert to Eastern Time
    eastern = pytz.timezone('US/Eastern')
    lasts['time'] = lasts['time'].dt.tz_convert(eastern)

elif data['ev'] in ('A', 'CA', 'XA'):
    lasts['volume'] = data['v']
    if not lasts.get('time'):
        return
lasts['symbol'] = ticker
for func, args in lasts['funcs']:
    func(pd.Series(lasts), *args)

— Reply to this email directly, view it on GitHub https://github.com/louisnw01/lightweight-charts-python/issues/418, or unsubscribe https://github.com/notifications/unsubscribe-auth/AWTRHNJLDDZLBJVM6GC7UFLZK3Z3VAVCNFSM6AAAAABKNVVZ5GVHI2DSMVQWIX3LMV43ASLTON2WKOZSGM4TGMBXGAYTQMY . You are receiving this because you are subscribed to this thread.Message ID: @.***>

louisnw01 commented 6 days ago

Hey @ahmedacoding,

print the values after conversion