def main(): a = 1 start = datetime.datetime(2016, 1, 1) end = datetime.date.today() aplOption = web.get_data_google("AAOI", start, end) apple = web.get_data_google("AAPL", start, end) fig = plt.figure(1) plt.subplot(211) plt.plot(aplOption.index.values, aplOption.Close) plt.title('Close Price for AAOI') plt.subplot(212) hist1 = plt.bar(aplOption.index.values, aplOption.Volume) plt.show() print(apple.head())
def test_tsla_download(): style.use('ggplot') start = dt.datetime(2000, 1, 1) end = dt.datetime(2012, 12, 31) df = pdr.get_data_google('TSLA') df.to_csv('../tsla.csv') print(df.head(6))
def plot_ohlc(stock, mov_avg): '''plot ohlc graph Args: stock (string): stock name in string format, e.g, 'NVDA', 'GOOGL' mov_avg (int): the range used to calculate moving average start (string): stop (string): Return: matplotlib graph Notes: ''' stock_data = pdr.get_data_google(stock) stock_data[str(mov_avg)] = np.round( stock_data["Close"].rolling(window=mov_avg, center=False).mean(), 2) # stock_data['Date'] = stock_data.index time_stamp = mdates.date2num(stock_data.index.to_pydatetime()) # drop the date index from the dataframe stock_data.reset_index(inplace=True) stock_data['Date'] = time_stamp fig = plt.figure() ax1 = plt.subplot2grid((1, 1), (0, 0)) # x = 0 # y = len(stock_data) # while x < y: # append_me = #ax1.xaxis.label.set_color('c') #ax1.yaxis.label.set_color('r') #ax1.set_yticks([0, 25, 50, 75]) candlestick_ohlc(ax1, stock_data.values, width=0.4, colorup='#77d879', colordown='#db3f3f') if mov_avg != None: ax1.plot(stock_data['Date'], stock_data[str(mov_avg)]) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) ax1.xaxis.set_major_formatter(mdates.DateFormatter('%Y-%m-%d')) plt.xlabel('Date') plt.ylabel('Price') plt.title(stock) # plt.legend() plt.show()
def _get_historical_prices(self, tickers, start_date, end_date): # pf = data.DataReader( # tickers, "google", start_date, end_date, pause=10) pf = pdr.get_data_google( tickers, start_date, end_date, pause=10) pf = pf.astype(np.float32) return pf
def graph_data(stock, start, end): stock_data = pdr.get_data_google(stock)[start:end] date = stock_data['Close'].index closep = stock_data['Close'].values plt.plot_date(date, closep, '-', label='Price') plt.xlabel('Date') plt.ylabel('Close Price') plt.title(stock + ' Stock Price') plt.legend() plt.show()
def get_prices( symbols: List[str], start_date: datetime.datetime = business_day(datetime.date.today(), 30), end_date: datetime.datetime = business_day(datetime.date.today(), 1)): ## TODO: par import pandas_datareader as pdr import pandas as pd df = pd.DataFrame() for s in symbols: print("Downloading {0}".format(s)) # df_tmp = pdr.get_data_yahoo(symbols=s, start=start_date, end=end_date) df_tmp = pdr.get_data_google(symbols=s, start=start_date, end=end_date) # adjusted? df[s] = df_tmp["Close"] # df[s] = df_tmp["Adj Close"] return df
def reset(self): self.cerebro = bt.Cerebro() # self.data = btf.YahooFinanceData(dataname=self.ticker, # from_date=self.from_date, # to_date=self.to_date, # adjusted=True, # reverse=False) self.pandas_data = pdr.get_data_google(self.ticker, start=self.from_date, end=self.to_date) self.pandas_data.drop('Volume', inplace=True, axis=1) self.data = bt.feeds.PandasData(dataname=self.pandas_data) self.cerebro.adddata(self.data) self.cerebro.broker.setcash(100000.0) self.cerebro.broker.setcommission(commission=0.001) self.cerebro.addstrategy(EnvironmentStrategy, environment=self) self.cerebro.addsizer(bt.sizers.PercentSizer, percents=5) self.min_value = self.cerebro.broker.getvalue() * 0.7 self._setup_scaler()
def graph_data(stock): stock_data = pdr.get_data_google(stock) fig = plt.figure() ax1 = plt.subplot2grid((1, 1), (0, 0)) ax1.plot(stock_data.index, stock_data['Close']) ax1.plot([], [], label='loss', color='r', linewidth=5) ax1.plot([], [], label='gain', color='g', linewidth=5) ax1.fill_between(stock_data.index, stock_data['Close'], stock_data['Close'][0], where=(stock_data['Close'] > stock_data['Close'][0]), facecolor='g', alpha=0.4) ax1.fill_between(stock_data.index, stock_data['Close'], stock_data['Close'][0], where=(stock_data['Close'] < stock_data['Close'][0]), facecolor='r', alpha=0.4) for label in ax1.xaxis.get_ticklabels(): label.set_rotation(45) ax1.grid(True) #ax1.xaxis.label.set_color('c') #ax1.yaxis.label.set_color('r') #ax1.set_yticks([0, 25, 50, 75]) plt.xlabel('Date') plt.ylabel('Price') plt.title(stock) plt.legend() plt.show()
import pandas_datareader as pdr import matplotlib.pyplot as plt import datetime aapl = pdr.get_data_google('AAPL', start=datetime.datetime(2010, 10, 1), end=datetime.datetime(2016, 1, 1)) # aapl.to_csv('aapl_ohlc.csv') # df = pd.read_csv('aapl_ohlc.csv', header=0, index_col='Date', parse_dates=True) sample = aapl.sample() print(aapl.pct_change().describe()) aapl.resample('BM').mean().pct_change().cumprod().plot(grid=True) plt.show()
import pandas_datareader as pdr import datetime import pandas as pd #get data from yahoo aapl = pdr.get_data_yahoo('AAPL', start=datetime.datetime(2011, 10, 1), end=datetime.datetime(2012, 1, 1)) print(aapl) #get data from google aapl2 = pdr.get_data_google('AAPL', start=datetime.datetime(2017, 10, 1), end=datetime.datetime(2017, 11, 11)) print(aapl2) print(aapl2.loc[pd.Timestamp('2017-11-01'):pd.Timestamp('2017-12-31')])
#!/usr/bin/env python3 import numpy as np import pandas as pd import pandas_datareader as pdr gld = pdr.get_data_google('GLD','2016-11-08')
def data(ticker): return pdr.get_data_google(ticker, start=startdate, end=enddate)
def __init__(self, sym): self.sym = sym self.data = pdr.get_data_google(sym)
ecoindex_joined['USE_YN'] == 'Y', col_df['Field'].values].drop_duplicates() udb.insert_mysql( ecoindex_mas_new_rows, h='35.188.205.252', port=3306, u='mas', p='mas', db='finance_db', table=TABLE_NM, logging=False, ) # `RAW` ---------------------------------------------------------------------- import pandas_datareader as pdr import datetime as dt pdr.get_data_google('KRX:KOSPI', dt.datetime(2010, 1, 1), dt.datetime(2010, 12, 31)) pdr.data.DataReader('KRX:KOSPI', 'google', dt.datetime(2010, 1, 1), dt.datetime(2010, 12, 31)) jj = 'http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json' with urllib.request.urlopen(jj) as resp: jfile = resp.read() jfile[:2]
def Print_Market_Profile(symbol, height_precision=1, frequency='m', start_date=None, end_date=None): # We will look at stock prices over the past year if start_date == None: # get a year's worth of data from today start_date = datetime.date.today() - datetime.timedelta(days=365.24) # set date to first of month start_date = start_date.replace(day=1) if end_date == None: end_date = datetime.date.today() fin_prod_data = pdr.get_data_google(symbol.upper(), start_date, end_date) fin_prod_data[('High')] = fin_prod_data[('High')] * height_precision fin_prod_data[('Low')] = fin_prod_data[('Low')] * height_precision fin_prod_data = fin_prod_data.round({'Low': 0, 'High': 0}) time_groups = fin_prod_data.groupby( pd.TimeGrouper(freq=frequency))['Adj Close'].mean() current_time_group_index = 0 # from collections import defaultdict mp = defaultdict(str) char_mark = 64 # build dictionary with all needed prices tot_min_price = min(np.array(fin_prod_data['Low'])) tot_max_price = max(np.array(fin_prod_data['High'])) for price in range(int(tot_min_price), int(tot_max_price)): mp[price] += ('\t') # add max price as it will be ignored in for range loop above mp[tot_max_price] = '\t' + str( time_groups.index[current_time_group_index])[5:7] + '/' + str( time_groups.index[current_time_group_index])[3:4] for x in range(0, len(fin_prod_data)): if fin_prod_data.index[x] > time_groups.index[current_time_group_index]: # new time period char_mark = 64 # buffer and tab all entries buffer_max = max([len(v) for k, v in mp.iteritems()]) current_time_group_index += 1 for k, v in mp.iteritems(): mp[k] += (chr(32) * (buffer_max - len(mp[k]))) + '\t' mp[tot_max_price] += str( time_groups.index[current_time_group_index])[5:7] + '/' + str( time_groups.index[current_time_group_index])[3:4] char_mark += 1 min_price = fin_prod_data['Low'][x] max_price = fin_prod_data['High'][x] for price in range(int(min_price), int(max_price)): mp[price] += (chr(char_mark)) sorted_keys = sorted(mp.keys(), reverse=True) for x in sorted_keys: # buffer each list print( str("{0:.2f}".format((x * 1.0) / height_precision)) + ': \t' + ''.join(mp[x]))
GoogleDailyReader.url = url ############################################################# # get data import pandas as pd import pandas_datareader as pdr import numpy as np from datetime import datetime #Includes for data load tickers = ['SPY', 'BND', 'TLT'] start = datetime(2017, 1, 1) #Calculate returns and add ticker symbol tck = tickers[0] data = pdr.get_data_google(tck, start) returns = ((data['Close'][1:] - data['Close'].shift(1)) / data['Close'][1:])[1:] returns = returns.to_frame() data['ticker'] = tck returns['ticker'] = tck for tck in tickers[1:]: temp = pdr.get_data_google(tck, start) temp['ticker'] = tck data = data.append(temp) temp = ((temp['Close'][1:] - temp['Close'].shift(1)) / temp['Close'][1:])[1:] temp = temp.to_frame() temp['ticker'] = tck returns = returns.append(temp)
import pandas_datareader as getData import datetime ##gets the data using pandas module, and stores it in the dataframe object "ge" ge = getData.get_data_google('GE',start=datetime.datetime(2017, 9, 1),end=datetime.datetime(2017,10,10)) ## creates another column of data in the dataframe, composed of the opening price - the closing price ge['diff']= ge.Open - ge.Close ##prints your results, the first 5 results specifically. If you want the entire data set, take out "head()" print(ge.head(5)) #similar method to get data from pandas and store it into the "aapl" dataframe aapl = getData.DataReader("AAPL", "google", start="2017/9/1", end="2017/9/20") #manipulates the data, just like above aapl['diff']= aapl.Open - aapl.Close #prints results print(aapl.tail(5)) ##here, we take our data from the dataframe and export it to a CSV file. useful to get out data visualized aapl.tail(5).to_csv('aapl.csv') ##another example to get data from pandas and store in the "MSFT" dataframe, using variables in the paramaterization of the dataframe ticker = 'MSFT' begdate = datetime.datetime(2017,1,2) enddate = datetime.datetime(2017,1,10) a = getData.DataReader(ticker, 'google',begdate, enddate) print(a.head()) ##A simple example of how to just print the head of some values print(getData.get_data_google('JPM').head())
import csv import pandas as pd import pandas_datareader as pdr import datetime as dt import numpy as np import matplotlib.pyplot as plt aapl = pdr.get_data_google('AAPL', '2017-01-01') aapl_cls = pd.DataFrame(aapl['Close']) aapl_cls['MA_9'] = aapl_cls['Close'].rolling(9).mean().shift() aapl_cls['MA_21'] = aapl_cls['Close'].rolling(21).mean() plt.figure(figsize=(15, 10)) plt.grid(True) plt.plot(aapl_cls['Close'], label='AAPL') plt.plot(aapl_cls['MA_9'], label='9 Day') plt.plot(aapl_cls['MA_21'], label='21 Day') plt.legend(loc=2) aapl_cls['Change'] = np.log(aapl_cls['Close'] / aapl_cls['Close'].shift()) plt.plot(aapl_cls.Change) aapl_cls['Volatility'] = aapl_cls.Change.rolling(21).std().shift() aapl_cls['Volatility'].plot() aapl_cls['Actual_Change'] = aapl_cls['Close'] - aapl_cls['Close'].shift() aapl_cls['Expected_Change'] = aapl_cls['Close'] * aapl_cls['Volatility'] aapl_cls = aapl_cls.dropna() aapl_cls.head() aapl_cls['Magnitude'] = aapl_cls['Actual_Change'] / aapl_cls['Expected_Change'] plt.hist(aapl_cls['Magnitude'], bins=50)
import numpy import pandas import pandas_datareader as pdr import json data = pdr.get_data_google('FRA:(insert ticker symbol here)') data.to_json('insert directory of output file') #print(data) #print(type(data)) #with open('directory', 'a') as outfile: #writer = csv.writer(outfile, delimiter=',') #for line in data: #writer.writerow(line) #with open('test.json', 'a') as outfile: #json.dump(data, outfile)
from Trading import backtest, strategy import pandas_datareader as pdr import datetime if __name__ == '__main__': symbol = 'AAPL' start = datetime.datetime(2006, 10, 1) end = datetime.datetime(2016, 1, 1) bars = pdr.get_data_google(symbol, start=start, end=end) mac = strategy.MovingAverageCrossStrategy(bars, 40, 100) signals = mac.generate_signals() portfolio = backtest.MarketOnClosePortfolio(symbol, bars, signals, 100000.0) returns = portfolio.backtest_portfolio() mac.graph() portfolio.graph()
def history_google(code, start, end): return pdr.get_data_google(code, start, end)