def sectors(l_args): parser = argparse.ArgumentParser( prog='sectors', description= '''Real-time and historical sector performances calculated from S&P500 incumbents. Pops plot in terminal. [Source: Alpha Vantage]''' ) try: (ns_parser, l_unknown_args) = parser.parse_known_args(l_args) except SystemExit: print("") return if l_unknown_args: print(f"The following args couldn't be interpreted: {l_unknown_args}") sp = SectorPerformances(key=cfg.API_KEY_ALPHAVANTAGE, output_format='pandas') df_sectors, d_meta_data = sp.get_sector() df_sectors['Rank A: Real-Time Performance'].plot(kind='bar') plt.title('Real Time Performance (%) per Sector') plt.tight_layout() plt.grid() plt.show() print("")
def sectorPerformance(self, timerange): filename = timerange+ "-sector-" + "-" + datetime.now().strftime("%Y-%m-%d-%H-%M-%S") +stockChartBaseName filePath = imageFolder +'/' + filename keyMap = { 'realtime': 'Rank A: Real-Time Performance', '1d': 'Rank B: Day Performance', '5d': 'Rank C: Day Performance', '1m': 'Rank D: Month Performance', '3m': 'Rank E: Month Performance', 'ytd': 'Rank F: Year-to-Date (YTD) Performance', '1y': 'Rank G: Year Performance', '3y': 'Rank H: Year Performance', '5y': 'Rank I: Year Performance', '10y': 'Rank J: Year Performance' } if timerange not in keyMap: throw('unknown timerage '+timerange) key = keyMap[timerange] title = key if timerange != 'realtime' and timerange != 'ytd': title = key[0:7] + ' '+ re.findall(r'\d+', timerange)[0] + ' ' + key[8:] sp = SectorPerformances(key='O16MFPVKSJGHLIL6', output_format='pandas') data, meta_data = sp.get_sector() fig = mplot.figure() data[key].plot(kind='bar') mplot.title(title) mplot.tight_layout() mplot.grid() fig.savefig(Path(filePath)) return(self.showResult(stockTemplate, imageFolder, filename))
def __init__(self, api_key): self._api_key = get_alpha_vantage_credentials(api_key) self._session = requests.Session() self._timeseries = TimeSeries(key=self._api_key) self._cryptocurrencies = CryptoCurrencies(key=self._api_key) self._foreignexchange = ForeignExchange(key=self._api_key) self._sectorperformance = SectorPerformances(key=self._api_key) self._techindicators = TechIndicators(key=self._api_key)
def __init__(self, symbol, api_key='KHMFAMB5CA0XGKXO'): self.api_key = api_key self.ticker = symbol self.ts = TimeSeries(api_key) self.ti = TechIndicators(api_key) self.sp = SectorPerformances(api_key) self.counter = 0 self.MAX_API_CALL = 500
def get_sector_data(): sp=SectorPerformances (key=key, output_format='pandas') data,_ = sp.get_sector() df = pd.DataFrame() df['1M Performane']=data['Rank D: Month Performance'] df['YTD Performance']=data['Rank F: Year-to-Date (YTD) Performance'] df['1Y Performance']=data['Rank G: Year Performance'] df['3Y Performance']=(data['Rank H: Year Performance']+1)**.33333333-1 df['10Y Performance']=(data['Rank J: Year Performance']+1)**.1-1 return df
def sector_performance_graph(key): from alpha_vantage.sectorperformance import SectorPerformances import matplotlib.pyplot as plt sp = SectorPerformances(key=key, output_format="pandas") data, meta_data = sp.get_sector() data["Rank A: Real-Time Performance"].plot(kind="bar") plt.title("Real Time Performance (%) per Sector") plt.tight_layout() plt.grid() plt.show()
def sectors_performance(): try: sp = SectorPerformances(key='YOUR_API_KEY', output_format='pandas') data, meta_data = sp.get_sector() data['Rank A: Real-Time Performance'].plot(kind='bar') plt.title('Real Time Performance (%) per Sector') plt.tight_layout() plt.grid() plt.show() except Exception as e: print(str(e)) messagebox.showwarning("ERROR",str(e))
def sector_performance(): if request.method == 'POST': ticker = request.form['ticker'] sp = SectorPerformances(key='SS66OZ9EH3PLN7HS', output_format='pandas') data, meta_data=sp.get_sector() data['Rank A: Real-Time Performance'].plot(kind='bar') plt.title('Real Time Performance (%) per Sector') plt.tight_layout() plt.grid() plt.savefig("static\\images\\sector_performance\\" + ticker) filename = 'images/sector_performance/'+ ticker + '.png' print(filename) return render_template('sector_performance.html', sector_performance_image = filename)
def performance_sectors_sp500(self, timespan: str = 'realtime') -> BytesIO: sp = SectorPerformances(key=conf.API['alphavantage_api_key'], output_format='pandas') df_sectors, _ = sp.get_sector() timespan_desc = PERFORMANCE_SECTORS_SP500_TIMESPAN[timespan] df_data = df_sectors[timespan_desc] title = f'S&P500 Sectors: {timespan_desc[8:]}' ylabel = '%' with PlotContext() as pc: buf = pc.create_bar_chart(df_data, title, ylabel) return buf
def get_sector_data() -> pd.DataFrame: """Get real-time performance sector data Returns ---------- df_sectors : pd.Dataframe Real-time performance data """ sector_perf = SectorPerformances(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas") # pylint: disable=unbalanced-tuple-unpacking df_sectors, _ = sector_perf.get_sector() return df_sectors
def sectorPerformance(API_key='Z6P4MY41TAIKFAXW'): print("########PROCESSING#########") from alpha_vantage.sectorperformance import SectorPerformances import matplotlib.pyplot as plt import mplfinance as mpf sp=SectorPerformances(key=API_key, output_format='pandas') data=sp.get_sector()[0] data['Rank A: Real-Time Performance'].plot(kind='bar') plt.title('Real Time Performance (%) per sector') plt.tight_layout() plt.grid() plt.show() return data
def get_sector_performances(key): sp = SectorPerformances(key) sector_data, meta = sp.get_sector() ranks = [] print("") for i in meta: print(i, meta[i], "\n") print("") for rank in sector_data: ranks.append(rank) for i in ranks: print("-------------------------------------\n", i, "\n-------------------------------------\n") for j in sector_data[i]: print("{}: {}".format(j, round(sector_data[i][j], 3))) print("")
def sectors(l_args): parser = argparse.ArgumentParser( prog="sectors", description= """Real-time and historical sector performances calculated from S&P500 incumbents. Pops plot in terminal. [Source: Alpha Vantage]""", ) parse_known_args_and_warn(parser, l_args) sector_perf = SectorPerformances(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas") # pylint: disable=unbalanced-tuple-unpacking df_sectors, _ = sector_perf.get_sector() # pylint: disable=invalid-sequence-index df_sectors["Rank A: Real-Time Performance"].plot(kind="bar") plt.title("Real Time Performance (%) per Sector") plt.tight_layout() plt.grid() plt.show() print("")
def get_sector_performance(): plt.close() sp = SectorPerformances(key='EZ3UZE4SWE1JI2A9', output_format='pandas') data, meta_data = sp.get_sector() fig_size = plt.rcParams["figure.figsize"] fig_size[0] = 12 fig_size[1] = 5 plt.rcParams["figure.figsize"] = fig_size # data['Rank A: Real-Time Performance'].plot(kind='bar') # plt.title('Real Time Performance (%) per Sector') # fig, ax = plt.subplots() # ax.plot(data.index, data['Rank A: Real-Time Performance'], kind='bar') data['close'].plot() plt.tight_layout() plt.grid() # ax.set_title('Real Time Performance (%) per Sector') # ax.set_xticklabels(data.index, rotation=90, ha='left', fontsize=10) # dictionary_rep = mpld3.fig_to_dict(fig) # plt.savefig("/Users/rjmac/Desktop/SahanaMD_Project/FrontEnd/src/assets/sector_performance.png", dpi=1000) # with open("/Users/rjmac/Desktop/SahanaMD_Project/Angular_Part/src/assets/sector_performance.png", "rb") as imageFile: # str = base64.b64encode(imageFile.read()) # print (str) plt.close()
def sectors_view(other_args: List[str]): """Opens a bar chart with sector performance Parameters ---------- other_args : List[str] argparse other args """ parser = argparse.ArgumentParser( add_help=False, prog="sectors", description=""" Real-time and historical sector performances calculated from S&P500 incumbents. Pops plot in terminal. [Source: Alpha Vantage] """, ) ns_parser = parse_known_args_and_warn(parser, other_args) if not ns_parser: return sector_perf = SectorPerformances(key=cfg.API_KEY_ALPHAVANTAGE, output_format="pandas") # pylint: disable=unbalanced-tuple-unpacking df_sectors, _ = sector_perf.get_sector() # pylint: disable=invalid-sequence-index df_sectors["Rank A: Real-Time Performance"].plot(kind="bar") plt.title("Real Time Performance (%) per Sector") plt.tight_layout() plt.grid() if gtff.USE_ION: plt.ion() plt.show() print("")
def setup_av(path='../config/myinfo.json'): global g_ts, g_ti, g_sp # Read API infos from config try: with open(path, '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') except Exception as e: print('Unable to setup Alpha Vantage') exit(-1)
def connect_datafeed(self, config=None): d = None if isinstance(config, str) and os.path.exists(config): with open (config, 'r') as f: d = json.load(f) # use config stored in the instance else: d = self.config self.datafeed_carrier = d['name'] self.datafeed_entry = d['entry'] self.datafeed_api_token = d['key'] if d['secret']: self.datafeed_api_secret = d['secret'] self.df_ts = TimeSeries(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas') self.df_ti = TechIndicators(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas') self.df_sp = SectorPerformances(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas')
import pandas as pd import matplotlib.pyplot as plt key = 'KXRFJKF10FZ75COC' from alpha_vantage.sectorperformance import SectorPerformances from alpha_vantage.techindicators import TechIndicators from alpha_vantage.timeseries import TimeSeries sp = SectorPerformances(key, output_format='pandas') data, meta_data = sp.get_sector() data['Rank A: Real-Time Performance'].plot(kind='bar') plt.title("Performance by Sector") plt.tight_layout() plt.grid(True) ta = TechIndicators(key, output_format='pandas') tsla, meta = ta.get_sma('TSLA', interval='daily', series_type='close') print(tsla.head) print(plt.plot(tsla))
def SectorPerformances(request, format=None): if request.method == 'GET': from alpha_vantage.sectorperformance import SectorPerformances sp = SectorPerformances(key=key) data, meta_data = sp.get_sector() return Response(data)
MAX_API_RETRIES = 3 slow_interval = 'daily' fast_interval = '15min' ema_fast_period = 12 ema_slow_period = 26 series_type = 'close' po_client = pushover.Client(PUSHOVER_USERKEY, api_token=PUSHOVER_TOKEN) r = Robinhood() logged_in = r.login(username=ROBINHOOD_USERNAME, password=ROBINHOOD_PASSWORD) ts = TimeSeries(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas') ti = TechIndicators(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas') sp = SectorPerformances(key=ALPHAVANTAGE_API_TOKEN, output_format='pandas') data = {} msg_template = { "MACD_OWN_BUY": "", #Owned stocks to HOLD: {} "MACD_OWN_SELL": "Owned stocks to SELL: {}", "MACD_WATCH_BUY": "Watched stocks to BUY: {}", "MACD_WATCH_SELL": "", #Watched stocks to stay away from: {} "PRICE_CROSS_EMA_OWN_EXIT_LONG": "Owned stocks exit LONG - consider SELL: {}", "PRICE_CROSS_EMA_OWN_EXIT_SHORT": "", #Owned stocks exit SHORT - to HOLD: {}
# ------------------------------ ti = TechIndicators(key='API_KEY', output_format='pandas') interval = '60min' data, metadata = ti.get_bbands(symbol=ticker, interval=interval, time_period=60) data.plot() plt.title('BBands indicator for %s stock, at %s interval' % (ticker, interval)) plt.show() # ------------------------------ # Part Three: Sector Performance # ------------------------------ sp = SectorPerformances(key='API_KEY', output_format='pandas') data, metadata = sp.get_sector() data['Rank A: Real-Time Performance'].plot(kind='bar') plt.title('Real Time Performance (%) per Sector') plt.tight_layout() plt.grid() plt.show() # --------------------------- # Part Four: Cryptocurrencies # --------------------------- ticker = 'BTC' cc = CryptoCurrencies(key='YOUR_API_KEY', output_format='pandas') data, metadata = cc.get_digital_currency_intraday(symbol=ticker, market='CNY') data['1b. price (USD)'].plot() plt.tight_layout()
from alpha_vantage.sectorperformance import SectorPerformances import matplotlib.pyplot as plt sp = SectorPerformances(key='85IAAJZVJLIKZZ26', output_format='pandas') data, meta_data = sp.get_sector() data['Rank A: Real-Time Performance'].plot(kind='bar') plt.title('Crecimiento por sectores en tiempo Real') plt.tight_layout() plt.show()
class AlphaVantageWrapper: ts = TimeSeries(key='QL2Z176B6Q3JYM6A', output_format='pandas') sp = SectorPerformances(key='QL2Z176B6Q3JYM6A', output_format='pandas') def get_intraday(self, company="AAPL", timegap="60min"): """Calls AlphaVantages API and gets the intraday figures for the given company. Args: company (string): Company name that we will look for timegap (string): The time interval we look at during the day Returns: Panda Dataframe: Dataframe of stock information for the given request """ data, meta_data = self.ts.get_intraday(symbol=company, interval=timegap) return data def get_days_information(self, company="AAPL"): """Calls AlphaVantages API and gets the days figures for the given company. Args: company (string): Company name that we will look for Returns: Panda Dataframe: Dataframe of stock information for the given request """ data, meta_data = self.ts.get_daily(symbol=str(company)) return data def get_weekly_information(self, company="AAPL"): """Calls AlphaVantages API and gets the weeks figures for the given company. Args: company (string): Company name that we will look for Returns: Panda Dataframe: Dataframe of stock information for the given request """ data, meta_data = self.ts.get_weekly(symbol=str(company)) return data def get_monthly_information(self, company="AAPL"): """Calls AlphaVantages API and gets the months figures for the given company. Args: company (string): Company name that we will look for Returns: Panda Dataframe: Dataframe of stock information for the given request """ data, meta_data = self.ts.get_monthly(symbol=str(company)) return data def get_sector_intraday(self): sp = SectorPerformances(key='QL2Z176B6Q3JYM6A', output_format='pandas') data, meta_data = self.sp.get_sector() realtime = data['Rank A: Real-Time Performance'] return realtime.get('Information Technology') def get_sector_daily(self): data, meta_data = self.sp.get_sector() day = data['Rank B: Day Performance'] return day.get('Information Technology') def get_sector_weekly(self): data, meta_data = self.sp.get_sector() week = data['Rank C: Day Performance'] return week.get('Information Technology') def get_sector_monthly(self): data, meta_data = self.sp.get_sector() month = data['Rank D: Month Performance'] return month.get('Information Technology')
class DashboardApp(QDialog): TIME_SERIES = TimeSeries(key='YJWXREJ7AXYQX6J7', output_format='pandas') SECTOR_PERFORMANCE = SectorPerformances(key='YJWXREJ7AXYQX6J7', output_format='pandas') TECH_INDICATORS = TechIndicators(key='YJWXREJ7AXYQX6J7', output_format='pandas') def __init__(self): super().__init__() self.dashboard = Dashboard() self.dashboard.setupUi(self) # self.setStyleSheet('background:red') self.dashboard.CompanyLogo.setIcon(QIcon('hflogo.png')) self.dashboard.CompanyLogo.setIconSize(QSize(361, 291)) self.show() self.ticker = '' self.set_new_ticker() self.ticker = str( QInputDialog.getText(self, 'Hesiod Financial, LLC', "Enter a New Ticker", QLineEdit.Normal, "")[0]) #self.dashboard.MacD.clicked.connect(self.macd) #self.dashboard.RSI.clicked.connect(self.rsi) #self.dashboard.MovAvg.clicked.connect(self.moving_average) #self.dashboard.BBands.clicked.connect(self.bollinger_bands) self.dashboard.NewTicker.clicked.connect(self.set_new_ticker) def macd(self): volume, meta = DashboardApp.TECH_INDICATORS.get_macd(self.ticker) self.dashboard.Graphic = volume self.dashboard.Graphic.plot() self.dashboard.Graphic.show() self.dashboard.GraphLabel.setText(f'MacD: {self.ticker}') def rsi(self): strength, meta = DashboardApp.TECH_INDICATORS.get_rsi(self.ticker) self.dashboard.Graphic = strength self.dashboard.Graphic.plot() self.dashboard.Graphic.show() self.dashboard.GraphLabel.setText( f'Relative Strength Index: {self.ticker}') def moving_average(self): ma, meta = DashboardApp.TECH_INDICATORS.get_wma(self.ticker) self.dashboard.Graphic = ma self.dashboard.Graphic.plot() self.dashboard.Graphic.show() self.dashboard.GraphLabel.setText( f'Weighted Moving Average: {self.ticker}') def bollinger_bands(self): bbands, meta = DashboardApp.TECH_INDICATORS.get_bbands(self.ticker) self.dashboard.Graphic = bbands self.dashboard.Graphic.plot() self.dashboard.Graphic.show() self.dashboard.GraphLabel.setText(f'Bollinger Bands: {self.ticker}') def set_new_ticker(self): # make it so the page refreshes new_ticker = self.dashboard.TickerSearch.text() self.ticker = new_ticker self.dashboard.Stock.setText(f'Current Stock: {new_ticker}') self.dashboard.Stock.repaint()
### 'education is something you don't want to finish' # [email protected] # feedback appreciated # exploring AlphaVantage sector performance # perform usual imports import pandas as pd import numpy as np import plotly import plotly.graph_objects as go from plotly.subplots import make_subplots from alpha_vantage.timeseries import TimeSeries from alpha_vantage.sectorperformance import SectorPerformances apikey = '' # input your alpha vantage api key sp = SectorPerformances(key=apikey) # get sector performance data = sp.get_sector() # this is a tuple l = list(data) # let's convert it to list df = pd.DataFrame.from_dict(l[0]).reset_index() # now convert it to DF dfTr = df.transpose().reset_index() # transpose for our use case dfTr.columns = dfTr.iloc[0] # update column values dfTr = dfTr.iloc[1:] # drop unnecessary row dfTr.head(3) # inspect data dfTr.tail(3) # keep inspecting ytd = dfTr[ dfTr['index'] == 'Rank F: Year-to-Date (YTD) Performance'] # year to date performance of sectors ytd = ytd.drop( 'Real Estate', axis=1
from alpha_vantage.sectorperformance import SectorPerformances import matplotlib.pyplot as plt from Environment_Settings import settings sp = SectorPerformances(key=settings.API_KEY, output_format='pandas') data, meta_data = sp.get_sector() data['Rank A: Real-Time Performance'].plot(kind='bar') plt.title('Real Time Performance (%) per Sector') plt.tight_layout() plt.grid() plt.show()
import pandas as pd from finta import TA from alpha_vantage.timeseries import TimeSeries from alpha_vantage.sectorperformance import SectorPerformances from alpha_vantage.techindicators import TechIndicators from fundamental_data import FundamentalData from config import key from sklearn import preprocessing from tqdm import tqdm ts = TimeSeries(key, output_format='pandas') sp = SectorPerformances(key, output_format='pandas') ti = TechIndicators(key, output_format='pandas') fd = FundamentalData(key, output_format='pandas') indicator_periods = [4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18] def get_daily_data(ticker, compact=True): # 1 call print("\nLoading data for ticker: {}".format(ticker)) outputsize = 'compact' num_data_points = 100 if not compact: outputsize = 'full' num_data_points = 1000 + indicator_periods[-1] * 2 stock, meta_data = ts.get_daily(ticker, outputsize=outputsize) stock.columns = ['open', 'high', 'low', 'close', 'volume'] stock = stock[:num_data_points].iloc[::-1] indicators = [] for period in indicator_periods: indicators.append( TA.TEMA(ohlc=stock, period=period).to_frame(name='TEMA'))
def get_sector_intraday(self): sp = SectorPerformances(key='QL2Z176B6Q3JYM6A', output_format='pandas') data, meta_data = self.sp.get_sector() realtime = data['Rank A: Real-Time Performance'] return realtime.get('Information Technology')
from alpha_vantage.sectorperformance import SectorPerformances sp = SectorPerformances(key='GSD3E3P11LSBZG5O', output_format='pandas') data, meta_data = sp.get_sector() print(data.head())
from alpha_vantage.sectorperformance import SectorPerformances from datetime import datetime from pytz import timezone from elasticsearch import Elasticsearch import time # reads sector performance from alpha vantage and writes it into elasticsearch # every 10 seconds es=Elasticsearch([{'host':'localhost','port':9200}]) while True: # get sector performance from alpha vantage sp = SectorPerformances(key='JLD6KKU8CQTZD02V',output_format='json') data, meta_data = sp.get_sector() performance = data['Rank A: Real-Time Performance'] #change timezone and bring into right format for elasticsearch date_us = timezone('US/Eastern').localize(datetime.strptime(meta_data['Last Refreshed'][:19], "%Y-%m-%d %H:%M:%S")) date_utc = date_us.astimezone(timezone('UTC')) date_es = date_utc.strftime("%Y-%m-%d"'T'"%H:%M:%S") print(performance) for sector in performance: doc = {} doc['sector'] = sector doc['change'] = performance[sector] doc['date'] = date_es res = es.index(index="sector", body=doc)