Beispiel #1
0
class AlpacaData(DataAPI):
    def __init__(self):
        self.alpaca_rest_client = REST(key_id=config.alpaca_api_key,
                                       secret_key=config.alpaca_api_secret)
        if not self.alpaca_rest_client:
            raise AssertionError(
                "Failed to authenticate Alpaca RESTful client")

    def get_symbols(self) -> List[Dict]:
        if not self.alpaca_rest_client:
            raise AssertionError("Must call w/ authenticated Alpaca client")

        return self.alpaca_rest_client.list_assets()

    def get_symbol_data(
        self,
        symbol: str,
        start: date,
        end: date = date.today(),
        scale: TimeScale = TimeScale.minute,
    ) -> pd.DataFrame:
        _start = nytz.localize(datetime.combine(
            start, datetime.min.time())).isoformat()
        _end = (nytz.localize(datetime.now().replace(
            microsecond=0)).isoformat() if end >= date.today() else end)
        if not self.alpaca_rest_client:
            raise AssertionError("Must call w/ authenticated Alpaca client")

        t: TimeFrame = (TimeFrame.Minute if scale == TimeScale.minute else
                        TimeFrame.Day if scale == TimeScale.day else None)
        data = self.alpaca_rest_client.get_bars(
            symbol=symbol,
            timeframe=t,
            start=_start,
            end=_end,
            limit=10000,
            adjustment="raw",
        ).df
        data = data.tz_convert("America/New_York")
        data["vwap"] = None
        data["average"] = None
        data["count"] = None

        if data.empty:
            raise ValueError(
                f"[ERROR] {symbol} has no data for {_start} to {_end} w {scale.name}"
            )

        return data
class AlpacaData(DataAPI):
    def __init__(self):
        self.alpaca_rest_client = REST(
            key_id=config.alpaca_api_key, secret_key=config.alpaca_api_secret
        )
        if not self.alpaca_rest_client:
            raise AssertionError(
                "Failed to authenticate Alpaca RESTful client"
            )

    def get_symbols(self) -> List[Dict]:
        if not self.alpaca_rest_client:
            raise AssertionError("Must call w/ authenticated polygon client")

        data = self.alpaca_rest_client.list_assets()
        return data

    def get_symbol_data(
        self,
        symbol: str,
        start: date,
        end: date = date.today(),
        scale: TimeScale = TimeScale.minute,
    ) -> pd.DataFrame:
        if not self.alpaca_rest_client:
            raise AssertionError("Must call w/ authenticated Alpaca client")

        t: TimeFrame = (
            TimeFrame.Minute
            if scale == TimeScale.minute
            else TimeFrame.Day
            if scale == TimeScale.day
            else None
        )
        data = self.alpaca_rest_client.get_bars(
            symbol=symbol, timeframe=t, start=start, end=end, limit=10000
        ).df

        if data.empty:
            raise ValueError(
                f"[ERROR] {symbol} has no data for {start} to {end} w {scale.name}"
            )

        return data
Beispiel #3
0
print(trades)
print(trades[trades['size']>=200])
min_price = float(trades['price'].min())
max_size = float(trades['size'].max())
print('min_price: %s' %min_price)
print('max_size: %s' %max_size)
if min_price<(0.96*low_price):
    print('Low price on the day: %s' %(low_price))
    for i in range(0,min(50,len(trades))):
        print(trades.sort_values('price').iloc[[i]] )
        print('conditions: %s' %((trades.sort_values('price')[['conditions','exchange']].iloc[[i]]) ))
        print('size: %s' %(trades.sort_values('price').iloc[[i]][['size']]) )
    print('Highest prices: %s' %((trades.sort_values('price')).iloc[[-1]][['price','exchange']]))
sys.exit(0)

trade_days = api.get_bars(ticker, TimeFrame.Day, "2021-01-02", "2021-03-12", 'raw').df
#trade_days = api.get_bars(ticker, TimeFrame.Day, "2021-03-05", "2021-03-12", 'raw').df
#print(trade_days)
#print(pd.unique(trade_days['volume']))
print(trade_days.index.unique())
total_days_tested = len(trade_days.index.unique())
days_less_thr=0
for myday in trade_days.index.unique():
    ts = pd.Timestamp(year = myday.year,  month = myday.month, day = myday.day, 
                    hour = 16, minute=00, second = 0, tz = 'US/Eastern') 
    te = pd.Timestamp(year = myday.year,  month = myday.month, day = myday.day, 
                    hour = 20, minute=00, second = 0, tz = 'US/Eastern') 
    #choseInd = [ind for ind in trade_days.index if (ind.day<9 or ind.hour>=16)]
    days_price = trade_days.loc[myday]
    print(days_price['high'])
    low_price=0.0
Beispiel #4
0
    def download_symbol(cls,
                        symbol: str,
                        timeframe: str = '1d',
                        start: tp.DatetimeLike = 0,
                        end: tp.DatetimeLike = 'now UTC',
                        adjustment: tp.Optional[str] = 'all',
                        limit: int = 500,
                        exchange: tp.Optional[str] = 'CBSE',
                        **kwargs) -> tp.Frame:
        """Download the symbol.

        Args:
            symbol (str): Symbol.
            timeframe (str): Timeframe of data.

                Must be integer multiple of 'm' (minute), 'h' (hour) or 'd' (day). i.e. '15m'.
                See https://alpaca.markets/data.

                !!! note
                    Data from the latest 15 minutes is not available with a free data plan.

            start (any): Start datetime.

                See `vectorbt.utils.datetime_.to_tzaware_datetime`.
            end (any): End datetime.

                See `vectorbt.utils.datetime_.to_tzaware_datetime`.
            adjustment (str): Specifies the corporate action adjustment for the stocks. 

                Allowed are `raw`, `split`, `dividend` or `all`.
            limit (int): The maximum number of returned items.
            exchange (str): For crypto symbols. Which exchange you wish to retrieve data from.

                Allowed are `FTX`, `ERSX`, `CBSE`

        For defaults, see `data.alpaca` in `vectorbt._settings.settings`.
        """
        from vectorbt._settings import settings
        from alpaca_trade_api.rest import TimeFrameUnit, TimeFrame, REST

        alpaca_cfg = settings['data']['alpaca']

        client_kwargs = dict()
        for k in get_func_kwargs(REST):
            if k in kwargs:
                client_kwargs[k] = kwargs.pop(k)

        client_kwargs = merge_dicts(alpaca_cfg, client_kwargs)

        client = REST(**client_kwargs)

        _timeframe_units = {'d': TimeFrameUnit.Day, 'h': TimeFrameUnit.Hour, 'm': TimeFrameUnit.Minute}

        if len(timeframe) < 2:
            raise ValueError("invalid timeframe")

        amount_str = timeframe[:-1]
        unit_str = timeframe[-1]

        if not amount_str.isnumeric() or unit_str not in _timeframe_units:
            raise ValueError("invalid timeframe")

        amount = int(amount_str)
        unit = _timeframe_units[unit_str]

        _timeframe = TimeFrame(amount, unit)

        start_ts = to_tzaware_datetime(start, tz=get_utc_tz()).isoformat()
        end_ts = to_tzaware_datetime(end, tz=get_utc_tz()).isoformat()

        def _is_crypto_symbol(symbol):
            return len(symbol) == 6 and "USD" in symbol

        if _is_crypto_symbol(symbol):
            df = client.get_crypto_bars(
                symbol=symbol,
                timeframe=_timeframe,
                start=start_ts,
                end=end_ts,
                limit=limit,
                exchanges=exchange
            ).df
        else:
            df = client.get_bars(
                symbol=symbol,
                timeframe=_timeframe,
                start=start_ts,
                end=end_ts,
                adjustment=adjustment,
                limit=limit
            ).df

        # filter for OHLCV
        # remove extra columns
        df.drop(['trade_count', 'vwap'], axis=1, errors='ignore', inplace=True)

        # capitalize
        df.rename(columns={
            'open': 'Open',
            'high': 'High',
            'low': 'Low',
            'close': 'Close',
            'volume': 'Volume',
            'exchange': 'Exchange'
        }, inplace=True)

        df['Open'] = df['Open'].astype(float)
        df['High'] = df['High'].astype(float)
        df['Low'] = df['Low'].astype(float)
        df['Close'] = df['Close'].astype(float)
        df['Volume'] = df['Volume'].astype(float)

        return df
Beispiel #5
0
from dotenv import load_dotenv
import os
from alpaca_trade_api.rest import REST, TimeFrame
load_dotenv()
api = REST()

bars = api.get_bars("AAPL",
                    TimeFrame.Hour,
                    "2021-02-08",
                    "2021-02-08",
                    limit=10,
                    adjustment='raw').df
print(bars)
Beispiel #6
0
from alpaca_trade_api.rest import REST, TimeFrame
import sys

BASE_URL = "https://paper-api.alpaca.markets"
ALPACA_API_KEY = sys.argv[1]
ALPACA_SECRET_KEY = sys.argv[2]

api = REST(ALPACA_API_KEY, ALPACA_SECRET_KEY, BASE_URL)

account = api.get_account()

print("Your account is:" + account.status)

rawData = api.get_bars("KO",
                       TimeFrame.Day,
                       "2021-06-01",
                       "2021-07-07",
                       limit=10,
                       adjustment='raw').df

print(rawData)

order = api.submit_order(
    symbol='KO',
    qty=1,
    side='buy',
    type='market',
    time_in_force='day',
)

print(order)