alpacahq / alpaca-py

The Official Python SDK for Alpaca API
https://alpaca.markets/sdks/python/getting_started.html
Apache License 2.0
543 stars 135 forks source link

[Bug]: TimeFrame.value() #314

Closed vgalanti closed 1 year ago

vgalanti commented 1 year ago

Is there an existing issue for this?

Current Behavior

TimeFrame objects are not getting correctly converted for requests, for example when calling .get_stock_bars() with a StockBarsRequest object this throws an error. At the definition of the TimeFrame class, the .value(self -> str) has a typo:

return f"{self.amount}{self.unit.value}"

"unit.value" should instead be "unit_value", and this is indeed fixed by replacing this with:

return f"{self.amount}{self.unit_value}"

instead.

Expected Behavior

See above ^

SDK Version I encountered this issue in

alpaca-py v0.8.2

Steps To Reproduce

from alpaca.data.historical import StockHistoricalDataClient
from alpaca.data.requests import StockQuotesRequest, StockBarsRequest
from alpaca.data.timeframe import TimeFrame

data_client = StockHistoricalDataClient(api_key=config.API_KEY, secret_key=config.SECRET_KEY)

stock_request = StockBarsRequest(
                    symbol_or_symbols=['TSLA'], 
                    start=dt.datetime(2022, 1, 10), 
                    end=dt.datetime(2022, 1, 11), 
                    timeframe=TimeFrame(1, 'Min')
                )

data_client.get_stock_bars(stock_request)

Filled out the Steps to Reproduce section?

Anything else?

No response

haxdds commented 1 year ago

What version of python are you using?

sshcli commented 1 year ago

@ValerioGalanti in my test, it works without any problems using Alpaca 0.8.2 + Python 3.9 and 3.10

Try with the following:

from alpaca.data.timeframe import TimeFrame              
from alpaca.data.timeframe import TimeFrameUnit          

symbol = 'SPY'  
now = datetime.datetime.now(pytz.timezone('America/New_York'))
delta = datetime.timedelta(minutes = 15)
start = now - delta

sbr = StockBarsRequest(symbol_or_symbols=[symbol],timeframe=TimeFrame(1, TimeFrameUnit.Minute), start=start, end=now)
bars = data.get_stock_bars(sbr).df.sort_values(by='timestamp', ascending=False)
haxdds commented 1 year ago

Great catch @sshcli

@ValerioGalanti The issue is occuring because you are passing in the TimeFrame unit as a string Min instead of TimeFrameUnit.Minute`