Ejemplo n.º 1
0
    def Get1000m(self, api):
        """Get1000m: 
        api - alpaca rest api
        """
        #
        # Collect the latest 1000 minute bars
        #
        nyc = timezone('America/New_York')
        today = datetime.now(tz=nyc) 
        d1 = today.strftime("%Y-%m-%dT%H:%M:%S-05:00")
        s1_day = (today + timedelta(days=-15)).strftime("%Y-%m-%dT%H:%M:%S-05:00")

        minute_prices = runTicker(api, self.ticker, timeframe=TimeFrame.Day, start=s1_day, end=d1, limit=100000)
        minute_prices = minute_prices[-1000:]
        
        return minute_prices
Ejemplo n.º 2
0
def get_tickers(_out_tickers = []):
    print('Getting current ticker data...')
    in_instruct_name=STOCK_DB_PATH+'/Instructions/out_momentum_instructions.csv'
    instruct = pd.read_csv(in_instruct_name,delimiter=' ')
    tickers = []
    if 'ticker' in instruct.columns:
        tickers = instruct['ticker'].unique()
    print(tickers)
    print('Success.')

    # Load assets
    assets = []
    for tick in tickers:
        assets +=[api.get_asset(tick)]

    symbols = [asset.symbol for asset in assets if asset.tradable]

    nyc = timezone('America/New_York')
    today = datetime.now(tz=nyc) 
    todayFilter = (today + timedelta(days=-2))
    d1 = today.strftime("%Y-%m-%dT%H:%M:%S-05:00")
    s1_day = (today + timedelta(days=-10)).strftime("%Y-%m-%dT%H:%M:%S-05:00")
    s1_min = (today).strftime("%Y-%m-%dT09:30:00-05:00")
    for s in symbols:
        trade = api.get_latest_trade(s)
        day_prices = runTicker(api, s, timeframe=TimeFrame.Day, start=s1_day, end=d1)
        #minute_prices = runTicker(api, s, timeframe=TimeFrame.Day, start=s1_min, end=d1)
        if len(day_prices)<2 or 'volume' not in day_prices.columns:
            continue
        prevday_volume = day_prices['volume'][-2]
        open_price = day_prices['open'][-1]
        if open_price<=0.0:
            continue

        if True or  trade.p >= min_share_price and \
           trade.p <= max_share_price and \
           prevday_volume*trade.p > min_last_dv and \
           (open_price - trade.p)/open_price >= 0.035:
            my_stock = Stock(s, api.get_asset(tick), day_prices, prevday_volume, trade)
            found = False
            for ts in _out_tickers:
                if s==ts.ticker:
                    found=True
            if not found:
                _out_tickers+=[my_stock]
            
    return _out_tickers
Ejemplo n.º 3
0
ticker='WRN'
#ticker='NTNX' #TDUP, SAVA, DOMO
#ticker='SAVA' #TDUP, SAVA, DOMO
#ticker='TSLA' #TDUP, SAVA, DOMO
#ticker='DOMO'
#ticker='KFY'
#ticker='X'
#ticker='HP'
#ticker='CVS'
ticker='WBA'
ticker='BSET'
today = datetime.datetime.now(tz=est) + datetime.timedelta(minutes=-40)
d1 = today.strftime("%Y-%m-%dT%H:%M:%S-04:00")
thirty_days = (today + datetime.timedelta(days=-30)).strftime("%Y-%m-%dT%H:%M:%S-04:00")
if True:
    minute_prices_thirty  = runTicker(api, ticker, timeframe=TimeFrame.Minute, start=thirty_days, end=d1)
    minute_prices_spy  = runTicker(api, 'SPY', timeframe=TimeFrame.Minute, start=thirty_days, end=d1)
    # add the extra data
    AddData(minute_prices_thirty)
    AddData(minute_prices_spy)
    
    minute_prices_spy['signif_volume_spy'] = minute_prices_spy.signif_volume
    minute_prices_thirty = minute_prices_thirty.join(minute_prices_spy.signif_volume_spy,how='left')
    minute_prices_thirty['signif_volume_over_spy'] = minute_prices_thirty.signif_volume / minute_prices_thirty.signif_volume_spy
    
    # get the last 5 days
    minute_prices = GetTimeSlot(minute_prices_thirty,days=10)
    minute_prices_spy_10d = GetTimeSlot(minute_prices_spy,days=10)
    #minute_prices=minute_prices_thirty
    print(minute_prices)
    AddDataShort(minute_prices)
Ejemplo n.º 4
0
    else: plt.savefig(outdir + '%s.png' % (saveName))
    if not draw: plt.close()
    plt.close()


api = ALPACA_REST()
ts = ALPHA_TIMESERIES()
ticker = 'SPY'
#ticker='TLT'
#ticker='QQQ'
#ticker='GLD'
#ticker='HAL'
#ticker='GUSH'
#ticker='AVCT'
#ticker='RZV'
spy = runTicker(api, ticker)
stock_info = None
spy = None
sqlcursor = SQL_CURSOR()
readType = 'full'

spy, j = ConfigTable(ticker, sqlcursor, ts, readType)
print('spy')
print(spy)

# add info
if len(spy) == 0:
    print('ERROR - empy info %s' % ticker)

spy['daily_return'] = spy['adj_close'].pct_change(periods=1) + 1
spy['openclosepct'] = (spy.close - spy.open) / spy.open + 1
Ejemplo n.º 5
0
def GenerateSignal(ticker,
                   out_file_name='out_bull_instructions.csv',
                   price_targets=[]):
    connectionCal = SQL_CURSOR('earningsCalendarv2.db')
    fd = ALPHA_FundamentalData()
    sqlcursor = SQL_CURSOR()
    ts = ALPHA_TIMESERIES()
    api = ALPACA_REST()

    stockInfoQuarter, stockInfoAnnual, company_overview = CollectEarnings(
        ticker, connectionCal)

    # annual balance sheet
    balance_sheet_annual = fd.get_balance_sheet_annual(ticker)[0]
    balance_sheet_annual['fiscalDateEnding'] = pd.to_datetime(
        balance_sheet_annual['fiscalDateEnding'], errors='coerce')
    for d in balance_sheet_annual.columns:
        if d not in ['fiscalDateEnding', 'totalAssets']:
            balance_sheet_annual[d] = pd.to_numeric(balance_sheet_annual[d],
                                                    errors='coerce')
    # quarterly income statement
    income_statement_quarterly = fd.get_income_statement_quarterly(ticker)[0]
    for d in income_statement_quarterly.columns:
        if d not in ['fiscalDateEnding', 'reportedCurrency']:
            income_statement_quarterly[d] = pd.to_numeric(
                income_statement_quarterly[d], errors='coerce')
    for d in ['fiscalDateEnding']:
        income_statement_quarterly[d] = pd.to_datetime(
            income_statement_quarterly[d], errors='coerce')
    if debug:
        print(income_statement_quarterly)
        print(income_statement_quarterly.dtypes)

    tstock_info, j = ConfigTable(ticker, sqlcursor, ts, 'full')
    spy, j = ConfigTable('SPY', sqlcursor, ts, 'compact')
    #print(spy.columns)
    est = pytz.timezone('US/Eastern')
    today = datetime.now(tz=est) + maindatetime.timedelta(minutes=-40)
    #today = datetime.utcnow() + maindatetime.timedelta(minutes=-30)
    d1 = today.strftime("%Y-%m-%dT%H:%M:%S-04:00")
    five_days = (
        today +
        maindatetime.timedelta(days=-7)).strftime("%Y-%m-%dT%H:%M:%S-04:00")
    minute_prices = []
    ntry = 0
    while ntry < 3:
        try:
            minute_prices = runTicker(api,
                                      ticker,
                                      timeframe=TimeFrame.Minute,
                                      start=five_days,
                                      end=d1)
            break
        except (requests.exceptions.ConnectionError):
            ntry += 1
    # may want to restrict to NYSE open times
    try:
        spy = AddInfo(spy, spy)
        tstock_info = AddInfo(tstock_info, spy, AddSupport=True)
    except (ValueError, KeyError):
        print('Error processing adding info %s' % ticker)

    recent_quotes = getQuotes(api, ticker)
    if debug:
        print(tstock_info[[
            'adj_close', 'sma20', 'sma20cen', 'vwap10cen', 'vwap10'
        ]][50:-10])
    earn = Earnings(ticker, income_statement_quarterly, company_overview,
                    balance_sheet_annual, stockInfoQuarter, stockInfoAnnual,
                    tstock_info, minute_prices, recent_quotes)
    #earn.BuildPDF()
    earn.WriteCSV(out_file_name, price_targets)
Ejemplo n.º 6
0
        print(income_statement_quarterly.dtypes)

    tstock_info, j = ConfigTable(ticker, sqlcursor, ts, 'compact')
    spy, j = ConfigTable('SPY', sqlcursor, ts, 'compact')

    est = pytz.timezone('US/Eastern')
    today = datetime.now(tz=est) + maindatetime.timedelta(minutes=-40)
    #today = datetime.utcnow() + maindatetime.timedelta(minutes=-30)
    d1 = today.strftime("%Y-%m-%dT%H:%M:%S-04:00")
    five_days = (
        today +
        maindatetime.timedelta(days=-7)).strftime("%Y-%m-%dT%H:%M:%S-04:00")

    minute_prices = runTicker(api,
                              ticker,
                              timeframe=TimeFrame.Minute,
                              start=five_days,
                              end=d1)
    # may want to restrict to NYSE open times
    #minute_prices = minute_prices[(minute_prices.index.hour>13) & (minute_prices.index.hour<20)
    #print(minute_prices)
    try:
        spy = AddInfo(spy, spy)
        tstock_info = AddInfo(tstock_info, spy, AddSupport=True)
    except (ValueError, KeyError):
        print('Error processing adding info to SPY %s' % ticker)

    recent_quotes = getQuotes(api, ticker)
    if debug:
        print(tstock_info[[
            'adj_close', 'sma20', 'sma20cen', 'vwap10cen', 'vwap10'
Ejemplo n.º 7
0
def generateFigure(apiA, tickerA):
    """generateFigure:
       apiA - alpaca api
       tickerA - str - ticker
    """
    figs = []
    doSPYComparison = False
    today = datetime.datetime.now(tz=est)  #+ datetime.timedelta(minutes=5)
    d1 = today.strftime("%Y-%m-%dT%H:%M:%S-05:00")
    thirty_days = (
        today +
        datetime.timedelta(days=-13)).strftime("%Y-%m-%dT%H:%M:%S-05:00")
    minute_prices_thirty = []
    try:
        minute_prices_thirty = runTicker(apiA,
                                         tickerA,
                                         timeframe=TimeFrame.Minute,
                                         start=thirty_days,
                                         end=d1)
        AddData(minute_prices_thirty)
        minute_prices_spy = []
        if doSPYComparison:
            minute_prices_spy = runTicker(apiA,
                                          'SPY',
                                          timeframe=TimeFrame.Minute,
                                          start=thirty_days,
                                          end=d1)
            AddData(minute_prices_spy)
            minute_prices_spy[
                'signif_volume_spy'] = minute_prices_spy.signif_volume
            minute_prices_spy['change_spy'] = minute_prices_spy.change
            minute_prices_spy[
                'minute_diffHL_spy'] = minute_prices_spy.minute_diffHL
            minute_prices_spy[
                'minute_diff_spy'] = minute_prices_spy.minute_diff

            minute_prices_thirty = minute_prices_thirty.join(
                minute_prices_spy.signif_volume_spy, how='left')
            minute_prices_thirty = minute_prices_thirty.join(
                minute_prices_spy.change_spy, how='left')
            minute_prices_thirty = minute_prices_thirty.join(
                minute_prices_spy.minute_diff_spy, how='left')
            minute_prices_thirty = minute_prices_thirty.join(
                minute_prices_spy.minute_diffHL_spy, how='left')
            minute_prices_thirty[
                'signif_volume_over_spy'] = minute_prices_thirty.signif_volume / minute_prices_thirty.signif_volume_spy
            minute_prices_thirty[
                'change_over_spy'] = minute_prices_thirty.change - minute_prices_thirty.change_spy
            minute_prices_thirty['signif_volume_over_spy'].where(
                minute_prices_thirty['signif_volume_over_spy'] < 150.0,
                150.0,
                inplace=True)
            minute_prices_thirty['signif_volume_over_spy'].where(
                minute_prices_thirty['signif_volume_over_spy'] > -150.0,
                -150.0,
                inplace=True)
        # draw figures
        fig = go.Figure(data=go.Scatter(
            x=minute_prices_thirty['i'],
            y=minute_prices_thirty['close'],
            error_y=dict(type='data',
                         symmetric=False,
                         array=minute_prices_thirty.high -
                         minute_prices_thirty.close,
                         arrayminus=minute_prices_thirty.close -
                         minute_prices_thirty.low)))
        fig.update_layout(xaxis_title="Minute Bars",
                          yaxis_title="%s Price" % tickerA)
        figs += [fig]

        fig = go.Figure(data=[
            go.Candlestick(x=minute_prices_thirty['i'],
                           open=minute_prices_thirty['open'],
                           high=minute_prices_thirty['high'],
                           low=minute_prices_thirty['low'],
                           close=minute_prices_thirty['close'])
        ])
        figs += [fig]

        fig = make_subplots(specs=[[{"secondary_y": True}]])
        # Add traces
        fig.add_trace(go.Scatter(x=minute_prices_thirty['i'],
                                 y=minute_prices_thirty['close'],
                                 name='price'),
                      secondary_y=False)
        if doSPYComparison:
            fig.add_trace(go.Scatter(
                x=minute_prices_thirty['i'],
                y=minute_prices_thirty['signif_volume_over_spy'],
                name='volume sigificance/SPY'),
                          secondary_y=True)

        fig.add_trace(go.Scatter(x=minute_prices_thirty['i'],
                                 y=minute_prices_thirty['slope'],
                                 name='slope'),
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=minute_prices_thirty['i'],
                                 y=minute_prices_thirty['signif_volume'],
                                 name='volume sigificance'),
                      secondary_y=True)

        # Set x-axis title
        fig.update_xaxes(title_text="Minute Bars")

        # Set y-axes titles
        fig.update_yaxes(title_text="Price", secondary_y=False)
        fig.update_yaxes(title_text="Slope", secondary_y=True)
        figs += [fig]

        fig = make_subplots(specs=[[{"secondary_y": True}]])
        fig.add_trace(go.Scatter(
            x=minute_prices_thirty['time'],
            y=minute_prices_thirty['close'],
            name='price',
            error_y=dict(type='data',
                         symmetric=False,
                         array=minute_prices_thirty.high -
                         minute_prices_thirty.close,
                         arrayminus=minute_prices_thirty.close -
                         minute_prices_thirty.low)),
                      secondary_y=False)
        fig.add_trace(go.Scatter(x=minute_prices_thirty['time'],
                                 y=minute_prices_thirty['slope'],
                                 name='slope'),
                      secondary_y=True)
        fig.add_trace(go.Scatter(x=minute_prices_thirty['time'],
                                 y=minute_prices_thirty['signif_volume'],
                                 name='volume sigificance'),
                      secondary_y=True)

        # Set x-axis title
        fig.update_layout(xaxis_title="Date", yaxis_title="%s Price" % tickerA)

        # Set y-axes titles
        fig.update_yaxes(title_text="Price", secondary_y=False)
        fig.update_yaxes(title_text="Slope", secondary_y=True)

        figs += [fig]

    except:
        pass

    return minute_prices_thirty, figs
Ejemplo n.º 8
0
def generateMeanRevFigure(apiA, sqlA, tsA, tickerA, doRelativeToSpy=False):
    """generateMeanRevFigure:
       apiA - alpaca api
       sqlA - mysql cursor
       tsA - time series api
       tickerA - str - ticker
       doRelativeToSpy - bool - compute the ratio to SPY for performance
    """
    figs = []

    today = datetime.datetime.now(tz=est)
    d1 = today.strftime("%Y-%m-%dT%H:%M:%S-05:00")
    d1_set = today.strftime("%Y-%m-%d")
    #d1_set = "2022-01-19"
    twelve_hours = (
        today +
        datetime.timedelta(hours=-12)).strftime("%Y-%m-%dT%H:%M:%S-05:00")
    minute_prices = runTicker(apiA,
                              tickerA,
                              timeframe=TimeFrame.Minute,
                              start=twelve_hours,
                              end=d1)

    daily_prices, j = ConfigTable(tickerA, sqlA, tsA, 'full', hoursdelay=18)

    # add todays numbers if available
    if len(minute_prices) > 0:
        df_today = pd.DataFrame([[
            minute_prices['open'][0], minute_prices['high'].max(),
            minute_prices['low'].min(), minute_prices['close'][-1],
            minute_prices['close'][-1], minute_prices['volume'].sum(), 0.0, 1.0
        ]],
                                columns=[
                                    'open', 'high', 'low', 'close',
                                    'adj_close', 'volume', 'dividendamt',
                                    'splitcoef'
                                ],
                                index=[d1_set
                                       ])  #index=[minute_prices.index[-1]])
        df_today.index = pd.to_datetime(df_today.index)
        if len(daily_prices
               ) == 0 or daily_prices.index[-1] < df_today.index[0]:
            daily_prices = pd.concat([daily_prices, df_today])
            daily_prices = daily_prices.sort_index()

    #st.table(daily_prices.tail())
    filter_shift_days = 0
    if filter_shift_days > 0:
        daily_prices = GetTimeSlot(daily_prices,
                                   days=6 * 365,
                                   startDate=todayFilter)
    daily_prices_60d = GetTimeSlot(daily_prices, days=60 + filter_shift_days)
    daily_prices_180d = GetTimeSlot(daily_prices, days=180 + filter_shift_days)
    daily_prices_365d = GetTimeSlot(daily_prices, days=365 + filter_shift_days)
    daily_prices_3y = GetTimeSlot(daily_prices,
                                  days=3 * 365 + filter_shift_days)
    daily_prices_5y = GetTimeSlot(daily_prices,
                                  days=5 * 365 + filter_shift_days)
    daily_prices_180d['daily_return'] = daily_prices_180d[
        'adj_close'].pct_change(periods=1)

    figs += [
        FitWithBand(
            daily_prices_60d.index,
            daily_prices_60d[['adj_close', 'high', 'low', 'open', 'close']],
            ticker=tickerA,
            outname='60d')
    ]
    figs += [
        FitWithBand(
            daily_prices_180d.index,
            daily_prices_180d[['adj_close', 'high', 'low', 'open', 'close']],
            ticker=tickerA,
            outname='180d')
    ]
    figs += [
        FitWithBand(
            daily_prices_365d.index,
            daily_prices_365d[['adj_close', 'high', 'low', 'open', 'close']],
            ticker=tickerA,
            outname='365d')
    ]
    figs += [
        FitWithBand(
            daily_prices_3y.index,
            daily_prices_3y[['adj_close', 'high', 'low', 'open', 'close']],
            ticker=tickerA,
            outname='3y')
    ]
    figs += [
        FitWithBand(
            daily_prices_5y.index,
            daily_prices_5y[['adj_close', 'high', 'low', 'open', 'close']],
            ticker=tickerA,
            outname='5y')
    ]

    # Compute relative to spy
    if doRelativeToSpy:
        spy, j = ConfigTable('SPY', sqlA, tsA, 'full', hoursdelay=18)
        if filter_shift_days > 0:
            spy = GetTimeSlot(spy, days=6 * 365, startDate=todayFilter)
        spy_daily_prices_60d = GetTimeSlot(spy, days=60 + filter_shift_days)
        spy_daily_prices_365d = GetTimeSlot(spy, days=365 + filter_shift_days)
        spy_daily_prices_5y = GetTimeSlot(spy,
                                          days=5 * 365 + filter_shift_days)

        figs += [
            FitWithBand(daily_prices_365d.index,
                        daily_prices_365d[[
                            'adj_close', 'high', 'low', 'open', 'close'
                        ]],
                        ticker=tickerA,
                        outname='365dspycomparison',
                        spy_comparison=spy_daily_prices_365d[[
                            'adj_close', 'high', 'low', 'open', 'close'
                        ]])
        ]
        figs += [
            FitWithBand(
                daily_prices_60d.index,
                daily_prices_60d[['adj_close', 'high', 'low', 'open',
                                  'close']],
                ticker=tickerA,
                outname='60dspycomparison',
                spy_comparison=spy_daily_prices_60d[[
                    'adj_close', 'high', 'low', 'open', 'close'
                ]])
        ]
        figs += [
            FitWithBand(
                daily_prices_5y.index,
                daily_prices_5y[['adj_close', 'high', 'low', 'open', 'close']],
                ticker=tickerA,
                outname='5yspycomparison',
                spy_comparison=spy_daily_prices_5y[[
                    'adj_close', 'high', 'low', 'open', 'close'
                ]])
        ]
    return figs