Skip to content

Commit 1aba0f0

Browse files
authored
Remove marketdata v1 functions (#590)
* Remove marketdata v1 functions * update README
1 parent 4b87893 commit 1aba0f0

File tree

8 files changed

+10
-846
lines changed

8 files changed

+10
-846
lines changed

README.md

Lines changed: 4 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -266,7 +266,7 @@ API Version now defaults to 'v2', however, if you still have a 'v1' account, you
266266

267267
The Alpaca API requires API key ID and secret key, which you can obtain from the
268268
web console after you sign in. You can pass `key_id` and `secret_key` to the initializers of
269-
`REST` or `StreamConn` as arguments, or set up environment variables as
269+
`REST` or `Stream` as arguments, or set up environment variables as
270270
outlined below.
271271

272272
### REST
@@ -370,20 +370,6 @@ api.submit_order(
370370

371371
---
372372

373-
#### Debugging
374-
Websocket exceptions may occur during execution.
375-
It will usually happen during the `consume()` method, which basically is the
376-
websocket steady-state.<br>
377-
exceptions during the consume method may occur due to:
378-
- server disconnections
379-
- error while handling the response data
380-
381-
We handle the first issue by reconnecting the websocket every time there's a disconnection.
382-
The second issue, is usually a user's code issue. To help you find it, we added a flag to the
383-
StreamConn object called `debug`. It is set to False by default, but you can turn it on to get a more
384-
verbose logs when this exception happens.
385-
Turn it on like so `StreamConn(debug=True)`
386-
387373
## Logging
388374
You should define a logger in your app in order to make sure you get all the messages from the different components.<br>
389375
It will help you debug, and make sure you don't miss issues when they occur.<br>
@@ -408,15 +394,15 @@ The steps to execute this are:
408394

409395
* Run the Alpaca Proxy Agent as described in the project's README
410396
* Define a new environment variable: `DATA_PROXY_WS` set to the address of the proxy agent. (e.g: `DATA_PROXY_WS=ws://127.0.0.1:8765`)
411-
* If you are using the Alpaca data stream, make sure to initiate the StreamConn object with the container's url: `data_url='http://127.0.0.1:8765'`
397+
* If you are using the Alpaca data stream, make sure to initiate the Stream object with the container's url: `data_url='http://127.0.0.1:8765'`
412398
* Execute your algorithm. It will connect to the Alpaca servers through the proxy agent, allowing you to execute multiple strategies
413399

414400

415401
## Raw Data vs Entity Data
416-
By default the data returned from the api or streamed via StreamConn is wrapped with an Entity object for ease of use. Some users may prefer working with vanilla python objects (lists, dicts, ...). You have 2 options to get the raw data:
402+
By default the data returned from the api or streamed via Stream is wrapped with an Entity object for ease of use. Some users may prefer working with vanilla python objects (lists, dicts, ...). You have 2 options to get the raw data:
417403

418404
* Each Entity object as a `_raw` property that extract the raw data from the object.
419-
* If you only want to work with raw data, and avoid casting to Entity (which may take more time, casting back and forth) you could pass `raw_data` argument to `Rest()` object or the `StreamConn()` object.
405+
* If you only want to work with raw data, and avoid casting to Entity (which may take more time, casting back and forth) you could pass `raw_data` argument to `Rest()` object or the `Stream()` object.
420406

421407
## Support and Contribution
422408

alpaca_trade_api/__init__.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,3 @@
33
from .rest import REST, TimeFrame, TimeFrameUnit # noqa
44
from .rest_async import AsyncRest # noqa
55
from .stream import Stream # noqa
6-
from .stream2 import StreamConn # noqa

alpaca_trade_api/entity.py

Lines changed: 4 additions & 77 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,7 @@ class Order(Entity):
6464
Entity properties:
6565
https://alpaca.markets/docs/api-documentation/api-v2/orders/#order-entity
6666
"""
67+
6768
def __init__(self, raw):
6869
super().__init__(raw)
6970
try:
@@ -95,6 +96,7 @@ class Bar(Entity):
9596
https://alpaca.markets/docs/api-documentation/api-v2/market-data/bars/
9697
#bars-entity
9798
"""
99+
98100
def __getattr__(self, key):
99101
if key == 't':
100102
val = self._raw[key[0]]
@@ -135,29 +137,6 @@ def df(self):
135137
return self._df
136138

137139

138-
class BarSet(dict):
139-
def __init__(self, raw):
140-
for symbol in raw:
141-
self[symbol] = Bars(raw[symbol])
142-
self._raw = raw
143-
144-
@property
145-
def df(self):
146-
'''## Experimental '''
147-
if not hasattr(self, '_df'):
148-
dfs = []
149-
for symbol, bars in self.items():
150-
df = bars.df.copy()
151-
df.columns = pd.MultiIndex.from_product(
152-
[[symbol, ], df.columns])
153-
dfs.append(df)
154-
if len(dfs) == 0:
155-
self._df = pd.DataFrame()
156-
else:
157-
self._df = pd.concat(dfs, axis=1)
158-
return self._df
159-
160-
161140
class _Timestamped(object):
162141
_tskeys = ('timestamp',)
163142

@@ -174,60 +153,6 @@ class _NanoTimestamped(_Timestamped):
174153
_unit = 'ns'
175154

176155

177-
class _MilliTimestamped(_Timestamped):
178-
_unit = 'ms'
179-
180-
181-
class Agg(_MilliTimestamped, Entity):
182-
"""
183-
Entity properties:
184-
https://alpaca.markets/docs/api-documentation/api-v2/market-data/streaming/
185-
"""
186-
_tskeys = ('timestamp', 'start', 'end')
187-
188-
189-
class Aggs(list):
190-
def __init__(self, raw):
191-
self._raw = raw
192-
super().__init__([
193-
Agg(tick) for tick in self.rename_keys()
194-
])
195-
196-
def _raw_results(self):
197-
return self._raw.get('results', [])
198-
199-
def rename_keys(self):
200-
colmap = {
201-
"o": "open",
202-
"h": "high",
203-
"l": "low",
204-
"c": "close",
205-
"v": "volume",
206-
"t": "timestamp",
207-
}
208-
return [
209-
{colmap.get(k, k): v for k, v in tick.items()}
210-
for tick in self._raw_results()
211-
]
212-
213-
@property
214-
def df(self):
215-
if not hasattr(self, '_df'):
216-
columns = ('timestamp', 'open', 'high', 'low', 'close', 'volume')
217-
df = pd.DataFrame(
218-
self.rename_keys(),
219-
columns=columns
220-
)
221-
df.set_index('timestamp', inplace=True)
222-
df.index = pd.to_datetime(
223-
df.index.astype('int64'),
224-
unit='ms', utc=True
225-
).tz_convert(NY)
226-
227-
self._df = df
228-
return self._df
229-
230-
231156
class Trade(_NanoTimestamped, Entity):
232157
pass
233158

@@ -263,6 +188,7 @@ class Calendar(Entity):
263188
https://alpaca.markets/docs/api-documentation/api-v2/calendar/
264189
#calendar-entity
265190
"""
191+
266192
def __getattr__(self, key):
267193
if key in self._raw:
268194
val = self._raw[key]
@@ -292,6 +218,7 @@ class PortfolioHistory(Entity):
292218
https://alpaca.markets/docs/api-documentation/api-v2/portfolio-history/
293219
#portfoliohistory-entity
294220
"""
221+
295222
def __init__(self, raw):
296223
self._raw = raw
297224

alpaca_trade_api/rest.py

Lines changed: 2 additions & 89 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
import deprecation
21
import logging
32
import os
43
from typing import Iterator, List, Optional, Union
@@ -15,8 +14,8 @@
1514
)
1615
from .entity import (
1716
Bar, Entity, Account, AccountConfigurations, AccountActivity,
18-
Asset, Order, Position, BarSet, Clock, Calendar,
19-
Aggs, Trade, Quote, Watchlist, PortfolioHistory
17+
Asset, Order, Position, Clock, Calendar,
18+
Trade, Quote, Watchlist, PortfolioHistory
2019
)
2120
from .entity_v2 import (
2221
BarV2, BarsV2, LatestBarsV2, LatestQuotesV2, LatestTradesV2,
@@ -542,92 +541,6 @@ def get_asset(self, symbol: str) -> Asset:
542541
resp = self.get('/assets/{}'.format(symbol))
543542
return self.response_wrapper(resp, Asset)
544543

545-
@deprecation.deprecated(deprecated_in="v1.0.0",
546-
details="Use get_bars instead")
547-
def get_barset(self,
548-
symbols,
549-
timeframe: str,
550-
limit: int = None,
551-
start: str = None,
552-
end: str = None,
553-
after: str = None,
554-
until: str = None) -> BarSet:
555-
"""
556-
read the documentation here:
557-
https://alpaca.markets/docs/api-documentation/api-v2/market-data/bars/
558-
Get BarSet(dict[str]->list[Bar])
559-
:param symbols: The parameter symbols can be either a comma-split
560-
string or a list of string. Each symbol becomes the key of the
561-
returned value.
562-
:param timeframe: One of minute, 1Min, 5Min, 15Min, day or 1D. minute
563-
is an alias of 1Min. Similarly, day is of 1D.
564-
:param limit: The maximum number of bars per symbol. It can be between
565-
1 and 1000. Default is 100.
566-
:param start: ISO Format str, ex: '2019-04-15T09:30:00-04:00' or
567-
'2019-04-15'
568-
:param end: ISO Format str
569-
:param after: ISO Format str
570-
:param until: ISO Format str
571-
:return: BarSet
572-
573-
note: start can't be used with after. end cannot be used with until.
574-
"""
575-
if not isinstance(symbols, str):
576-
symbols = ','.join(symbols)
577-
params = {
578-
'symbols': symbols,
579-
}
580-
if limit is not None:
581-
params['limit'] = limit
582-
if start is not None:
583-
params['start'] = start
584-
if end is not None:
585-
params['end'] = end
586-
if after is not None:
587-
params['after'] = after
588-
if until is not None:
589-
params['until'] = until
590-
resp = self.data_get('/bars/{}'.format(timeframe), params)
591-
return self.response_wrapper(resp, BarSet)
592-
593-
@deprecation.deprecated(deprecated_in="v1.0.0",
594-
details="Use get_bars instead")
595-
def get_aggs(self,
596-
symbol: str,
597-
multiplier: int,
598-
timespan: str,
599-
_from: str,
600-
to: str) -> Aggs:
601-
"""
602-
603-
:param symbol: str eg AAPL
604-
:param multiplier: must be 1
605-
:param timespan: day or minute
606-
:param _from: yyyy-mm-dd
607-
:param to: yyyy-mm-dd
608-
:return:
609-
"""
610-
resp = self.data_get('/aggs/ticker/{}/range/{}/{}/{}/{}'.format(
611-
symbol, multiplier, timespan, _from, to
612-
))
613-
return self.response_wrapper(resp, Aggs)
614-
615-
@deprecation.deprecated(deprecated_in="v1.0.0",
616-
details="Use get_latest_trade instead")
617-
def get_last_trade(self, symbol: str) -> Trade:
618-
"""
619-
Get the last trade for the given symbol
620-
"""
621-
resp = self.data_get('/last/stocks/{}'.format(symbol))
622-
return self.response_wrapper(resp['last'], Trade)
623-
624-
@deprecation.deprecated(deprecated_in="v1.0.0",
625-
details="Use get_latest_quote instead")
626-
def get_last_quote(self, symbol: str) -> Quote:
627-
"""Get the last quote for the given symbol"""
628-
resp = self.data_get('/last_quote/stocks/{}'.format(symbol))
629-
return self.response_wrapper(resp['last'], Quote)
630-
631544
def _data_get(self,
632545
endpoint: str,
633546
symbol_or_symbols: Union[str, List[str]],

alpaca_trade_api/stream.py

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
"""
2-
Stream V2
3-
For historic reasons stream2.py contains the old api version.
4-
Don't get confused
5-
"""
61
import asyncio
72
import logging
83
import json

0 commit comments

Comments
 (0)