def get_stock_data(contract, s_year, s_month, s_day, e_year, e_month, e_day): """ Args: contract (str): the name of the stock/etf s_year (int): start year for data s_month (int): start month s_day (int): start day e_year (int): end year e_month (int): end month e_day (int): end day Returns: Pandas Dataframe: Daily OHLCV bars """ start = datetime.datetime(s_year, s_month, s_day) end = datetime.datetime(e_year, e_month, e_day) retry_cnt, max_num_retry = 0, 3 while (retry_cnt < max_num_retry): try: bars = pd.DataReader(contract, "google", start, end) return bars except: retry_cnt += 1 time.sleep(np.random.randint(1, 10)) print("Google Finance is not reachable") raise Exception('Google Finance is not reachable')
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% [markdown] # # Plotly Candlestick Chart in Python # %% import pandas as web from datetime import datetime import numpy as np import pandas as pd import plotly.plotly as py # %% df = web.DataReader("gs", 'yahoo', datetime(2008, 1, 1), datetime(2008, 12, 28)) # %% df.head() # %% [markdown] # ### Initial candlestick chart # %% INCREASING_COLOR = '#17BECF' DECREASING_COLOR = '#7F7F7F' # %% data = [ dict( type = 'candlestick',
from keras.layers import Dense, LSTM import math import matplotlib.pyplot as plt plt.style.use('default') import pandas as pd pd.options.mode.chained_assignment = None import pandas_datareader as pd import numpy as np # In[5]: # Get the financial data of the corporation fin_data = pd.DataReader('IBM', data_source='yahoo', start='2010-01-01', end='2020-01-01') # Get only the 'Close' column close_data = fin_data.filter(['Close']) npy_close_data = close_data.values train_length = math.floor(.75 * len(npy_close_data)) # Scale the data using StandardScaler before using the data for our model sc = StandardScaler() sc = sc.fit(npy_close_data) sc_data = sc.transform(npy_close_data) # In[6]: # Independent training features
def __init__(self, ticker, start, end, source='bitfinex', interval='1D', workingdays=None): if source == 'quandl': if type(start) == dt.datetime: self.start = str(start).split(' ')[0] elif type(start) == str: self.start = start else: self.start = str(dt.datetime(*start).date()) if type(end) == dt.datetime: self.end = str(end).split(' ')[0] elif type(end) == str: self.end = end else: self.end = str(dt.datetime(*end).date()) self.ticker = ticker self.source = source self.order = None stock_data = 'WIKI/' + self.ticker stock_data = pds.DataReader(stock_data, self.source, self.start, self.end) self.C = stock_data['Close'] self.H = stock_data['High'] self.L = stock_data['Low'] self.V = stock_data['Volume'] self.O = stock_data['Open'] self.dates = map(lambda t: t.to_datetime(), stock_data.index) if workingdays is not None: workingday_str = map(lambda x: str(x.date()), workingdays) filtered_close = [] filtered_high = [] filtered_dates = [] filtered_volume = [] for dateindex in workingday_str: if dateindex in self.C.index: filtered_close.append(self.C[dateindex]) filtered_high.append(self.H[dateindex]) filtered_volume.append(self.V[dateindex]) filtered_dates.append( workingdays[workingday_str.index(dateindex)]) self.dates = filtered_dates self.C = pds.Series(filtered_close, index=self.dates) self.H = pds.Series(filtered_high, index=self.dates) self.V = pds.Series(filtered_volume, index=self.dates) elif source == 'bitfinex': self.interval = interval # Converting datetime to timestamp self.epoch = dt.datetime(1970, 1, 1) self.epochTS = self.epoch.timetuple() self.epochTS = time.mktime(self.epochTS) self.startTS = start self.startTS = self.startTS.timetuple() # Correcting for my timezone self.startTS = int(time.mktime(self.startTS) - self.epochTS) * 1000 self.endTS = end self.endTS = self.endTS.timetuple() self.endTS = int(time.mktime(self.endTS) - self.epochTS) * 1000 # Structuring request's url self.ticker = ticker self.url = "https://api.bitfinex.com/v2/candles/trade:" + self.interval + ":t" + self.ticker + "/hist" response = requests.request("GET", self.url, params={ 'limit': 1000, 'start': int(self.startTS), 'end': int(self.endTS) }) # handling data self.rawData = response.json() self.cryptoData = pds.DataFrame(self.rawData) self.cryptoData.columns = [ 'dates', 'Open', 'High', 'Low', 'Close', 'Volume' ] self.cryptoData['dates'] = self.cryptoData['dates'].apply( lambda x: dt.datetime.fromtimestamp(x / 1000).date()) self.C = self.cryptoData['Close'] self.H = self.cryptoData['High'] self.L = self.cryptoData['Low'] self.V = self.cryptoData['Volume'] self.O = self.cryptoData['Open'] self.dates = self.cryptoData['dates']
sns.despine(); #Bar plot of median values sns.factorplot("agency_abbr", "loan_amount_000s", data=ver, palette="PuBu_d", estimator=np.median); #Bar plot example sns.factorplot("loan_purpose_name", data=ver, hue="action_taken_name"); #***********************************time seriese******************************************************** #Analyzing Data with Pandas - Time Series import matplotlib.pyplot as plt import datetime import pandas as pd from pandas_datareader import data, wb# You need to install if you do not have this package #Read the data yhoo = pd.DataReader("yhoo", "yahoo", datetime.datetime(2007, 1, 1),datetime.datetime(2012,1,1)) #Plot stock price and volume top = plt.subplot2grid((4,4), (0, 0), rowspan=3, colspan=4) top.plot(yhoo.index, yhoo["Close"]) plt.title('Yahoo Price from 2007 - 2012') bottom = plt.subplot2grid((4,4), (3,0), rowspan=1, colspan=4) bottom.bar(yhoo.index, yhoo['Volume']) plt.title('Yahoo Trading Volume') plt.gcf().set_size_inches(15,8) #Calculate moving averages