Untitled

mail@pastecode.io avatar
unknown
plain_text
24 days ago
1.6 kB
8
Indexable
Never
    async def get_underlying_bars(self, underlying, start_date, end_date, interval = 60000):
        endpoint = "hist/stock/ohlc?root=" + str(underlying) + "&start_date=" + str(start_date) + "&end_date=" + str(end_date) + "&ivl=" + str(interval)
        data = await self.get(endpoint, headers=self.headers)
        schema = [
            ('ms_of_day', pl.Float64), 
            ('open', pl.Float64), 
            ('high', pl.Float64), 
            ('low', pl.Float64), 
            ('close', pl.Float64), 
            ('volume', pl.Float64), 
            ('count', pl.Float64), 
            ('date', pl.Utf8), 
        ]
        if not data or 'response' not in data:
            return pl.DataFrame([], schema=schema)
        pd_df = pd.DataFrame(data['response'])
        df = pl.DataFrame(
            pd_df, 
            schema=schema
        )
        df = df.with_columns(
            symbol=pl.lit(underlying),
            timestamp=pl.struct(['date', 'ms_of_day']).apply(lambda x: datetime.strptime(x['date'], "%Y%m%d").timestamp() + x['ms_of_day'] / 1000.0),
            date=pl.col('date').apply(lambda x: x[0:4] + '-' + x[4:6] + '-' + x[6:8]),
            close=pl.col('close').apply(lambda x: None if x == 0 else x)
        )
        df = df.with_columns(
            timestamp=pl.col('timestamp').apply(lambda x: datetime.fromtimestamp(x).strftime("%Y-%m-%d %H:%M:%S")),
            close_log_return=pl.col('close').apply(lambda x: np.log(x)) - pl.col('close').shift(1).over('date').apply(lambda x: np.log(x))
        )

        return df
Leave a Comment