Ejemplo n.º 1
0
def load(
    ticker: str,
    start: datetime = (datetime.now() - timedelta(days=1100)),
    interval: int = 1440,
    end: datetime = datetime.now(),
    prepost: bool = False,
    source: str = "yf",
    iexrange: str = "ytd",
    weekly: bool = False,
    monthly: bool = False,
):
    """
    Load a symbol to perform analysis using the string above as a template. Optional arguments and their
    descriptions are listed above. The default source is, yFinance (https://pypi.org/project/yfinance/).
    Alternatively, one may select either AlphaVantage (https://www.alphavantage.co/documentation/)
    or IEX Cloud (https://iexcloud.io/docs/api/) as the data source for the analysis.
    Please note that certain analytical features are exclusive to the source.

    To load a symbol from an exchange outside of the NYSE/NASDAQ default, use yFinance as the source and
    add the corresponding exchange to the end of the symbol. i.e. ‘BNS.TO’.

    BNS is a dual-listed stock, there are separate options chains and order books for each listing.
    Opportunities for arbitrage may arise from momentary pricing discrepancies between listings
    with a dynamic exchange rate as a second order opportunity in ForEx spreads.

    Find the full list of supported exchanges here:
    https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html

    Certain analytical features, such as VWAP, require the ticker to be loaded as intraday
    using the ‘-i x’ argument.  When encountering this error, simply reload the symbol using
    the interval argument. i.e. ‘load -t BNS -s YYYY-MM-DD -i 1 -p’ loads one-minute intervals,
    including Pre/After Market data, using the default source, yFinance.

    Certain features, such as the Prediction menu, require the symbol to be loaded as daily and not intraday.

    Parameters
    ----------
    ticker: str
        Ticker to get data
    start: datetime
        Start date to get data from with
    interval: int
        Interval (in minutes) to get data 1, 5, 15, 30, 60 or 1440
    end: datetime
        End date to get data from with
    prepost: bool
        Pre and After hours data
    source: str
        Source of data extracted
    iexrange: str
        Timeframe to get IEX data.
    weekly: bool
        Flag to get weekly data
    monthly: bool
        Flag to get monthly data

    Returns
    -------
    df_stock_candidate: pd.DataFrame
        Dataframe of data
    """

    # Daily
    if interval == 1440:

        # Alpha Vantage Source
        if source == "av":
            try:
                ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas")
                # pylint: disable=unbalanced-tuple-unpacking
                df_stock_candidate, _ = ts.get_daily_adjusted(
                    symbol=ticker, outputsize="full"
                )
            except Exception as e:
                console.print(e)
                return pd.DataFrame()

            df_stock_candidate.columns = [
                val.split(". ")[1].capitalize() for val in df_stock_candidate.columns
            ]

            df_stock_candidate = df_stock_candidate.rename(
                columns={
                    "Adjusted close": "Adj Close",
                }
            )

            # Check that loading a stock was not successful
            # pylint: disable=no-member
            if df_stock_candidate.empty:
                console.print("No data found.\n")
                return pd.DataFrame()

            df_stock_candidate.index = df_stock_candidate.index.tz_localize(None)

            # pylint: disable=no-member
            df_stock_candidate.sort_index(ascending=True, inplace=True)

            # Slice dataframe from the starting date YYYY-MM-DD selected
            df_stock_candidate = df_stock_candidate[
                (df_stock_candidate.index >= start.strftime("%Y-%m-%d"))
                & (df_stock_candidate.index <= end.strftime("%Y-%m-%d"))
            ]

        # Yahoo Finance Source
        elif source == "yf":

            # TODO: Better handling of interval with week/month
            int_ = "1d"
            int_string = "Daily"
            if weekly:
                int_ = "1wk"
                int_string = "Weekly"
            if monthly:
                int_ = "1mo"
                int_string = "Monthly"

            # Adding a dropna for weekly and monthly because these include weird NaN columns.
            df_stock_candidate = yf.download(
                ticker, start=start, end=end, progress=False, interval=int_
            ).dropna(axis=0)

            # Check that loading a stock was not successful
            if df_stock_candidate.empty:
                console.print("")
                return pd.DataFrame()

            df_stock_candidate.index.name = "date"

        # IEX Cloud Source
        elif source == "iex":

            df_stock_candidate = pd.DataFrame()

            try:
                client = pyEX.Client(api_token=cfg.API_IEX_TOKEN, version="v1")

                df_stock_candidate = client.chartDF(ticker, timeframe=iexrange)

                # Check that loading a stock was not successful
                if df_stock_candidate.empty:
                    console.print("No data found.\n")
            except Exception as e:
                if "The API key provided is not valid" in str(e):
                    console.print("[red]Invalid API Key[/red]\n")
                else:
                    console.print(e)

                return df_stock_candidate

            df_stock_candidate = df_stock_candidate[
                ["close", "fHigh", "fLow", "fOpen", "fClose", "volume"]
            ]
            df_stock_candidate = df_stock_candidate.rename(
                columns={
                    "close": "Close",
                    "fHigh": "High",
                    "fLow": "Low",
                    "fOpen": "Open",
                    "fClose": "Adj Close",
                    "volume": "Volume",
                }
            )

            df_stock_candidate.sort_index(ascending=True, inplace=True)
        s_start = df_stock_candidate.index[0]
        s_interval = f"{interval}min"
        int_string = "Daily" if interval == 1440 else "Intraday"

    else:

        s_int = str(interval) + "m"
        s_interval = s_int + "in"
        d_granularity = {"1m": 6, "5m": 59, "15m": 59, "30m": 59, "60m": 729}

        s_start_dt = datetime.utcnow() - timedelta(days=d_granularity[s_int])
        s_date_start = s_start_dt.strftime("%Y-%m-%d")

        df_stock_candidate = yf.download(
            ticker,
            start=s_date_start if s_start_dt > start else start.strftime("%Y-%m-%d"),
            progress=False,
            interval=s_int,
            prepost=prepost,
        )

        # Check that loading a stock was not successful
        if df_stock_candidate.empty:
            console.print("")
            return pd.DataFrame()

        df_stock_candidate.index = df_stock_candidate.index.tz_localize(None)

        if s_start_dt > start:
            s_start = pytz.utc.localize(s_start_dt)
        else:
            s_start = start

        df_stock_candidate.index.name = "date"

        int_string = "Intraday"
    s_intraday = (f"Intraday {s_interval}", int_string)[interval == 1440]

    console.print(
        f"\nLoading {s_intraday} {ticker.upper()} stock "
        f"with starting period {s_start.strftime('%Y-%m-%d')} for analysis.",
    )

    return df_stock_candidate
Ejemplo n.º 2
0
def main():
    """
    Gamestonk Terminal is an awesome stock market terminal that has been developed for fun,
    while I saw my GME shares tanking. But hey, I like the stock.
    """

    # Enable VT100 Escape Sequence for WINDOWS 10 Ver. 1607
    if sys.platform == "win32":
        os.system("")

    s_ticker = ""
    s_start = ""
    df_stock = pd.DataFrame()
    s_interval = "1440min"

    # Set stock by default to speed up testing
    # s_ticker = "BB"
    # ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE, output_format='pandas')
    # df_stock, d_stock_metadata = ts.get_daily_adjusted(symbol=s_ticker, outputsize='full')
    # df_stock.sort_index(ascending=True, inplace=True)
    # s_start = datetime.strptime("2020-06-04", "%Y-%m-%d")
    # df_stock = df_stock[s_start:]

    # Add list of arguments that the main parser accepts
    menu_parser = argparse.ArgumentParser(add_help=False,
                                          prog="gamestonk_terminal")
    choices = [
        "help",
        "quit",
        "q",
        "clear",
        "load",
        "candle",
        "view",
        "export",
        "disc",
        "mill",
        "ba",
        "res",
        "fa",
        "ta",
        "dd",
        "pred",
        "ca",
        "op",
        "fred",
        "pa",
    ]
    menu_parser.add_argument("opt", choices=choices)
    completer = NestedCompleter.from_nested_dict({c: None for c in choices})

    # Print first welcome message and help
    print("\nWelcome to Gamestonk Terminal 🚀\n")
    should_print_help = True
    parsed_stdin = False

    if gtff.ENABLE_THOUGHTS_DAY:
        print("-------------------")
        try:
            thought.get_thought_of_the_day()
        except Exception as e:
            print(e)
        print("")

    # Loop forever and ever
    while True:
        main_cmd = False
        if should_print_help:
            print_help(s_ticker, s_start, s_interval, b_is_stock_market_open())
            should_print_help = False

        # Get input command from stdin or user
        if not parsed_stdin and len(sys.argv) > 1:
            as_input = " ".join(sys.argv[1:])
            parsed_stdin = True
            print(f"{get_flair()}> {as_input}")
        elif session and gtff.USE_PROMPT_TOOLKIT:
            as_input = session.prompt(f"{get_flair()}> ", completer=completer)
        else:
            as_input = input(f"{get_flair()}> ")

        # Is command empty
        if not as_input:
            print("")
            continue

        # Parse main command of the list of possible commands
        try:
            (ns_known_args,
             l_args) = menu_parser.parse_known_args(as_input.split())

        except SystemExit:
            print("The command selected doesn't exist\n")
            continue

        b_quit = False
        if ns_known_args.opt == "help":
            should_print_help = True

        elif (ns_known_args.opt == "quit") or (ns_known_args.opt == "q"):
            break

        elif ns_known_args.opt == "clear":
            s_ticker, s_start, s_interval, df_stock = clear(
                l_args, s_ticker, s_start, s_interval, df_stock)
            main_cmd = True

        elif ns_known_args.opt == "load":
            s_ticker, s_start, s_interval, df_stock = load(
                l_args, s_ticker, s_start, s_interval, df_stock)
            main_cmd = True

        elif ns_known_args.opt == "candle":

            if s_ticker:
                candle(
                    s_ticker,
                    (datetime.now() -
                     timedelta(days=180)).strftime("%Y-%m-%d"),
                )

            else:
                print(
                    "No ticker selected. Use 'load ticker' to load the ticker you want to look at.",
                    "\n",
                )

            main_cmd = True

        elif ns_known_args.opt == "view":

            if s_ticker:
                view(l_args, s_ticker, s_start, s_interval, df_stock)

            else:
                print(
                    "No ticker selected. Use 'load ticker' to load the ticker you want to look at."
                )
            main_cmd = True

        elif ns_known_args.opt == "export":
            export(l_args, df_stock)
            main_cmd = True

        elif ns_known_args.opt == "disc":
            b_quit = dm.disc_menu()

        elif ns_known_args.opt == "mill":
            b_quit = mill.papermill_menu()

        elif ns_known_args.opt == "ba":
            b_quit = ba_controller.menu(s_ticker, s_start)

        elif ns_known_args.opt == "res":
            b_quit = rm.res_menu(s_ticker, s_start, s_interval)

        elif ns_known_args.opt == "ca":
            b_quit = ca_controller.menu(df_stock, s_ticker, s_start,
                                        s_interval)

        elif ns_known_args.opt == "fa":
            b_quit = fam.fa_menu(s_ticker, s_start, s_interval)

        elif ns_known_args.opt == "ta":
            b_quit = tam.ta_menu(df_stock, s_ticker, s_start, s_interval)

        elif ns_known_args.opt == "dd":
            b_quit = ddm.dd_menu(df_stock, s_ticker, s_start, s_interval)

        elif ns_known_args.opt == "op":
            b_quit = opm.opt_menu(s_ticker)

        elif ns_known_args.opt == "fred":
            b_quit = fm.fred_menu()

        elif ns_known_args.opt == "pa":
            b_quit = port_controller.menu()

        elif ns_known_args.opt == "pred":

            if not gtff.ENABLE_PREDICT:
                print("Predict is not enabled in feature_flags.py")
                print("Prediction menu is disabled")
                print("")
                continue

            try:
                # pylint: disable=import-outside-toplevel
                from gamestonk_terminal.prediction_techniques import pred_menu as pm
            except ModuleNotFoundError as e:
                print("One of the optional packages seems to be missing")
                print("Optional packages need to be installed")
                print(e)
                print("")
                continue
            except Exception as e:
                print(e)
                print("")
                continue

            if s_interval == "1440min":
                b_quit = pm.pred_menu(df_stock, s_ticker, s_start, s_interval)
            # If stock data is intradaily, we need to get data again as prediction
            # techniques work on daily adjusted data. By default we load data from
            # Alpha Vantage because the historical data loaded gives a larger
            # dataset than the one provided by quandl
            else:
                try:
                    ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE,
                                    output_format="pandas")
                    # pylint: disable=unbalanced-tuple-unpacking
                    df_stock_pred, _ = ts.get_daily_adjusted(symbol=s_ticker,
                                                             outputsize="full")
                    # pylint: disable=no-member
                    df_stock_pred = df_stock_pred.sort_index(ascending=True)
                    df_stock_pred = df_stock_pred[s_start:]
                    b_quit = pm.pred_menu(df_stock_pred,
                                          s_ticker,
                                          s_start,
                                          s_interval="1440min")
                except Exception as e:
                    print(e)
                    print(
                        "Either the ticker or the API_KEY are invalids. Try again!"
                    )
                    return

        else:
            print("Shouldn't see this command!")
            continue

        if b_quit:
            break
        else:
            if not main_cmd:
                should_print_help = True

    print(
        "Hope you enjoyed the terminal. Remember that stonks only go up. Diamond hands.\n"
    )
Ejemplo n.º 3
0
from Creds import Creds
from alpha_vantage.timeseries import TimeSeries

ts = TimeSeries(key=Creds().getApiKey(), output_format='pandas')


def getCurrentPrice(symbol):
    return ts.get_intraday(symbol=symbol)[0].iloc[-1]['4. close']


def getDailyData(symbol, startDate=None, endDate=None):
    data, metadata = ts.get_daily_adjusted(symbol=symbol)

    # If start date is not within the recent data, fetch the full dataset.
    if data.index[0] > startDate:
        data, metadata\
            = ts.get_daily_adjusted(symbol=symbol, outputsize="full")

    return data
Ejemplo n.º 4
0
import os, sys, time, logging

from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
from alpha_vantage.sectorperformance import SectorPerformances

import pandas, json

# Read API infos from config
config_paht = 'myinfo.json'
if os.path.exists(config_paht):
    with open(config_paht, 'r') as f:
        info = json.load(f)
        ALPHAVANTAGE_API_TOKEN = info['alphavantage']['key']

g_ts = TimeSeries(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas')
g_ti = TechIndicators(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas')
g_sp = SectorPerformances(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas')

# global constants
MAX_API_RETRIES = 3

# ti params
g_intervals = ['1min', '5min', '15min', '60min']
slow_interval = '1min'
fast_interval = '1min'
ema_fast_period = 4
ema_slow_period = 8
series_type = 'close'
track_interval = '1min'
Ejemplo n.º 5
0
 def new_price(self, ticker, key):
     ALPHAVANTAGE_KEY = key
     ts = TimeSeries(key=ALPHAVANTAGE_KEY, output_format='pandas')
     data, junk = ts.get_daily(symbol=ticker)
     return data['4. close'][-1]
Ejemplo n.º 6
0
def init_data(companies):
    #     pd.DataFrame(),pd.DataFrame(), pd.DataFrame(),[],pd.DataFrame(),
    for comp in companies:
        # main_data[comp] = pd.read_csv(f'./rsc/{comp}_data.csv', sep = ',')
        # main_data[comp].dropna()

        # Input all the technical indicators and the stock times series data

        ti = TechIndicators(key='L2O2TYTG382ETN0N', output_format='pandas')

        # Fetch the simple moving average (SMA) values
        main_data[comp], meta_data = ti.get_sma(symbol=comp,
                                                interval='1min',
                                                time_period=100,
                                                series_type='close')

        # Fetch the exponential moving average (EMA) values
        ema_data, meta_data = ti.get_ema(symbol=comp,
                                         interval='1min',
                                         time_period=100,
                                         series_type='close')
        main_data[comp]['EMA'] = ema_data
        """
        # Fetch the weighted moving average (WMA) values
        wma_data, meta_data = ti.get_wma(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['WMA'] = wma_data
        
        # Fetch the double exponential moving agerage (DEMA) values
        dema_data, meta_data = ti.get_dema(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['DEMA'] = dema_data
        
        # Fetch the triple exponential moving average (TEMA) values
        tema_data, meta_data = ti.get_tema(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['TEMA'] = tema_data
        
        # Fetch the triangular moving average (TRIMA) values 
        trima_data, meta_data = ti.get_trima(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['TRIMA'] = trima_data

        # Fetch the Kaufman adaptive moving average (KAMA) values
        kama_data, meta_data = ti.get_kama(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['KAMA'] = kama_data		

        # Fetch the MESA adaptive moving average (MAMA) values
        mama_data, meta_data = ti.get_mama(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['MAMA'] = mama_data['MAMA']
        main_data[comp]['FAMA'] = mama_data['FAMA']

        # Fetch the triple exponential moving average (T3) values
        t3_data, meta_data = ti.get_t3(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['T3'] = t3_data	
        """

        # Fetch the moving average convergence / divergence (MACD) values
        macd_data, meta_data = ti.get_macd(symbol=comp,
                                           interval='1min',
                                           series_type='close')
        main_data[comp]['MACD'] = macd_data['MACD']
        main_data[comp]['MACD_Hist'] = macd_data['MACD_Hist']
        main_data[comp]['MACD_Signal'] = macd_data['MACD_Signal']
        """		
        # Fetch the moving average convergence / divergence values with controllable moving average type
        macdext_data, meta_data = ti.get_macdext(symbol=comp,interval='1min', series_type='close')
        main_data[comp]['MACDEXT'] = macdext_data['MACD']
        main_data[comp]['MACDEXT_Hist'] = macdext_data['MACD_Hist']
        main_data[comp]['MACDEXT_Signal'] = macdext_data['MACD_Signal']
        """

        # Fetch the stochastic oscillator (STOCH) values
        stoch_data, meta_data = ti.get_stoch(symbol=comp, interval='1min')
        main_data[comp]['SlowK'] = stoch_data['SlowK']
        main_data[comp]['SlowD'] = stoch_data['SlowD']
        """
        # Fetch the stochastic fast (STOCHF) values
        stochf_data, meta_data = ti.get_stochf(symbol=comp,interval='1min')
        main_data[comp]['FastK'] = stochf_data['FastK']
        main_data[comp]['FastD'] = stochf_data['FastD']
        """

        # Fetch the relative strength index (RSI) values
        rsi_data, meta_data = ti.get_rsi(symbol=comp,
                                         interval='1min',
                                         time_period=10,
                                         series_type='close')
        main_data[comp]['RSI'] = rsi_data
        """
        # Fetch the stochastic relative strength index (STOCHRSI) values
        stochrsi_data, meta_data = ti.get_stochrsi(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['STOCHRSI_FastK'] = stochrsi_data['FastK']
        main_data[comp]['STOCHRSI_FastD'] = stochrsi_data['FastD']

        # Fetch the Williams' %R (WILLR) values
        willr_data, meta_data = ti.get_willr(symbol=comp,interval='1min', time_period=10)
        main_data[comp]['WILLR'] = willr_data
        """

        # Fetch the average directional movement index (ADX) values
        adx_data, meta_data = ti.get_adx(symbol=comp,
                                         interval='1min',
                                         time_period=100)
        main_data[comp]['ADX'] = adx_data
        """
        # Fetch the average directional movement index rating (ADXR) values
        adxr_data, meta_data = ti.get_adxr(symbol=comp,interval='1min', time_period=10)
        main_data[comp]['ADXR'] = adxr_data

        # Fetch the absolute price oscillator (APO) values
        apo_data, meta_data = ti.get_apo(symbol=comp,interval='1min', series_type='close')
        main_data[comp]['APO'] = apo_data

        # Fetch the percentage price oscillator (PPO) values
        ppo_data, meta_data = ti.get_ppo(symbol=comp,interval='1min', series_type='close')
        main_data[comp]['PPO'] = ppo_data

        # Fetch the momentum (MOM) values
        mom_data, meta_data = ti.get_mom(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['MOM'] = mom_data

        # Fetch the balance of power (BOP) values
        bop_data, meta_data = ti.get_bop(symbol=comp,interval='1min')
        main_data[comp]['BOP'] = bop_data
        """
        time.sleep(5)

        # Fetch the commodity channel index (CCI) values
        cci_data, meta_data = ti.get_cci(symbol=comp,
                                         interval='1min',
                                         time_period=100)
        main_data[comp]['CCI'] = cci_data
        """
        # Fetch the Chande momentum oscillator (CMO) values
        cmo_data, meta_data = ti.get_cmo(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['CMO'] = cmo_data

        # Fetch the rate of change (ROC) values
        roc_data, meta_data = ti.get_roc(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['ROC'] = roc_data


        # Fetch the rate of change ratio (ROCR) values
        rocr_data, meta_data = ti.get_rocr(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['ROCR'] = rocr_data

        time.sleep(5)
        """
        # Fetch the Aroon (AROON) values
        aroon_data, meta_data = ti.get_aroon(symbol=comp,
                                             interval='1min',
                                             time_period=100)
        main_data[comp]['Aroon Down'] = aroon_data['Aroon Down']
        main_data[comp]['Aroon Up'] = aroon_data['Aroon Up']
        """
        # Fetch the Aroon oscillator (AROONOSC) values
        aroonosc_data, meta_data = ti.get_aroonosc(symbol=comp,interval='1min', time_period=10)
        main_data[comp]['AROONOSC'] = aroonosc_data

        # Fetch the money flow index (MFI) values
        mfi_data, meta_data = ti.get_mfi(symbol=comp,interval='1min', time_period=10)
        main_data[comp]['MFI'] = mfi_data

        # Fetch the 1-day rate of change of a triple smooth exponential moving average (TRIX) values
        triX_train_data['AAPL'], meta_data = ti.get_trix(symbol=comp,interval='1min', time_period=10, series_type='close')
        main_data[comp]['TRIX'] = triX_train_data['AAPL']

        # Fetch the ultimate oscillator (ULTOSC) values
        ultosc_data, meta_data = ti.get_ultsoc(symbol=comp,interval='1min', time_period=10)
        main_data[comp]['ULTOSC'] = ultosc_data

        # Fetch the directional movement index (DX) values
        dX_train_data['AAPL'], meta_data = ti.get_dx(symbol=comp,interval='1min', time_period=10)
        main_data[comp]['DX'] = dX_train_data['AAPL']
        """

        # Fetch the Chaikin A/D line (AD) value
        ad_data, meta_data = ti.get_trix(symbol=comp, interval='1min')
        main_data[comp]['AD'] = ad_data

        # Fetch the on balance volume (OBV) values
        obv_data, meta_data = ti.get_obv(symbol=comp, interval='1min')
        main_data[comp]['OBV'] = obv_data

        # print(main_data[comp].head())

        ts = TimeSeries(key='L2O2TYTG382ETN0N', output_format='pandas')
        intraday_data, meta_data = ts.get_intraday(symbol=comp,
                                                   interval='1min',
                                                   outputsize='full')

        # intraday_data = intraday_data.iloc[9:]
        # intraday_data = intraday_data.reset_index(drop=True)
        # intraday_data.index = main_data[comp].index
        # intraday_data.set_index('date')
        intraday_data.index = pd.Index(
            [index[:-3] for index in intraday_data.index], name='date')
        # intraday_data.set_index('date')
        """
        for index in intraday_data.index:
            print(index)
        print(type(intraday_data.index))
        """

        main_data[comp] = pd.concat([main_data[comp], intraday_data], axis=1)
        print(main_data[comp].index)

        print(main_data[comp].head())

        main_data[comp] = main_data[comp].dropna()
        main_data[comp].index.name = 'date'

        y = np.where(
            main_data[comp]['4. close'].shift(-1) >
            main_data[comp]['4. close'], 1, -1)
        main_data[comp]['Open-Close'] = main_data[comp]['1. open'] - main_data[
            comp]['4. close']
        main_data[comp]['High-Low'] = main_data[comp]['2. high'] - main_data[
            comp]['3. low']
        X = main_data[comp][main_data[comp].columns[0:]]
        split = int(split_percentage * len(main_data[comp]['1. open']))
        X_split_data[comp] = main_data[comp][split:]
        X_train_data[comp] = X[:split]
        y_train_data[comp] = y[:split]
        X_test_data[comp] = X[split:]
        y_test_data[comp] = y[split:]

    return main_data
Ejemplo n.º 7
0
def intraday():
    ts = TimeSeries(key=getenv('ALPHAVANTAGE_API_KEY'),
                    output_format='pandas',
                    indexing_type='date')
    data, meta_data = ts.get_intraday('GOOGL')
Ejemplo n.º 8
0
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.cryptocurrencies import CryptoCurrencies
from pprint import pprint
import matplotlib.pyplot as plt

ts = TimeSeries(key='361NZHAPWQW945GZ', output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',
                                  interval='1min',
                                  outputsize='full')
pprint(data['timestamp'])
# data['4. close'].plot()
# plt.title('Intraday Times Series for the MSFT stock (1 min)')

# cc = CryptoCurrencies(key='361NZHAPWQW945GZ', output_format='pandas')
# data, meta_data = cc.get_digital_currency_intraday(symbol='BTC', market='CNY')
# data['1b. price (USD)'].plot()
# plt.tight_layout()
# plt.title('Intraday value for bitcoin (BTC)')
# plt.grid()

# plt.show()
def obv_strategy(args, portfolio_amount):
    # Retrieve API Key
    from secrets import ALPHA_VANTAGE_TOKEN
    from alpha_vantage.timeseries import TimeSeries
    from alpha_vantage.techindicators import TechIndicators
    ts = TimeSeries(key=ALPHA_VANTAGE_TOKEN, output_format='pandas')
    ti = TechIndicators(key=ALPHA_VANTAGE_TOKEN, output_format='pandas')

    # If no symbols were passed in
    # Retrieve top volatile stocks from Yahoo Finance
    try:
        symbols = args[1].split(',')
    except IndexError:
        print('No symbol(s) provided. Retrieving top 10 from Yahoo Finance...')
        symbols = get_10_best_active_stocks()
    print(symbols)
    confirmation = input('Are these the stocks you want to test? (Y/n): ')
    if confirmation.lower() != 'y':
        return

    interval = '5min'
    current_time = dt.now().time()
    # trading_day = dt.strftime(dt.now() if current_time.hour > 20 else dt.now() - timedelta(1), '%Y-%m-%d')
    trading_day = '2021-02-22'

    results = {}
    holdings = {}

    portfolio = float(portfolio_amount)
    position_size = portfolio / len(symbols)
    print(
        f"Testing a portfolio of $%.2f across {len(symbols)} stock{'s' if len(symbols) > 1 else ''}"
        % portfolio)

    for symbol in symbols:
        if len(symbols) > 2 and symbols.index(symbol) % 2 == 0:
            print('Waiting 1 minute to ensure API availability...')
            t.sleep(60)
        print('===================================')
        print(
            f'Trading {symbol} using {interval} intervals on {trading_day}...\n'
        )

        # Get json object with the intraday data
        try:
            intraday, _ = ts.get_intraday(symbol=symbol,
                                          interval=interval,
                                          outputsize='full')
        except ValueError:
            print(f'Error: {symbol} not found.\n')
            continue
        intraday = intraday.sort_index()
        print(intraday.index)
        intraday = intraday[intraday.index.to_series().between(
            f'{trading_day} 00:00:00', f'{trading_day} 23:59:59')]

        # Get OBV data
        obv_data, _ = ti.get_obv(symbol=symbol, interval=interval)
        obv_data = obv_data.sort_index()
        obv_data['OBV_EMA'] = obv_data['OBV'].ewm(span=20).mean()

        stock_data = pd.concat([intraday, obv_data], axis=1, join="inner")
        print(stock_data)

        Transactions = {}
        transaction_holder = {}
        position = None
        stop_loss_price = None
        initial_loss_percentage = 0.98
        trailing_loss_percentage = 0.96

        Transactions[trading_day] = []
        for i in range(0, len(stock_data.index)):
            datetime = stock_data.index[i]
            interval_date, interval_time = str(datetime).split(' ')

            if is_market_open(stock_data.index[i]):
                close_price = stock_data['4. close'][datetime]
                obv = stock_data['OBV'][datetime]
                obv_ema = stock_data['OBV_EMA'][datetime]

                if not position and obv > obv_ema:
                    shares = math.floor(position_size / close_price)
                    transaction_holder = {
                        'Buy': close_price,
                        'Buy Time': interval_time,
                        'Quantity': shares
                    }
                    position = close_price
                    stop_loss_price = close_price * initial_loss_percentage
                    print(f'Buy triggered by: {obv} > {obv_ema}')
                    print(
                        f'Buy {shares} shares on {interval_date} at {interval_time}: $%.2f'
                        % close_price)
                    print('Set stop loss to $%.2f' % stop_loss_price)

                # If at least 2 indicators from the last 3 intervals tell it to sell
                elif position and obv < obv_ema:
                    transaction_holder['Sell'] = close_price
                    transaction_holder['Sell Time'] = interval_time
                    Transactions[interval_date].append(transaction_holder)
                    print(f'Sell triggered by: {obv} < {obv_ema}')
                    print(
                        f'Sell on {interval_date} at {interval_time}: $%.2f' %
                        close_price)
                    net_profit = (close_price * transaction_holder['Quantity']
                                  ) - (transaction_holder['Buy'] *
                                       transaction_holder['Quantity'])
                    percentage = ((close_price - transaction_holder['Buy']) /
                                  transaction_holder['Buy']) * 100
                    print('Profit/Loss: ${0} ({1}%)\n'.format(
                        ('%.2f' % net_profit), ('%.2f' % percentage)))
                    position = None
                    transaction_holder = {}

                # Sell if its holding and the price has dropped to our stop loss
                elif position and close_price <= stop_loss_price:
                    transaction_holder['Sell'] = close_price
                    transaction_holder['Sell Time'] = interval_time
                    Transactions[interval_date].append(transaction_holder)
                    print('Sell triggered by stop loss $%.2f' %
                          stop_loss_price)
                    print(
                        f'Sell on {interval_date} at {interval_time}: $%.2f' %
                        close_price)
                    net_profit = (close_price * transaction_holder['Quantity']
                                  ) - (transaction_holder['Buy'] *
                                       transaction_holder['Quantity'])
                    percentage = ((close_price - transaction_holder['Buy']) /
                                  transaction_holder['Buy']) * 100
                    print('Profit/Loss: ${0} ({1}%)\n'.format(
                        ('%.2f' % net_profit), ('%.2f' % percentage)))
                    position = None
                    transaction_holder = {}

                # Update trailing stop loss if price is rising
                elif position and close_price > position and (
                        close_price *
                        trailing_loss_percentage) > stop_loss_price:
                    position = close_price
                    stop_loss_price = close_price * trailing_loss_percentage
                    print('Updated trailing stop loss to $%.2f' %
                          stop_loss_price)

                # If the market's about to close, sell remaining positions
                if position and interval_time == '15:59:00':
                    transaction_holder['Sell'] = close_price
                    transaction_holder['Sell Time'] = interval_time
                    Transactions[interval_date].append(transaction_holder)
                    print('Sell triggered by market closing')
                    print(
                        f'Sell on {interval_date} at {interval_time}: $%.2f' %
                        close_price)
                    net_profit = (close_price * transaction_holder['Quantity']
                                  ) - (transaction_holder['Buy'] *
                                       transaction_holder['Quantity'])
                    percentage = ((close_price - transaction_holder['Buy']) /
                                  transaction_holder['Buy']) * 100
                    print('Profit/Loss: ${0} ({1}%)\n'.format(
                        ('%.2f' % net_profit), ('%.2f' % percentage)))
                    position = None
                    transaction_holder = {}
        print()

        # Calculate total results for the symbol on the day
        total_profits = 0
        if len(Transactions[trading_day]) > 0:
            for transaction in Transactions[trading_day]:
                num_shares = transaction['Quantity']
                buy = transaction['Buy']
                if 'Sell' in transaction.keys():
                    sell = transaction['Sell']
                    total_profits += (sell * num_shares) - (buy * num_shares)
                else:
                    holdings[symbol] = transaction
        results[symbol] = total_profits

    # END SYMBOL LOOP

    # Display results
    print(f'\nTOTAL GAINS ON {trading_day}:')
    updated_portfolio = portfolio
    for symbol in results.keys():
        updated_portfolio += results[symbol]
        print(f'{symbol}: $%.2f' % results[symbol])
    print()

    print('On {0}, I turned ${1} into ${2}'.format(
        trading_day, ('%.2f' % portfolio), ('%.2f' % updated_portfolio)))
    if len(holdings.keys()) > 0:
        print("I'm still holding:")
        for symbol in holdings.keys():
            print(f'{symbol}: $%.2f' %
                  (holdings[symbol]['Quantity'] * holdings[symbol]['Buy']))

    plot.figure(figsize=(15, 6))
    plot.bar(results.keys(), results.values())
    plot.title(f'Results from {trading_day}')
    plot.xlabel('Symbols')
    plot.ylabel('Net Gain/Loss ($)')
    plot.show()
from alpha_vantage.timeseries import TimeSeries
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
from pprint import pprint

key_path = "/home/i-sip_iot/s_vv/AlphaVantage.txt"

ts = TimeSeries(key=open(key_path, 'r').read(), output_format='pandas')
data, meta_data = ts.get_intraday(symbol='celg', interval='1min', outputsize='full')
pprint(data.head(20))
print("\n")
print("meta_data: ", meta_data)
Ejemplo n.º 11
0
            "3. low": "1.1622",
            "4. close": "1.1623"
        },
    }
    '''


def build_fx_mongodb(db_name, collection_name):
    database = mongodb_api.build_one_database(db_name, None, None)
    collection = mongodb_api.build_one_collection(database, collection_name)
    #document=mongodb_api.build_one_document(collection,collection_name)
    return collection


ts = TimeSeries(key=api_key,
                retries=5,
                output_format='pandas',
                indexing_type='integer')


def redis_fx_data_delete(r, fx_symbols):
    for item in fx_symbols:
        from_symbol_name, to_symbol_name = item
        scan_ptn = from_symbol_name + "_to_" + to_symbol_name + "_[0-9]*"
        redis_datatabase_api.delete_data_by_ptn(r, scan_ptn)


def main():
    fx_symbols = [("USD", "JPY"), ("CNY", "JPY")]
    fx_collection = build_fx_mongodb("fx_db", "price_collection")
    r = redis_datatabase_api.build_realtime_db()
    count = 0
Ejemplo n.º 12
0
import pandas as pd
from bokeh.plotting import figure, show, curdoc
from bokeh.layouts import column
from math import pi

# read config file
config = configparser.ConfigParser()
config.read('ressources/config.ini')

## read alphavantage key
alpha_key = config['alpha']['key']

stock_name = config['stock']['name']
index_name = config['index']['name']

ts = TimeSeries(key=alpha_key)

data_stock, meta_data = ts.get_daily(stock_name)

data_index, meta_index = ts.get_daily(index_name)


def dict_to_df(data_dict):
    df = pd.DataFrame.from_dict(data_dict, orient='index')
    df = df.reset_index()
    df = df.rename(index=str,
                   columns={
                       "index": "date",
                       "1. open": "open",
                       "2. high": "high",
                       "3. low": "low",
Ejemplo n.º 13
0
def load(l_args, s_ticker, s_start, s_interval, df_stock):
    parser = argparse.ArgumentParser(
        add_help=False,
        prog="load",
        description=
        "Load stock ticker to perform analysis on. When the data source is 'yf', an Indian ticker can be"
        " loaded by using '.NS' at the end, e.g. 'SBIN.NS'. See available market in"
        " https://help.yahoo.com/kb/exchanges-data-providers-yahoo-finance-sln2310.html.",
    )
    parser.add_argument(
        "-t",
        "--ticker",
        action="store",
        dest="s_ticker",
        required=True,
        help="Stock ticker",
    )
    parser.add_argument(
        "-s",
        "--start",
        type=valid_date,
        default="2015-01-01",
        dest="s_start_date",
        help="The starting date (format YYYY-MM-DD) of the stock",
    )
    parser.add_argument(
        "-i",
        "--interval",
        action="store",
        dest="n_interval",
        type=int,
        default=1440,
        choices=[1, 5, 15, 30, 60],
        help="Intraday stock minutes",
    )
    parser.add_argument(
        "--source",
        action="store",
        dest="source",
        type=check_sources,
        default="yf",
        help="Source of historical data. 'yf' and 'av' available.",
    )
    parser.add_argument(
        "-p",
        "--prepost",
        action="store_true",
        default=False,
        dest="b_prepost",
        help=
        "Pre/After market hours. Only works for 'yf' source, and intraday data",
    )

    try:
        # For the case where a user uses: 'load BB'
        if l_args:
            if "-" not in l_args[0]:
                l_args.insert(0, "-t")

        ns_parser = parse_known_args_and_warn(parser, l_args)
        if not ns_parser:
            return [s_ticker, s_start, s_interval, df_stock]

        # Daily
        if ns_parser.n_interval == 1440:

            # Alpha Vantage Source
            if ns_parser.source == "av":
                ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE,
                                output_format="pandas")
                # pylint: disable=unbalanced-tuple-unpacking
                df_stock_candidate, _ = ts.get_daily_adjusted(
                    symbol=ns_parser.s_ticker, outputsize="full")

                # Check that loading a stock was not successful
                if df_stock_candidate.empty:
                    print("")
                    return [s_ticker, s_start, s_interval, df_stock]

                # pylint: disable=no-member
                df_stock_candidate.sort_index(ascending=True, inplace=True)

                # Slice dataframe from the starting date YYYY-MM-DD selected
                df_stock_candidate = df_stock_candidate[ns_parser.
                                                        s_start_date:]

            # Yahoo Finance Source
            elif ns_parser.source == "yf":
                df_stock_candidate = yf.download(ns_parser.s_ticker,
                                                 start=ns_parser.s_start_date,
                                                 progress=False)

                # Check that loading a stock was not successful
                if df_stock_candidate.empty:
                    print("")
                    return [s_ticker, s_start, s_interval, df_stock]

                df_stock_candidate = df_stock_candidate.rename(
                    columns={
                        "Open": "1. open",
                        "High": "2. high",
                        "Low": "3. low",
                        "Close": "4. close",
                        "Adj Close": "5. adjusted close",
                        "Volume": "6. volume",
                    })
                df_stock_candidate.index.name = "date"

            # Check if start time from dataframe is more recent than specified
            if df_stock_candidate.index[0] > pd.to_datetime(
                    ns_parser.s_start_date):
                s_start = df_stock_candidate.index[0]
            else:
                s_start = ns_parser.s_start_date

        # Intraday
        else:

            # Alpha Vantage Source
            if ns_parser.source == "av":
                ts = TimeSeries(key=cfg.API_KEY_ALPHAVANTAGE,
                                output_format="pandas")
                # pylint: disable=unbalanced-tuple-unpacking
                df_stock_candidate, _ = ts.get_intraday(
                    symbol=ns_parser.s_ticker,
                    outputsize="full",
                    interval=str(ns_parser.n_interval) + "min",
                )

                # Check that loading a stock was not successful
                if df_stock_candidate.empty:
                    print("")
                    return [s_ticker, s_start, s_interval, df_stock]

                # pylint: disable=no-member
                df_stock_candidate.sort_index(ascending=True, inplace=True)

                # Slice dataframe from the starting date YYYY-MM-DD selected
                df_stock_candidate = df_stock_candidate[ns_parser.
                                                        s_start_date:]

                # Check if start time from dataframe is more recent than specified
                if df_stock_candidate.index[0] > pd.to_datetime(
                        ns_parser.s_start_date):
                    s_start = df_stock_candidate.index[0]
                else:
                    s_start = ns_parser.s_start_date

            # Yahoo Finance Source
            elif ns_parser.source == "yf":
                s_int = str(ns_parser.n_interval) + "m"

                d_granularity = {
                    "1m": 6,
                    "5m": 59,
                    "15m": 59,
                    "30m": 59,
                    "60m": 729
                }

                s_start_dt = datetime.utcnow() - timedelta(
                    days=d_granularity[s_int])
                s_date_start = s_start_dt.strftime("%Y-%m-%d")

                if s_start_dt > ns_parser.s_start_date:
                    # Using Yahoo Finance with granularity {s_int} the starting date is set to: {s_date_start}

                    df_stock_candidate = yf.download(
                        ns_parser.s_ticker,
                        start=s_date_start,
                        progress=False,
                        interval=s_int,
                        prepost=ns_parser.b_prepost,
                    )

                else:
                    df_stock_candidate = yf.download(
                        ns_parser.s_ticker,
                        start=ns_parser.s_start_date.strftime("%Y-%m-%d"),
                        progress=False,
                        interval=s_int,
                        prepost=ns_parser.b_prepost,
                    )

                # Check that loading a stock was not successful
                if df_stock_candidate.empty:
                    print("")
                    return [s_ticker, s_start, s_interval, df_stock]

                if s_start_dt > ns_parser.s_start_date:
                    s_start = pytz.utc.localize(s_start_dt)
                else:
                    s_start = ns_parser.s_start_date

                df_stock_candidate = df_stock_candidate.rename(
                    columns={
                        "Open": "1. open",
                        "High": "2. high",
                        "Low": "3. low",
                        "Close": "4. close",
                        "Adj Close": "5. adjusted close",
                        "Volume": "6. volume",
                    })
                df_stock_candidate.index.name = "date"

        s_intraday = (f"Intraday {s_interval}",
                      "Daily")[ns_parser.n_interval == 1440]

        print(
            f"Loading {s_intraday} {ns_parser.s_ticker.upper()} stock "
            f"with starting period {s_start.strftime('%Y-%m-%d')} for analysis.\n"
        )

        return [
            ns_parser.s_ticker.upper(),
            s_start,
            str(ns_parser.n_interval) + "min",
            df_stock_candidate,
        ]

    except Exception as e:
        print(e,
              "\nEither the ticker or the API_KEY are invalids. Try again!\n")
        return [s_ticker, s_start, s_interval, df_stock]

    except SystemExit:
        print("")
        return [s_ticker, s_start, s_interval, df_stock]
Ejemplo n.º 14
0
from twilio.rest import Client
from config import *
from multiprocessing import Process
import multiprocessing
from itertools import product
import requests, json, collections
import time 
import pandas as pd
import matplotlib.pyplot as plt


headers = {"APCA-API-KEY-ID": alpaca_key, "APCA-API-SECRET-KEY": secret_key}
client = Client(twilio_sid, twilio_auth)

indicators = TechIndicators(alphavantage_key, output_format='pandas')
time_series_data = TimeSeries(alphavantage_key, output_format='pandas')


def get_clock():
    request = requests.get(clock_url, headers=headers)
    return json.loads(request.content)


def get_stock_data(ticker):
    parameters = {
    "apikey": td_key,
    "symbol": ticker
    }
    request = requests.get(url=td_quotes_url, params=parameters).json()
    data = pd.DataFrame.from_dict(request, orient='index').reset_index(drop=True)
    
Ejemplo n.º 15
0
from pprint import pprint
from alpha_vantage.timeseries import TimeSeries


def get_stock_symbols_for_text(search_text):
    data, metadata = ts.get_symbol_search(search_text)
    pprint(data[['1. symbol', '2. name', '8. currency']])
    option = input("Enter the company for which u want the info :")
    company = data.loc[int(option), ['1. symbol']].values
    get_final_quote(company)


def get_final_quote(company):
    data, meta_data = ts.get_quote_endpoint(company[0])
    print(data)


if __name__ == '__main__':
    ts = TimeSeries(key='A0IASAGQJJ1GUZDO',
                    output_format='pandas',
                    indexing_type='integer')
    # Get json object with the intraday data and another with  the call's metadata
    name = input("Enter the company name to search :")
    get_stock_symbols_for_text(name)
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 29 21:41:13 2020

@author: elijah
"""
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
import time

api_key = '52IJ61RCT32DB1VZ'
# Using full to have all intraday data
ts = TimeSeries(key=api_key, output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',
                                  interval='1min',
                                  outputsize='full')
# Using date as index
ts2 = TimeSeries(key=api_key, output_format='pandas', indexing_type='date')
data2, meta_data = ts2.get_intraday(symbol='JNJ',
                                    interval='5min',
                                    outputsize='compact')
# Using number as index
ts3 = TimeSeries(key=api_key, output_format='pandas', indexing_type='integer')
data3, meta_data = ts3.get_intraday(symbol='JNJ',
                                    interval='5min',
                                    outputsize='compact')
# pprint gives more formatting choice when printing
from pprint import pprint
pprint(data3.head(2))

# Technical indicators Sample
from django.http import HttpResponseNotFound, JsonResponse
from django.views.decorators.http import require_http_methods
from django.views.decorators.csrf import csrf_exempt

import bcrypt

from project1.api.models import UserModel, PurchaseModel, StockModel, PortfolioModel

from alpha_vantage.timeseries import TimeSeries

from datetime import datetime
from time import sleep

# don't put this here in real code! you are welcome to use this key if you would like
av_api_key = "B6Z376P6CGR0XAL5"
ts = TimeSeries(key=av_api_key)
"""
You will create many 4 key views here: register, buy, sell, and list

register - allows a user to register and obtain an API token
buy - allows a user to buy some stocks by submitting a symbol and an amount
sell - allows a user to sell some stocks by submitting a symbol and an amount
list - allows a user to see their current portfolio, does not take arguments
"""


@require_http_methods(["POST"])
@csrf_exempt
def register(request):
    fields = ["first_name", "last_name", "username", "password"]
Ejemplo n.º 18
0
# Stock Market prediction with Machine Learning
# Senior Project at BYU-I by Matt Wyndham
# get your own API Key from Alpha Vantage: https://www.alphavantage.co/documentation/

from myapikey import APIkey
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt

ts = TimeSeries(key=APIkey, output_format='pandas')
data, meta_data = ts.get_intraday(symbol='MSFT',
                                  interval='1min',
                                  outputsize='full')
data['4. close'].plot()
plt.title('Intraday Times Series for the MSFT stock (1 min)')
plt.show()
Ejemplo n.º 19
0
#importar librerias
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
from alpha_vantage.sectorperformance import SectorPerformances
from alpha_vantage.cryptocurrencies import CryptoCurrencies
import matplotlib
import matplotlib.pyplot as plt
#import os
# Make plots bigger
matplotlib.rcParams['figure.figsize'] = (20.0, 10.0)
import pandas as pd
from datetime import datetime

#llave de alpha_vantage
ts = TimeSeries(key='FH69CNJPTEAVXKHO', output_format='pandas')

#importar datos

#APPLE
aapl, meta_data = ts.get_intraday(symbol='AAPL',
                                  interval='1min',
                                  outputsize='full')
aapl = aapl.rename(
    columns={
        '1. open': 'open',
        '2. high': 'high',
        '3. low': 'low',
        '4. close': 'close',
        '5. volume': 'volume'
    })
Ejemplo n.º 20
0
from alpha_vantage.timeseries import TimeSeries
import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import register_matplotlib_converters

register_matplotlib_converters()

ts = TimeSeries(key='VX39C7NJDNVB23C4',output_format='pandas')

ticker = 'MIST'

data, meta_data = ts.get_intraday(symbol=ticker,interval='5min', outputsize='full')

#df = pd.DataFrame({'x':data.index, 'y1' :data['1. open'], 'y2' :data['4. close'], 'y3' :data['5. volume']})

# multiple line plot
#plt.plot( df['x'], df['y1'], color='skyblue', linewidth=4, label='Open')
#plt.plot( df['x'], df['y2'], color='green', linewidth=4, label='Close')
#plt.plot( df['x'], df['y3'], color='yellow', linewidth=4, label='Volume')
#plt.legend()


data['4. close'].plot(label='Close')
data['5. volume'].plot(label='Volume')
plt.legend()
plt.title('Intraday TimeSeries ' + ticker)
plt.show() 
Ejemplo n.º 21
0
#!/bin/python3

import yfinance as yf
from alpha_vantage.timeseries import TimeSeries
import datetime

stocks = ['GOOGL', 'AAPL', 'TD', 'AMZN']
savePath = "/home/angad/Pictures/stocks/"

# Your key here
key = 'MCZCTGXDDSEVULB2'
ts = TimeSeries(key)
aapl, meta = ts.get_daily(symbol='AAPL')
print(aapl['2020-02-07'])
Ejemplo n.º 22
0
# initiate keys
ALPACA_API_KEY = os.path.expandvars('$ALPACA_API_KEY')
ALPACA_API_SECRET_KEY = os.path.expandvars('$ALPACA_API_SECRET_KEY')
ALPACA_API_BASE_URL = "https://paper-api.alpaca.markets"
ALPHA_VANTAGE_KEY = os.path.expandvars('$ALPHA_VANTAGE_KEY')

# connect to alpaca
alpaca = tradeapi.REST(ALPACA_API_KEY,
                       ALPACA_API_SECRET_KEY,
                       ALPACA_API_BASE_URL,
                       api_version='v2')
account = alpaca.get_account()

# initiate tech indicator and time series
ti = TechIndicators(key=ALPHA_VANTAGE_KEY, output_format='pandas')
ts = TimeSeries(ALPHA_VANTAGE_KEY, output_format='pandas')

while (True):
    sma = ti.get_sma(symbol='IBM', interval='1min',
                     time_period=30)[0].tail(2)['SMA']
    current_sma = sma[1]
    last_sma = sma[0]

    price = ts.get_intraday(symbol='IBM',
                            interval='1min')[0].tail(2)['4. close']
    current_price = price[1]
    last_price = price[0]

    try:
        position = int(alpaca.get_position('IBM').qty)
    except:
Ejemplo n.º 23
0
 def get_intraday(name, duration):
     ts = TimeSeries(key='YOUR_OWN_API', output_format='pandas')
     data, metadata = ts.get_intraday(symbol=Company.comp[name],
                                      interval=duration,
                                      outputsize='full')
     return data
Ejemplo n.º 24
0
@author: Avinash
"""
#Packages Required

import pandas as pd
from alpha_vantage.timeseries import TimeSeries
import requests

stock = "RELIANCE.NS"
terms = ["Reliance", "Jio"]
begin_date = "2015-07-01"
end_date = "2018-03-18"

#86GWLA2M8WL2J702
API_KEY = "86GWLA2M8WL2J702"
ts = TimeSeries(key=API_KEY)

print(ts.TIME_SERIES_DAILY_ADJUSTED(symbol=stock))

url = "https://www.alphavantage.co/query"

symbol = "RELIANCE.NS"
function = "TIME_SERIES_DAILY_ADJUSTED"
api_key = "86GWLA2M8WL2J702"

data = {
    "function": function,
    "symbol": symbol,
    "outputsize": "full",
    "datatype": "csv",
    "apikey": api_key
Ejemplo n.º 25
0
def dlquotes(avKey, filePath, email, password, rh_watchlist):
    from datetime import datetime
    import os
    import sys
    import requests
    import robin_stocks as r
    import time
    from alpha_vantage.timeseries import TimeSeries
    ts = TimeSeries(key=avKey, output_format='pandas', indexing_type='date')
    processed_count = 0
    failed_symbols = []
    wlFile = filePath + 'Watchlist.csv'
    if os.path.exists(wlFile):
        os.remove(wlFile)
    f = open(wlFile, 'a')
    try:
        print("Logging into Robinhood to fetch watchlist symbols ... ")
        print("")
        rh_li_starttime = time.time()
        r.login(email, password)
        rh_li_endtime = time.time()
        rh_li_time = rh_li_endtime - rh_li_starttime
        print("Logged in. Time to complete login:"******"")
        print("Fetching watchlist symbols ...")
        print("")
        rh_wl_starttime = time.time()
        watchlist = r.get_watchlist_by_name(name=rh_watchlist, info=None)
        rh_wl_endtime = time.time()
        rh_wl_time = rh_wl_endtime - rh_wl_starttime
        print("Got the watchlist. Time to complete:", rh_wl_time)
        print("")
        watchlistDict = {}
        print("Putting watchlist symbols into file at", filePath+'Watchlist.csv ...')
        print("")
        for item in watchlist:
            url = item['instrument']
            r = requests.get(url)
            data_json = r.json()
            # print(str(data_json))  # print this to see more symbol info.
            watchlistDict[data_json['symbol']] = data_json['simple_name']
            print("Processing", str(watchlistDict[data_json['symbol']]))
            f.write(str(data_json['simple_name'])+",")
        f.close()
    except Exception as e:
        sys.exit(e)

    start_time = datetime.now()
    oldepoch = time.time()
    print("")
    print("Starting Quotes Download ...")
    print("Total number of symbols to update: ", len(watchlistDict))
    print("")
    total_symbols = len(watchlistDict)
    symbols_remaining = total_symbols
    processed_count_continuous = 0
    for _symbol, name in watchlistDict.items():
        try:
            rate_limit_begin_time = time.time()
            processed_count = processed_count+1
            processed_count_continuous = processed_count_continuous+1
            print(_symbol,": ",name)
            data, meta = ts.get_daily(_symbol,outputsize='full')
            fileName = _symbol + ".csv"
            fh = open(filePath + fileName, "w")
            fh.write( data.to_csv() )
            fh.close()
            symbols_remaining = symbols_remaining-1
            # Adjustments for AlphaVantage's Rate Limit, 5 symbols per minute
            if minute_passed(oldepoch) or processed_count==5:
                rate_limit_end_time = time.time()
                time_passed = rate_limit_end_time - rate_limit_begin_time
                pause_time = 60 - time_passed
                processed_count=0
                print("*** Pausing for ",pause_time," seconds.")
                print("*** ",symbols_remaining," symbols remain.")
                time_passed = datetime.now() - start_time
                print("*** Quotes Download has been running for ",time_passed)
                download_rate = time_passed / processed_count_continuous
                estimated_time_remaining = symbols_remaining * download_rate
                print("*** Estimated time remaining: ",estimated_time_remaining)
                est_end_time = datetime.now() + estimated_time_remaining
                print("*** Estimated end time: ",est_end_time)
                print("")
                time.sleep(pause_time)
                oldepoch = time.time()
        except Exception as e:
            print("Error on "+_symbol+": ", e)
            failed_symbols.append(_symbol)

    if len(failed_symbols) > 0:
        print("Initial download complete. Pausing 1 minute before downloading ", len(failed_symbols) ," failed symbols.")
        print("Failed symbols: "+str(failed_symbols))
        print("Please wait 1 minute ...")
        time.sleep(60)
        print("Now downloading failed symbols ...")
        name="Failed Symbol"
        symbols_remaining = len(failed_symbols)
        for _symbol in failed_symbols:
            try:
                rate_limit_begin_time = time.time()
                processed_count = processed_count+1
                processed_count_continuous = processed_count_continuous+1
                print(_symbol,": ",name)
                data, meta = ts.get_daily(_symbol,outputsize='full')
                fileName = _symbol + ".csv"
                fh = open(filePath + fileName, "w")
                fh.write( data.to_csv() )
                fh.close()
                symbols_remaining = symbols_remaining-1
                # Adjustments for AlphaVantage's Rate Limit, 5 symbols per minute
                if minute_passed(oldepoch) or processed_count==5:
                    rate_limit_end_time = time.time()
                    time_passed = rate_limit_end_time - rate_limit_begin_time
                    pause_time = 60 - time_passed
                    processed_count=0
                    print("*** Pausing for ",pause_time," seconds.")
                    print("*** ",symbols_remaining," symbols remain.")
                    time_passed = datetime.now() - start_time
                    print("*** This download has been running for ",time_passed)
                    download_rate = time_passed / processed_count_continuous
                    estimated_time_remaining = symbols_remaining * download_rate
                    print("*** Estimated time remaining: ",estimated_time_remaining)
                    est_end_time = datetime.now() + estimated_time_remaining
                    print("*** Estimated end time: ",est_end_time)
                    time.sleep(pause_time)
                    oldepoch = time.time()
            except Exception as e:
                print("***************************")
                print("Error on "+_symbol+": ",e)
                print(_symbol," quotes will not be downloaded on this run. Please try again.")
                print("***************************")

    else:
        end_time = datetime.now()
        print("**************************")
        print("")
        print("There were no failed symbols.")
        print("Time Elapsed: "+ str(end_time - start_time) )
        print("Completed at ",end_time)
Ejemplo n.º 26
0

def printtimes(i, f, timesData):
    print("At " + timesData[i][0] + " the max price was: " +
          str(timesData[i][2]))
    print("At " + timesData[f][0] + " the min price was: " +
          str(timesData[f][3]))
    profit = float(timesData[f][3]) / float(timesData[i][2]) - 1
    print("That gives a profit of " + "{0:.3%}".format(profit))
    #print("That means a profit of "+"{0:.3%}".format(profit/(i-f))+" per minute")
    print()


key = open("passwords.txt", 'r').readline().rstrip()

ts = TimeSeries(key=key, output_format='csv')
data, meta_data = ts.get_intraday(symbol='TSLA', interval='1min')
timesData = [row for row in data]

profitTimes = []

for i in range(2, 16):
    for f in range(1, i):
        if (comparetimes(i, f, timesData)):
            printtimes(i, f, timesData)
            profitTimes.append(
                [i, f, (float(timesData[f][3]) / float(timesData[i][2]) - 1)])


def profit(e):
    return e[2]
Ejemplo n.º 27
0
def get_data(ticker):
    try:
        print("Processing data for {}".format(ticker))
        # create empty dataframes
        TEMPdf = pd.DataFrame()
        df = pd.DataFrame()
        global df2
        #log.WriteToLog(LOGFILE,ticker)
        # Price data
        SUCCESS = 0
        DCHANGE = 0
        while SUCCESS < 10:
            try:
                APIkey = AV_func.GetAPIkey(
                    KEYS)  # get a new API key each time the script runs
                time.sleep(WAITAPI)
                ts = TimeSeries(key=APIkey, output_format='pandas')
                data = ts.get_quote_endpoint(symbol=ticker)  #;
                TEMPdf = df.append(data)
                DTICKER = TEMPdf.iat[0, 0]
                DTICKER = '"{}"'.format(DTICKER)
                log.WriteToLog(LOGFILE, "Getting data for {}".format(DTICKER))
                DPRICE = TEMPdf.iat[0, 4]
                DCLOSE = TEMPdf.iat[0, 7]
                DCHANGE = TEMPdf.iat[0, 9]
                DCHANGE = '"{}"'.format(DCHANGE)
                TEMPdf = pd.DataFrame()  # create empty dataframe
                SUCCESS = True
                break
            except:
                log.WriteToLog(LOGFILE, "{} - Price exception".format(ticker))
                SUCCESS = SUCCESS + 1
                log.WriteToLog(
                    LOGFILE,
                    "{} - Error found, {}, attempt no. {}. ({})".format(
                        DCHANGE, DCHANGE, SUCCESS, APIkey))
                time.sleep(WAITERR)
        # RSI data
        log.WriteToLog(LOGFILE, "Get RSI data for {}".format(DTICKER))
        #SUCCESS = 0
        while SUCCESS < 10:
            try:
                APIkey = AV_func.GetAPIkey(
                    KEYS)  # get a new API key each time the script runs
                time.sleep(WAITAPI)
                ti = TechIndicators(key=APIkey, output_format='pandas')
                dataRSI = ti.get_rsi(symbol=ticker,
                                     interval=RSI_INT,
                                     time_period=RSI_PERIOD)
                dataRSI = dataRSI[0]
                TEMPdf = TEMPdf.append(dataRSI)
                RS = TEMPdf.last('1D')
                RS = RS.iat[0, 0]
                RSR = round(RS, 2)
                # suggest buy/sell based on RSI & price action
                # #def GetSuggestion(RS,DCLOSE,DPRICE,BUY,SELL,HOLD,RSIHIGH,RSIVHIGH,RSILOW,RSIVLOW):
                SUGGESTION = AV_func.GetSuggestion(RS, DCLOSE, DPRICE, BUY,
                                                   SELL, HOLD, RSIHIGH,
                                                   RSIVHIGH, RSILOW, RSIVLOW)
                SUGGESTION = '"{}"'.format(SUGGESTION)
                #log.WriteToLog(LOGFILE,"Suggestion for {}: {}".format(ticker,SUGGESTION))
                #df2 = df2.append(df)
                break
                #logging.info(df2)
            except:
                log.WriteToLog(LOGFILE, "{} - RSI exception".format(ticker))
                SUCCESS = SUCCESS + 1
                log.WriteToLog(
                    LOGFILE,
                    "{} - Error found, {}, attempt no. {}. ({})".format(
                        ticker, "RSI", SUCCESS, APIkey))
                time.sleep(WAITERR)
        INSERT_CMD = "INSERT INTO {} VALUES (NULL,{},{},{},{},{},{},{},NULL)".format(
            TABLE_NAME, DDATE, DTICKER, DPRICE, DCLOSE, DCHANGE, RSR,
            SUGGESTION)
        log.WriteToLog(LOGFILE, INSERT_CMD)
        cursor.execute(INSERT_CMD)
        connection.commit()
    except:  # catch all exceptions in the same way
        log.WriteToLog(LOGFILE, "Main Error catch {}".format(ticker))
        log.WriteToLog(
            LOGFILE, "{} - Error found, {}, attempting to continue...".format(
                ticker, "Main Error catch"))
Ejemplo n.º 28
0
 def __init__(self, api_key=alpha_vantage_api_key, ticker_symbol=alpha_vantage_ticker_symbol, tezos_key=tezos_user_key, oracle_contract_address=oracle_address):
     self.oracle_contract_address = oracle_contract_address
     self.pytezos_instance = pytezos.using(key=tezos_key, shell='carthagenet')
     self.time_series = TimeSeries(key=api_key, output_format='json')
     self.ticker_symbol = ticker_symbol
Ejemplo n.º 29
0
import pandas as pd
from alpha_vantage.timeseries import TimeSeries
from alpha_vantage.techindicators import TechIndicators
import matplotlib.pyplot as plt

api_key = 'RNZPXZ6Q9FEFMEHM'

ts = TimeSeries(key=api_key, output_format='pandas')
data_ts, meta_data_ts = ts.get_intraday(symbol='MSFT',
                                        interval='1min',
                                        outputsize='full')

period = 60

ti = TechIndicators(key=api_key, output_format='pandas')
data_ti, meta_data_ti = ti.get_sma(symbol='MSFT',
                                   interval='1min',
                                   time_period=period,
                                   series_type='close')

df1 = data_ti
df2 = data_ts['4. close'].iloc[period - 1::]

df2.index = df1.index

total_df = pd.concat([df1, df2], axis=1)
print(total_df)

total_df.plot()
plt.show()
def connect_time_series_api(key=call_api):
    api_connect = TimeSeries(key)
    return api_connect