Skip to content

Commit

Permalink
Merge pull request alpacahq#3 from alpacahq/master
Browse files Browse the repository at this point in the history
Dev changes
  • Loading branch information
bbeale authored Mar 2, 2020
2 parents c0da5a8 + 0ef3e95 commit 2a8065c
Show file tree
Hide file tree
Showing 7 changed files with 75 additions and 10 deletions.
19 changes: 13 additions & 6 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,6 +169,10 @@ Calls `GET /clock` and returns a `Clock` entity.
### REST.get_calendar(start=None, end=None)
Calls `GET /calendar` and returns a `Calendar` entity.

### REST.get_portfolio_history(date_start=None, date_end=None, period=None, timeframe=None, extended_hours=None)
Calls `GET /account/portfolio/history` and returns a PortfolioHistory entity. PortfolioHistory.df
can be used to get the results as a dataframe.

---

## StreamConn
Expand All @@ -191,7 +195,7 @@ if `AM.*` given to the `subscribe()` method, a WebSocket connection is
established to Polygon's interface.

The `run` method is a short-cut to start subscribing to channels and
runnnig forever. The call will be blocked forever until a critical
running forever. The call will be blocked forever until a critical
exception is raised, and each event handler is called asynchronously
upon the message arrivals.

Expand All @@ -215,15 +219,15 @@ async def on_account_updates(conn, channel, account):
print('account', account)

@conn.on(r'^status$')
def on_status(conn, channel, data):
async def on_status(conn, channel, data):
print('polygon status update', data)

@conn.on(r'^AM$')
def on_minute_bars(conn, channel, bar):
async def on_minute_bars(conn, channel, bar):
print('bars', bar)

@conn.on(r'^A$')
def on_second_bars(conn, channel, bar):
async def on_second_bars(conn, channel, bar):
print('bars', bar)

# blocks forever
Expand Down Expand Up @@ -328,6 +332,9 @@ For example, the `o` field is renamed to `open`.
### polygon/Aggs.df
Returns a pandas DataFrame object with the ticks returned by `hitoric_agg_v2`.

### polygon/REST.daily_open_close(symbol, date)
Returns a `DailyOpenClose` entity.

### poylgon/REST.last_trade(symbol)
Returns a `Trade` entity representing the last trade for the symbol.

Expand Down Expand Up @@ -363,7 +370,7 @@ Returns a `NewsList` entity for the symbol.
---
# Alpha Vantage API Service

In addition to Polygon is Alpha Vantage, for users without a live account (paper trading) or want to use the unique features of AV data. You can get a free key [here](https://www.alphavantage.co/support/#api-key) and the documentation is [here](https://www.alphavantage.co/documentation/). Premium keys are also available [here](https://www.alphavantage.co/premium/#intro)
In addition to Polygon is Alpha Vantage, for users without a live account (paper trading) or want to use the unique features of AV data. You can get a free key [here](https://www.alphavantage.co/support/#api-key) and the documentation is [here](https://www.alphavantage.co/documentation/). Premium keys are also available [here](https://www.alphavantage.co/premium/#intro)
This python SDK wraps their API service and seamlessly integrates it with the Alpaca
API. `alpaca_trade_api.REST.alpha_vantage` will be the `REST` object for Alpha Vantage.

Expand Down Expand Up @@ -415,7 +422,7 @@ Returns a `json` object with the current OHLCV data of the selected currency pai
Returns a `csv`, `json`, or `pandas` object of historical OHLCV data for the cryptocurrency pair.

### alpha_vantage/REST.techindicators(self, techindicator='SMA', output_format='json', **kwargs)
Returns a `csv`, `json`, or `pandas` object with the data from the techindicator of choice.
Returns a `csv`, `json`, or `pandas` object with the data from the techindicator of choice.

### alpha_vantage/REST.sector()
Returns a `json` of the currrency sector performances.
Expand Down
2 changes: 1 addition & 1 deletion alpaca_trade_api/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from .rest import REST # noqa
from .stream2 import StreamConn # noqa

__version__ = '0.44'
__version__ = '0.45'
25 changes: 25 additions & 0 deletions alpaca_trade_api/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,3 +155,28 @@ def __getattr__(self, key):

class Watchlist(Entity):
pass


class PortfolioHistory(Entity):
def __init__(self, raw):
self._raw = raw

@property
def df(self):
if not hasattr(self, '_df'):
df = pd.DataFrame(
self._raw, columns=(
'timestamp', 'profit_loss', 'profit_loss_pct', 'equity'
),
)
df.set_index('timestamp', inplace=True)
if not df.empty:
df.index = pd.to_datetime(
(df.index * 1e6).astype('int64'), utc=True,
).tz_convert(NY)
else:
df.index = pd.to_datetime(
df.index, utc=True
)
self._df = df
return self._df
4 changes: 4 additions & 0 deletions alpaca_trade_api/polygon/entity.py
Original file line number Diff line number Diff line change
Expand Up @@ -314,3 +314,7 @@ class NewsList(EntityList):

class Ticker(Entity):
pass


class DailyOpenClose(Entity):
pass
8 changes: 7 additions & 1 deletion alpaca_trade_api/polygon/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,8 @@
Trade, Trades, TradesV2,
Quote, Quotes, QuotesV2,
Exchange, SymbolTypeMap, ConditionMap,
Company, Dividends, Splits, Earnings, Financials, NewsList, Ticker
Company, Dividends, Splits, Earnings, Financials, NewsList, Ticker,
DailyOpenClose
)
from alpaca_trade_api.common import get_polygon_credentials
from deprecated import deprecated
Expand Down Expand Up @@ -141,6 +142,11 @@ def grouped_daily(self, date, unadjusted=False):
raw = self.get(path, params, version='v2')
return Aggsv2Set(raw)

def daily_open_close(self, symbol, date):
path = '/open-close/{}/{}'.format(symbol, date)
raw = self.get(path)
return DailyOpenClose(raw)

def last_trade(self, symbol):
path = '/last/stocks/{}'.format(symbol)
raw = self.get(path)
Expand Down
21 changes: 20 additions & 1 deletion alpaca_trade_api/rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
from .entity import (
Account, AccountConfigurations, AccountActivity,
Asset, Order, Position, BarSet, Clock, Calendar,
Watchlist
Watchlist, PortfolioHistory
)
from . import polygon
from . import alpha_vantage
Expand Down Expand Up @@ -435,3 +435,22 @@ def delete_watchlist(self, watchlist_id):

def delete_from_watchlist(self, watchlist_id, symbol):
self.delete('/watchlists/{}/{}'.format(watchlist_id, symbol))

def get_portfolio_history(
self, date_start=None, date_end=None, period=None,
timeframe=None, extended_hours=None
):
params = {}
if date_start is not None:
params['date_start'] = date_start
if date_end is not None:
params['date_end'] = date_end
if period is not None:
params['period'] = period
if timeframe is not None:
params['timeframe'] = timeframe
if extended_hours is not None:
params['extended_hours'] = extended_hours
return PortfolioHistory(
self.get('/account/portfolio/history', data=params)
)
6 changes: 5 additions & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,11 @@
author_email='[email protected]',
url='https://github.com/alpacahq/alpaca-trade-api-python',
keywords='financial,timeseries,api,trade',
packages=['alpaca_trade_api', 'alpaca_trade_api.polygon', 'alpaca_trade_api.alpha_vantage'],
packages=[
'alpaca_trade_api',
'alpaca_trade_api.polygon',
'alpaca_trade_api.alpha_vantage',
],
install_requires=[
'asyncio-nats-client',
'pandas',
Expand Down

0 comments on commit 2a8065c

Please sign in to comment.