Пример #1
0
def get_action_for_training(df, date):
    preprocess_obj = preprocess()
    starting_date_obj = datetime.datetime.strptime(
        date, "%Y-%m-%d")
    num_days_next_three_months = preprocess_obj.get_next_three_months_days(
        date)
    num_days_next_two_months = preprocess_obj.get_next_two_months_days(date)
    next_three_month_date = starting_date_obj + \
        datetime.timedelta(num_days_next_three_months)
    next_two_month_date = starting_date_obj + \
        datetime.timedelta(num_days_next_two_months)
    df_opening_calc = investpy.get_stock_historical_data(
        stock='SBI', country='India', from_date=starting_date_obj.strftime("%d/%m/%Y"), to_date=next_two_month_date.strftime("%d/%m/%Y"))
    df_closing_calc = investpy.get_stock_historical_data(
        stock='SBI', country='India', from_date=starting_date_obj.strftime("%d/%m/%Y"), to_date=next_three_month_date.strftime("%d/%m/%Y"))

    # to calculate date till it is found in df
    next_three_month_date_temp = next_three_month_date
    while next_three_month_date_temp not in df.index:
        next_three_month_date_temp = next_three_month_date_temp - \
            datetime.timedelta(1)

    # to calculate date till it is found in df
    next_two_month_date_temp = next_two_month_date
    while next_two_month_date_temp not in df.index:
        next_two_month_date_temp = next_two_month_date_temp - \
            datetime.timedelta(1)

    if df_closing_calc.loc[next_three_month_date_temp]['Close'] > df_opening_calc.loc[next_two_month_date_temp]['Close']:
        return 'Long'
    elif df_closing_calc.loc[next_three_month_date_temp]['Close'] < df_opening_calc.loc[next_two_month_date_temp]['Close']:
        return 'Short'
    else:
        return 'Hold'
Пример #2
0
    def historico_acoes(self, acao, status='Close'):
        """
        :param acao: acao que tu quer pegar (mesmo sendo só uma, deve ser passada como lista)
        :param status: Pode ser Close / Open / Low / High / Volume / Currency
        :return: retorno dos dados
        """

        if len(acao) > 1:
            dados = pd.DataFrame()
            for papel in acao:
                dados[papel] = inv.get_stock_historical_data(
                    papel,
                    self.pais,
                    from_date=self.data_inicial,
                    to_date=self.data_final,
                    as_json=False,
                    order=self.ordem,
                    interval=self.intervalo)[status]
            if self.json:
                data = dict()
                for colunas in dados.columns:
                    paper = list()
                    for infos in range(len(dados)):
                        paper.append({
                            "data":
                            dados.index[infos].strftime("%Y-%m-%d"),
                            "preço":
                            dados[colunas][infos]
                        })
                    data[colunas] = paper
                return data

            else:
                return dados

                # to_json -> json.dumps(limpando, ensure_ascii=False).encode('utf8')

        else:
            dados = pd.DataFrame()
            for papel in acao:
                dados = inv.get_stock_historical_data(
                    papel,
                    self.pais,
                    from_date=self.data_inicial,
                    to_date=self.data_final,
                    as_json=False,
                    order=self.ordem,
                    interval=self.intervalo)
            if self.json:
                stock_json = dict()
                dados['Date'] = dados.index.strftime("%Y-%m-%d")
                stock_json[acao[0]] = dados.to_dict('records')
                return stock_json
            else:
                return dados
Пример #3
0
def check_stock(stock):
	check_result = False

	try:
		investpy.get_stock_historical_data(stock=stock,
                                        country='South Korea')
		check_result = True
	except:
		check_result = False

	return check_result
def descargar_cotizaciones_diarias_investing_api(info_activos, fecha_inicio, fecha_fin):

    data = investpy.get_stock_historical_data(
        'ACS', 'spain', '01/01/2019', '31/12/2019')

    data = investpy.get_stock_historical_data(
        stock=info_activos['ticker'], country=info_activos['market'], from_date=fecha_inicio.strftime('%d/%m/%Y'), to_date=fecha_fin.strftime('%d/%m/%Y'), order='descending')
    data['Fecha'] = data.index
    cols = ['Fecha', 'Close', 'Open', 'High', 'Low', 'Volume']
    data = data[cols]
    data.reset_index(drop=True, inplace=True)
    data.columns = ['Fecha', 'Último', 'Apertura', 'Máximo', 'Mínimo', 'Vol.']
    return data
Пример #5
0
def only():
    stock = request.form.get('stockName').upper()
    start = request.form.get('startDate')
    end = request.form.get('endDate')
    country = request.form.get('countryName')
    model = load_model('model.h5')

    start_date = datetime.strptime(start, "%Y-%m-%d").strftime("%d/%m/%Y")
    end_date = datetime.strptime(end, "%Y-%m-%d").strftime("%d/%m/%Y")
    df = investpy.get_stock_historical_data(stock=stock,
                                            country=country,
                                            from_date=start_date,
                                            to_date=end_date)
    df.drop('Currency', axis=1, inplace=True)
    data = df.filter(['Close'])
    dataset = data.values
    scaler = MinMaxScaler(feature_range=(0, 1))
    scaled_data = scaler.fit_transform(dataset)

    df = investpy.get_stock_historical_data(stock=stock,
                                            country=country,
                                            from_date=start_date,
                                            to_date=end_date)
    df.drop('Currency', axis=1, inplace=True)
    pred_data = df.filter(['Close'])

    last_60_days = pred_data[-60:].values

    last_60_days_scaled = scaler.fit_transform(last_60_days)
    X_test = []
    X_test.append(last_60_days_scaled)
    X_test = np.array(X_test)
    X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], 1))

    pred_price = model.predict(X_test)
    pred_price = scaler.inverse_transform(pred_price)
    print(pred_price)

    com_profile = investpy.get_stock_company_profile(stock=stock,
                                                     country=country,
                                                     language='english')
    profile = com_profile['desc']

    return render_template('only.html',
                           stock=stock,
                           start_date=start_date,
                           end_date=end_date,
                           profile=profile,
                           pred_price=pred_price)
Пример #6
0
def consultar_acao(stock, country, from_date, to_date, interval):
    df = ip.get_stock_historical_data(stock=stock,
                                      country=country,
                                      from_date=from_date,
                                      to_date=to_date,
                                      interval=interval)
    return df
Пример #7
0
def get_df_ticker(ticker, country, age='2Y'):
    # function to get ticker OLHC prices from name and country
    # by default 2 years back from today
    if 'Y' in age:
        age = float(age.strip('Y'))
        date_since = dt.date.today() - dt.timedelta(days=age*365.25)
    elif 'M' in age:
        date_since = dt.date.today() - dt.timedelta(days=age*31)
    date_since = date_since.strftime('%d/%m/%Y')
    date_to = dt.date.today().strftime('%d/%m/%Y')
    try:
        df = investpy.get_stock_historical_data(stock=ticker, 
                                            country=country, 
                                            from_date=date_since,
                                            to_date=date_to, 
                                            as_json=False, 
                                            order='ascending')
        df.reset_index(inplace=True)
        df.columns = [i.lower() for i in df.columns]
    except:
        # couldn't retrieve data!!
        raise Exception(f"Couldn\'t get data for {ticker} in {country}")
        df = pd.DataFrame([])
    
    return df
Пример #8
0
def show_scatter_and_return_corr(name: str, country: str, start_date: str,
                                 end_date: str):
    BTC = investpy.get_crypto_historical_data(crypto='bitcoin',
                                              from_date=start_date,
                                              to_date=end_date)
    try:
        security = investpy.indices.get_index_historical_data(
            index=name,
            country=country,
            from_date=start_date,
            to_date=end_date,
            as_json=False,
            order='ascending',
            interval='Daily')
    except:
        security = investpy.get_stock_historical_data(stock=name,
                                                      country=country,
                                                      from_date=start_date,
                                                      to_date=end_date)
    security = security.reindex(BTC.index)
    security.fillna(value={'Volume': 0}, inplace=True)
    security.fillna(method='ffill', inplace=True)
    security.dropna(how='any', inplace=True)
    BTC = BTC.reindex(security.index)

    plt.scatter(x=BTC.Close, y=security.Close)
    plt.show()

    return security, np.round(np.corrcoef(BTC.Close, security.Close)[0, 1], 2)
Пример #9
0
def get_investiments_returns(pct_change_window=1):

    stocks_name = get_assets_env_var('STOCKS')
    funds_name = get_assets_env_var('FUNDS')

    today = date.today()
    today = today.strftime("%d/%m/%Y")

    close_prices = []
    for stock in stocks_name:
        prices = inv.get_stock_historical_data(stock=stock,
                                               country='brazil',
                                               from_date='01/01/2015',
                                               to_date=today)
        close_prices.append(prices.Close)

    for fund in funds_name:
        prices = inv.get_fund_historical_data(fund,
                                              country='brazil',
                                              from_date='01/01/2015',
                                              to_date=today)
        close_prices.append(prices.Close)

    prices = pd.concat(close_prices, axis=1)
    prices = prices.dropna()

    columns_name = []
    for column_name in (stocks_name + funds_name):
        columns_name.append(column_name[:10])

    prices.columns = columns_name

    returns = prices.pct_change(pct_change_window).dropna()

    return returns
Пример #10
0
def get_price(stock: str, country: str, start=None, end=None) -> dfType:
    """
    investypyでの株価を取得する
    :param country: investpyで定義される国
    :param stock:証券コード
    :param start:取得開始日時
    :param end:取得終了日時 default:実行日時
    :return:価格情報のデータフレーム
    """
    if end is None:
        end = datetime.datetime.now().strftime("%d/%m/%Y")

    if start is None:
        start = (datetime.datetime.now() -
                 datetime.timedelta(days=100)).strftime("%d/%m/%Y")

    try:
        res = investpy.get_stock_historical_data(stock=stock,
                                                 from_date=start,
                                                 to_date=end,
                                                 country=country)
    except RuntimeError:
        print("価格の取得に失敗しました。")

        res = ""

    return res
def getDailyFromStock(isin):

    years_obs = timedelta(days=365.24) * 1  #~250 obs
    endus = datetime.now()
    endeu = endus.strftime("%d/%m/%Y")  #EU to US date conversion
    startus = endus - years_obs
    starteu = startus.strftime("%d/%m/%Y")

    country_iniziali = isin[:2]  #ISIN conversion
    country = country_isin.get(country_iniziali)

    periodicita = "Daily"  #time basis from API, daily-weekly-monthly...

    stock = inv.stocks.get_stocks(country=country)
    info_gen = stock.loc[stock["isin"] == isin]
    #info_tech = inv.stocks.get_stock_information(info_gen["symbol"].values[0], country, as_json=False)
    df = inv.get_stock_historical_data(stock=info_gen["symbol"].values[0],
                                       country=country,
                                       from_date=starteu,
                                       to_date=endeu,
                                       as_json=False,
                                       order='ascending',
                                       interval=periodicita)

    return df, info_gen,  #info_tech
Пример #12
0
    def ApiGetAllByIsin(self, isin, tipologia_strumento, periodicita, start):    #restituisce il nome di corrispondenza all'isin inserito

        country_iniziali = isin[:2]
        country = GLOBE.country_isin.get(country_iniziali)

        endus = datetime.now()
        endeu = endus.strftime("%d/%m/%Y")
        # print(inv.stocks.get_stock_countries())        

        if tipologia_strumento == GLOBE.mappa_strumenti.get("stock"):

            stock = inv.stocks.get_stocks(country = country)
            info_gen = stock.loc[stock["isin"] == isin]
            df = inv.get_stock_historical_data(stock = info_gen["symbol"].values[0], country = country, from_date = start, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita[periodicita])

        elif tipologia_strumento == GLOBE.mappa_strumenti.get("etf"):

            etf = inv.etfs.get_etfs(country = country)
            info_gen = etf.loc[etf["isin"] == isin]
            df = inv.get_etf_historical_data(etf = info_gen["name"].values[0], country = country, from_date = start, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita[periodicita])
        
        elif tipologia_strumento == GLOBE.mappa_strumenti.get("fund"):

            fund = inv.funds.get_funds(country = country)
            info_gen = fund.loc[fund["isin"] == isin]
            df = inv.get_fund_historical_data(fund = info_gen["name"].values[0], country = country, from_date = start, to_date = endeu, as_json=False, order='ascending', interval = GLOBE.mappa_periodicita[periodicita])
        
        all_info = {     #dict con tutte le informazioni
                    
            "datafetch" : df, 
            "info_gen" : info_gen, 
            "tipo_strumento" : tipologia_strumento
           }   

        return all_info
Пример #13
0
def get_data(code):
    td = datetime.timedelta(days=200)
    today = datetime.datetime.today()
    return investpy.get_stock_historical_data(
        stock=code,
        country='japan',
        from_date=(today - td).strftime('%d/%m/%Y'),
        to_date=today.strftime('%d/%m/%Y'))
Пример #14
0
def get_ru_quotes(tiker):
    now = datetime.date.today().strftime('%d/%m/%Y')
    yesterday = (datetime.date.today() - timedelta(days=1)).strftime('%d/%m/%Y')

    df = investpy.get_stock_historical_data(stock=tiker,
                                            country='Russia',
                                            from_date=yesterday,
                                            to_date=now)
    return f'{df}'
Пример #15
0
def getData(stock,fromdate,todate,period):
    data = investpy.get_stock_historical_data(stock=stock,country='turkey',
                                              from_date=fromdate,
                                              to_date=todate,interval=period)
    keep_col=['Close']
    data=data[keep_col]
    data.index=pd.to_datetime(data.index)

    return data
Пример #16
0
    def download_stocks(self, source, country):
        for i, symbol in enumerate(self.holding.Symbol):
            download_success = True
            if source == "yahoo":
                data = yf.download(symbol, start=self.start, end=self.today)

            elif source == "investing":
                try:
                    data = investpy.get_stock_historical_data(
                        stock=symbol.split('.')[0],
                        country=country,
                        from_date=str(self.start.day) + '/' +
                        str(self.start.month) + '/' + str(self.start.year),
                        to_date=str(self.today.day) + '/' +
                        str(self.today.month) + '/' + str(self.today.year))
                except:
                    print(symbol.split('.')[0] + " not found!")
                    download_success = False
            if download_success:  # days with bad data
                bad_days = data[data.Close == 0].index
                if data.shape[0] >= 2:
                    print(data.shape)
                    for bad_day in bad_days:
                        avg_close_price = (
                            data.loc[bad_day - dt.timedelta(days=5):bad_day +
                                     dt.timedelta(days=5)].Close)
                        avg_close_price = np.mean(avg_close_price)
                        data.at[bad_day, 'Close'] = avg_close_price
                    mcap = data["Close"][-2] * data["Volume"][-2]
                    delta = black_litterman.market_implied_risk_aversion(
                        data['Close'])
                    if (np.max(data.Close) / np.min(data.Close) < 20):
                        self.stock_prices = pd.concat([
                            self.stock_prices,
                            pd.DataFrame({symbol: data.Close})
                        ],
                                                      axis=1)
                        self.details.append([
                            symbol, mcap, delta,
                            np.array(self.holding["Holding"])[3]
                        ])
                        print(symbol + " passed")
                    else:
                        print(symbol + " failed")

        if self.save_output:
            self.stock_prices.to_csv(
                os.path.join(self.output_path,
                             self.name + '_stock_prices.csv'))
            with open(os.path.join(self.output_path,
                                   self.name + '_details.csv'),
                      'w',
                      newline='') as csvfile:
                writer = csv.writer(csvfile)
                writer.writerows(self.details)
Пример #17
0
def carteira(ativos: list,
             start: dt,
             end: dt,
             source: str = 'iv',
             crypto: bool = False) -> pd.DataFrame:
    """Retorna um dataframe com os preços de fechmanto diários de 'ativos',
    dentro do período 'start' e 'end'. É possível utilizar as fontes
    investing.com (source = 'iv') e yahoo finance (source = 'yf'). Criptoativos
    podem ser coletados de yf (usar crypto=True).

    Args:
        ativos (list): lista dos ativos a serem baixados.
        start (datetime): data de início.
        end (datetime): data final.
        source (str, optional): fonte de coleta 'iv' ou 'yf'. Padrão: 'iv'.
        crypto (bool, optional): deve ser setado para True, por questões de
        formatação, se houver somente criptoativos em 'ativos'.

    Returns:
        pd.DataFrame: dataframe com os preços diários dos ativos contidos
        em 'ativos', entre o período 'start' e 'end'.
    """
    carteira_precos = pd.DataFrame()

    if sum(1 for d in (start, end) if isinstance(d, dt)) == 0:
        return carteira_precos

    if source == 'iv':
        for ativo in ativos:
            carteira_precos[ativo] = iv.get_stock_historical_data(
                stock=ativo,
                country='brazil',
                from_date=start.strftime('%d/%m/%Y'),
                to_date=end.strftime('%d/%m/%Y'))['Close']
    elif source == 'yf':
        if not crypto:
            for ativo in ativos:
                t = yf.Ticker(f'{ativo}.SA')
                carteira_precos[ativo] = t.history(
                    start=start.strftime('%Y-%m-%d'),
                    end=end.strftime('%Y-%m-%d'),
                    interval='1d')['Close']
        else:
            for ativo in ativos:
                t = yf.Ticker(ativo)
                carteira_precos[ativo] = t.history(
                    start=start.strftime('%Y-%m-%d'),
                    end=end.strftime('%Y-%m-%d'),
                    interval='1d')['Close']
    else:
        raise NameError('Fonte inválida.')

    carteira_precos.index = pd.to_datetime(carteira_precos.index)
    return carteira_precos
Пример #18
0
def get_stock_data(name):
    k1 = investpy.search_quotes(text=name,
                                products=['stocks'],
                                countries=['India'],
                                n_results=2)[0]

    k1 = investpy.get_stock_historical_data(stock=k1.symbol,
                                            country='India',
                                            from_date='01/01/2015',
                                            to_date='20/03/2021')
    return k1
    def lessrisk_moregains(self,datei,datef,index_,qts):
        country_='Brazil'   ##I don't know how the symbols of stocks in other country works, so i will limit my code to Brazil
        symbols = inv.get_stocks(country=country_).symbol
        my_rank = pd.DataFrame({'symb':[],'abv_bench_mean':[],'beta':[],'ratio':[]})
        bench_hist = inv.get_index_historical_data(index=index_,country=country_,from_date=datei,to_date=datef,interval="Monthly").Open
        bench_hist_change = bench_hist[bench_hist!=0].pct_change()
        bench_hist_change = bench_hist_change.dropna()
        how_many_errors=0 ###counts how many unavailable assets
        for symb in symbols:
            if symb[-1]!='3':
                continue
            ##There's some stocks names listed in inv.get_stocks that information is unavailable
            ##so i will do a test first
            works=False
            try:
                asset_hist = inv.get_stock_historical_data(stock=symb,country=country_,from_date=datei,to_date=datef,interval="Monthly").Open
                asset_hist_change = asset_hist[asset_hist!=0].pct_change()
                asset_hist_change = asset_hist_change.dropna()
                works=True
                sort = pd.DataFrame({'benchmark':bench_hist_change,'asset':asset_hist_change}).dropna().reset_index()
            except:
                if(how_many_errors<30):
                    how_many_errors+=1
                    print("Sorry, but "+symb+" is not available, it will be excluded from the rank")
                    print("How many unavailable:"+str(how_many_errors))
                if(how_many_errors==30):
                    print("More than 30 assets unavailable, it could be a connection problem")
                    how_many_errors+=1
                pass
            ##sort = data sorted by common dates and delete dates not in common
            if (works)and(len(sort.benchmark)!=0)and(len(sort.asset)!=0):
                beta = line(sort.benchmark,sort.asset)[0]
                if(beta<=0):
                    continue
                abv_bench =  sort.asset-sort.benchmark
                abv_bench_mean = abv_bench.mean()
                ratio = abv_bench_mean/beta
                
                add={'symb':symb,'abv_bench_mean':(str(round(abv_bench_mean*100,2))+"%"),'beta':round(beta,4),'ratio':ratio}
                my_rank = my_rank.append(add,ignore_index=True)

        my_rank = my_rank.sort_values(by='ratio',ascending=False).head(qts)
        my_rank = my_rank.drop('ratio',1)
        fig,ax = plt.subplots(figsize=[10,5])
        ax.set_title("Top "+str(qts)+" stocks with highest gains above "+index_+" index and lowest risks in "+country_)
        period_string = ("Period: "+datei +" to "+datef)
        ax.set_xlabel("Average monthly relative rentability(AMRR)="+" Average gains above Benchmark("+index_+" Index)\n"+period_string)
        plt.xticks([])
        plt.yticks([])
        ax.table(bbox=[0,0.1,1,0.8],rowLabels=range(1,qts+1),colLabels=['Symbol','AMRR','Beta(risk)'],cellText=my_rank.values,loc='center',rowLoc='center',cellLoc='center')

        fig.savefig('Rank.png')
        plt.show()
Пример #20
0
def get_comp_data(symbol):
    end_date = datetime.now()
    start_date = end_date - timedelta(days=2000)

    df = inp.get_stock_historical_data(
        stock=symbol,
        country='turkey',
        from_date=start_date.strftime('%d/%m/%Y'),
        to_date=end_date.strftime('%d/%m/%Y'),
        as_json=False,
        order='ascending')
    return df
Пример #21
0
def get_frame_data(symbol, start_date, end_date):
    """
    This function return data frame consisting of stock data
    in range of given dates for given stock symbol
    """
    try:
        data = investpy.get_stock_historical_data(stock=symbol, country="india", from_date=start_date,
                                                  to_date=end_date)
        return data

    except IndexError:
        return False
Пример #22
0
def get_data_by_isin(isin: str, dates: Tuple[datetime.date],
                     is_etf: bool) -> Tuple[Optional[np.ndarray], str]:
    """Retrieves stock/ETF prices in EUR by ISIN for the given dates. Cached to make sure this is only queried once for
    a given currency & date-range."""
    from_date = dates[0].strftime("%d/%m/%Y")
    to_date = (dates[-1] + datetime.timedelta(days=7)).strftime("%d/%m/%Y")

    # Retrieves stock/etf information based on the ISIN
    try:
        if is_etf:
            data = investpy.search_etfs(by="isin", value=isin)
        else:
            data = investpy.search_stocks(by="isin", value=isin)
    except RuntimeError:
        print(
            f"[DGPC] Warning, could not retrieve {'ETF' if is_etf else 'stock'} data for ISIN {isin}."
        )
        return None, ""

    # When a stock/ETF is listed in multiple countries, take one of the preferred countries if found
    for country in PREFERRED_COUNTRIES:
        local_data = data[data["country"] == country]
        if local_data.shape[0] > 0:
            break
    else:
        # Taking the first country from the results if none of the preferred countries is found
        country = data["country"][0]
        local_data = data

    # Retrieves the actual historical prices for the stock/etf
    currency = list(local_data["currency"])[0]
    symbol = list(local_data["symbol"])[0]
    if is_etf:
        name = list(local_data["name"])[0]
        history = investpy.get_etf_historical_data(name,
                                                   country=country,
                                                   from_date=from_date,
                                                   to_date=to_date)
    else:
        history = investpy.get_stock_historical_data(symbol,
                                                     country=country,
                                                     from_date=from_date,
                                                     to_date=to_date)
    history = history.reset_index()
    values = densify_history(history, dates)

    # Convert the results to euro
    if currency != "EUR":
        currency_modifier = to_euro_modifier(currency, tuple(dates))
        values *= currency_modifier

    return values, symbol
Пример #23
0
def ticker_data_reader(
    name: str, *, days_from_now: int = None, from_date: str = None, to_date: str = None
) -> DataFrame:  # pragma: no cover
    """Đọc dữ liệu ticker từ investing.com"""
    name = name.upper()
    from_date, to_date = _get_date_string(days_from_now, from_date, to_date)

    df = investpy.get_stock_historical_data(
        stock=name, country="vietnam", from_date=from_date, to_date=to_date
    )
    df["name"] = name

    return df
Пример #24
0
def get_previous_price(stock, date):
    """
    Get the closing date price of the given date provided
    Args:
        stock (str): stock name in investpy
        date (str): date with format 'dd/mm/yyyy'

    Returns:
        Last price of the given date
    """
    day, month, year = date.split('/')
    next_day = str(int(day)+1)+'/'+month+'/'+year
    price_list = investpy.get_stock_historical_data(stock=stock, country='Malaysia', from_date=date, to_date=next_day)['Close'].to_list()
    return price_list[0]
Пример #25
0
def get_stock_info(ticker):
    info = investpy.get_stock_company_profile(stock=ticker, country='iceland')
    description = info["desc"]
    url = info["url"]
    price_now = get_stock_price(ticker)
    now = datetime.datetime.now()
    price_year_ago = investpy.get_stock_historical_data(
        stock=ticker,
        country='iceland',
        from_date=(now - datetime.timedelta(days=365)).strftime('%d/%m/%Y'),
        to_date=(
            now -
            datetime.timedelta(days=350)).strftime('%d/%m/%Y'))['Close'][-1]
    return price_now, price_year_ago, description, url
Пример #26
0
def get_reward(df, date, actionstate):
    preprocess_obj = preprocess()
    starting_date_obj = datetime.datetime.strptime(
        date, "%Y-%m-%d")
    num_days_next_three_months = preprocess_obj.get_next_three_months_days(
        date)
    num_days_next_two_months = preprocess_obj.get_next_two_months_days(date)
    next_three_month_date = starting_date_obj + \
        datetime.timedelta(num_days_next_three_months)
    next_two_month_date = starting_date_obj + \
        datetime.timedelta(num_days_next_two_months)
    df_opening_calc = investpy.get_stock_historical_data(
        stock='SBI', country='India', from_date=starting_date_obj.strftime("%d/%m/%Y"), to_date=next_two_month_date.strftime("%d/%m/%Y"))
    df_closing_calc = investpy.get_stock_historical_data(
        stock='SBI', country='India', from_date=starting_date_obj.strftime("%d/%m/%Y"), to_date=next_three_month_date.strftime("%d/%m/%Y"))

    #print('opening', df_opening_calc)
    #print('closing', df_closing_calc)
    # to calculate date till it is found in df
    next_three_month_date_temp = next_three_month_date
    while next_three_month_date_temp not in df.index:
        next_three_month_date_temp = next_three_month_date_temp - \
            datetime.timedelta(1)

    # to calculate date till it is found in df
    next_two_month_date_temp = next_two_month_date
    while next_two_month_date_temp not in df.index:
        next_two_month_date_temp = next_two_month_date_temp - \
            datetime.timedelta(1)

    if actionstate == 'Long':
        return df_closing_calc.loc[next_three_month_date_temp]['Close'] - df_opening_calc.loc[next_two_month_date_temp]['Close']
    if actionstate == 'Short':
        return -(df_closing_calc.loc[next_three_month_date_temp]['Close'] - df_opening_calc.loc[next_two_month_date_temp]['Close'])
    if actionstate == 'Hold':
        return 0
Пример #27
0
def get_data(symbol, start_date, end_date):
    """
    This function returns data frame consisting of stock data between given dates,
    data for last trading day in given date range and data for second last trading day.
    so those data can use to apply various comparision filters for day data and long term data
    """
    try:
        data = investpy.get_stock_historical_data(stock=symbol, country="india", from_date=start_date,
                                                  to_date=end_date)
        day_data = data.iloc[-1]
        prev_day_data = data.iloc[-2]
        return data, day_data, prev_day_data

    except IndexError:
        return (None, None, None)
Пример #28
0
def extraer(cond, stock_valor, pais, pi="", pf=""):
    """
    Se extraen los datos del precio final diaro del valor 
    """
    if cond == 1:
        # Se extraen los datos del precio final diario del valor en el rango de días dado
        df = investpy.get_stock_historical_data(stock_valor, pais, pi, pf)
    else:
        # Se extraen los datos del precio final diario del valor en el último mes del valor
        df = investpy.get_stock_recent_data(stock_valor,
                                            pais,
                                            as_json=False,
                                            order='ascending')

    return df
def download(symbol, save_dir):
    # data = yf.download(symbol, start_date, end_date)
    # return data
    df = investpy.get_stock_historical_data(
        stock=symbol,
        country="United States",
        from_date="18/12/2018",
        to_date="20/02/2021",
    )
    df.drop("Currency", axis=1, inplace=True)
    # for col in df.columns:
    #    df.loc[:, col] = np.log(df.loc[:, col]) - np.log(df.loc[:, col].shift(1))
    # df = df.iloc[1:, :]
    # df = df.resample('H').pad()
    df.to_csv(f"{save_dir}/{symbol}.csv", index=True, header=True)
def get_historical_cotation(stock, country, from_date, to_date):
    df = investpy.get_stock_historical_data(stock,
                                            country,
                                            from_date,
                                            to_date
                                           ).reset_index()
    df = df[['Date', 'Close']]

    df = df.rename(columns={"Date":"data",
              "Close": "valor"})

    df['ticker'] = stock

    df = df[[ 'data', 'ticker', 'valor']]
    
    return df