class VendingMachine: def __init__(self): self.stock = Stock({'coke': 5, 'diet coke': 5, 'tea': 5}) self.money_manager = MoneyManager(5)#わかりにくい #stock探すのと、おつりに入れる def __check_stock(self, kindOfDrink, coin): if self.stock.check_stock(kindOfDrink): #raise ValueError("stockがありません!") return True return False def __check_charge_stock(self, coin): if self.money_manager.check_charge(coin): return True return False def __buy_drink(self, kindOfDrink, coin): drink = self.stock.take_from_stock(kindOfDrink) self.money_manager.take_from_stock_charge(coin)#ここ return drink def buy(self, coin, kindOfDrink):#処理ごとにメソッドわける """購入する Arguments: coin {Coin} -- 投入金額. 100円と500円のみ受け付ける. kindOfDrink {Enum} -- ジュースの種類. コーラ({@code Juice.COKE}),ダイエットコーラ({@code Juice.DIET_COKE},お茶({@code Juice.TEA})が指定できる. Returns: Drink-- 指定したジュース. 在庫不足や釣り銭不足で買えなかった場合は {@code null} が返される. """ #飲み物の在庫確認 if not self.__check_stock(kindOfDrink, coin): return coin #釣り銭の在庫確認 if not self.__check_charge_stock(coin): return coin #釣り銭の計算と、stockの操作 drink = self.__buy_drink(kindOfDrink, coin) return drink def refund(self): """お釣りを取り出す Returns: int-- お釣りの金額 """ money = self.money_manager.get_charge() return money
def build_treemap(stocks): """ Takes a list of Stocks and returns a binary tree, constructed greedily, where each internal node represents the market cap of its two children, and each leaf is a Stock. Leaves contain the original Stock objects. Internal nodes store "Super" stocks that represent the sum of the market caps of all Stocks in their subtree. Args: stocks (list of Stock): a list of Stock objects Yields: Tree: the root node of the binary tree """ trees = [Tree(stock) for stock in stocks] trees.sort(reverse=True, key=lambda t: t.value.cap) while len(trees) > 1: tree1 = trees.pop() tree2 = trees.pop() t1value = tree1.value t2value = tree2.value superstock = Stock(t1value.symbol + " " + t2value.symbol, t1value.cap + t2value.cap, t1value.change + t2value.change) trees.append(Tree(superstock, tree1, tree2)) trees.sort(reverse=True, key=lambda t: t.value.cap) return trees[0]
def setUp(self): ''' Setting data for unit tests ''' self.common_stock = Stock('ABCD', EnumStockTypes.COMMON, 100, 8, None, 100) self.preferred_stock = Stock('EFGH', EnumStockTypes.PREF, 100, 8, 0.02, 100) self.common_stock_division_by_zero = Stock('ABCD', EnumStockTypes.COMMON, 0, 8, None, 100) self.preferred_stock_division_by_zero = Stock('EFGH', EnumStockTypes.PREF, 100, 8, 0.02, 0) self.calculator = Calculator() self.common_trade = Trade(self.common_stock, datetime.strptime("09/09/18 16:30:31", "%d/%m/%y %H:%M:%S") , 200, EnumBuySellIndicator.BUY.value , 150) self.preferred_trade = Trade(self.preferred_stock, datetime.strptime("09/09/18 16:30:32", "%d/%m/%y %H:%M:%S"), 300, EnumBuySellIndicator.SELL.value, 200) self.list_of_trades.append(Trade(self.common_stock, datetime.strptime("09/09/18 16:30:29", "%d/%m/%y %H:%M:%S") , 200, EnumBuySellIndicator.BUY, 150)) self.list_of_trades.append(Trade(self.common_stock, datetime.strptime("09/09/18 16:30:30", "%d/%m/%y %H:%M:%S") , 200, EnumBuySellIndicator.BUY, 150)) self.list_of_trades.append(Trade(self.common_stock, datetime.strptime("09/09/18 16:30:31", "%d/%m/%y %H:%M:%S") , 200, EnumBuySellIndicator.BUY, 150)) self.list_of_trades.append(Trade(self.preferred_stock, datetime.strptime("09/09/18 16:45:30", "%d/%m/%y %H:%M:%S"), 300, EnumBuySellIndicator.SELL, 200)) self.list_of_trades.append(Trade(self.preferred_stock, datetime.strptime("09/09/18 16:45:30", "%d/%m/%y %H:%M:%S"), 300, EnumBuySellIndicator.SELL, 200)) self.list_of_trades.append(Trade(self.preferred_stock, datetime.strptime("09/09/18 16:45:30", "%d/%m/%y %H:%M:%S"), 300, EnumBuySellIndicator.SELL, 200))
def fetch_stock_data(self, stocks, run_no, data_depth, observed_days): no_go_stocks = ['OBTEST0' + str(i) for i in range(10)] # try: html_text = urllib.request.urlopen( "http://www.netfonds.no/quotes/kurs.php", None, 5).read() stock_market = re.findall( re.compile(b'<td name="ju.last.(.+?).OSE">(.+?)</td>'), html_text) if stocks != 'all': stock_market = [ stock for stock in stock_market if stock[0].decode("UTF-8") in stocks ] if run_no == 0: for (stock, price) in stock_market: if stock.decode("UTF-8") not in no_go_stocks: self.stocks.append(Stock(stock.decode("UTF-8"))) else: pass print("Fetching data...") error_stocks = [] for stock in self.stocks: if data_depth == 'day': stock.fetch_intraday_data(run_no) elif data_depth == 'historic': error = stock.fetch_historic_data(run_no, observed_days) if error != None: error_stocks.append(stock) self.stocks = [ stock for stock in self.stocks if not stock in error_stocks ] print("Finished fetching data")
def scrapper(): stock_list = [] driver = webdriver.Chrome(executable_path='/usr/local/bin/chromedriver', ) driver.get("https://finance.yahoo.com/gainers") result = driver.page_source #load entire page assert "Stock" in driver.title tbody = driver.find_element_by_tag_name("tbody") for row in tbody.find_elements_by_tag_name("tr"): cells = row.find_elements_by_tag_name("td") symbol = cells[0].text name = cells[1].text price = cells[2].text change = cells[3].text percent_change = cells[4].text stock_list.append(Stock(symbol, name, price, change, percent_change)) top_names = [] top_symbols = [] top_price = [] top_change = [] top_percent_change = [] for top_stock in stock_list[:5]: top_names.append(top_stock.name) top_symbols.append(top_stock.symbol) top_price.append(top_stock.price) top_change.append(top_stock.change) top_percent_change.append(top_stock.percent_change) data_top_5 = { 'Name': top_names, 'Symbol':top_symbols, 'Price':top_price, 'Change':top_change, 'Change (%)':top_percent_change } df = pd.DataFrame(data_top_5, columns=['Name', 'Symbol', 'Price', 'Change', 'Change (%)']) print(df) driver.close()
def __init__(self, stocks: dict()): """Inits Market instance and constructs stock dictionary """ self.stocks = {ticker : Stock(ticker) for ticker in stocks}
from timeseries import TimeSeries import csv from stocks import StockRecord, Stock myAPIkey = 'Your API KEY' ts = TimeSeries(key=myAPIkey, output_format='csv', indexing_type='integer') data, metadata = ts.get_intraday(symbol='ASX', interval='60min', outputsize='full') IND = StockRecord(symbol='IND') counter = 0 for row in data: if counter != 0: newStockEntry = Stock(counter, row[1], row[4], row[2], row[3], row[5]) IND.addStock(newStockEntry) counter += 1 print(IND) IND.showRecords() print(IND)
def test_create_stock(self, symbol_, last_dividend_, par_value_): with self.assertRaises(TypeError): Stock(symbol_, last_dividend_, par_value_)
import argparse from stocks import Stock from userinput import CSVInput, UserInput parser = argparse.ArgumentParser(conflict_handler='resolve') parser.add_argument('csv_file', nargs='?', default=None, help="CSV file path") args = parser.parse_args() csv_file = args.csv_file if __name__ == "__main__": all_stock_data = CSVInput().read(csv_file) user_input = UserInput(list(all_stock_data.keys()))() stock_records = all_stock_data[user_input['name']] stock = Stock(stock_records, user_input['start_date'], user_input['end_date']) stock.print_all_data()
def __init__(self): self.stock = Stock({'coke': 5, 'diet coke': 5, 'tea': 5}) self.money_manager = MoneyManager(5)#わかりにくい
def setup(self): self.stock = Stock('FB')
def process_recos_html(reco_elements): ''' Input is of type bs4.element.ResultSet. Each element represents one stock in reco table which needs to be converted to Stock object and stored in DB :param reco_elements: :return: ''' # record new recos encountered new_recos = [] for row in reco_elements: cells = list(row.find_all('td')) # Sample row # 0: <td> # <a href="/stocks/296/ashiana-housing-ltd#premium-coverage"> # Ashiana Housing </a> # <small class="text-capitalize drkgrey"></small> </td> # 1: <td data-order="20171027" width="8%"> # 27-Oct-17 </td> # 2: <td class="text-right">166.70</td> # 3: <td class="text-right">147.25</td> # 4: <td class="text-right" width="">-11.7</td> # 5: <td class="text-right" width="">3.5</td> # 6: <td class="text-right">1,520</td> # 7: <td class="text-right ">39.77</td> # 8: <td class="text-right ">1.99</td> # 9: <td class="text-right">24/30</td> # 10: <td class="text-center text-right"><a class="text-uppercase view-coverage" href="/coverage?company_code=296">view</a></td> # 11: <td class="text-center text-right"> # <a class="text-uppercase add-watchlist" href="#"> added </a> # </td> if len(cells) < 2: # not a valid row break reco_date = cells[1].text.strip() # Extract name and stock_id from 1st cell reco_name = cells[0].text.strip() if '\n' in reco_name: stock_name, stock_type = reco_name.split('\n') stock_name = stock_name.strip() stock_type = stock_type.strip() else: stock_name = reco_name stock_type = 'NA' # extract href href = cells[0].find_all('a')[0]['href'] vr_code = href.rsplit('/')[2] stock_symbol = get_symbol(vr_code) # Timely or All-weather -- this can be missing. #stock_type = row.find() print(f' {stock_name},{stock_type}, {stock_symbol}') # cells[2] -- market cap not required right now reco_date_price = cells[3].text.strip() print(f" 2: {cells[2].text}") print(f" 3: {cells[3].text}") #(self, name, type, symbol, reco_date, reco_date_price, stock_id) # create a stock object check if it exists in db if not add. if not check_stock_in_db(stock_symbol): stock = Stock(stock_name, stock_type, stock_symbol, reco_date, reco_date_price, vr_code) new_recos.append(stock) # add_recos to the csv file add_recos(new_recos) print(f"Saved {len(new_recos)}") #TODO Send alert for new recos added using list new_recos return
def week_8(): ''' create accounts database, within accounts.db there will be 3 tables: investor, stock, bond ''' #database name current_date = date.today() db_name = "accounts.db" table_name = "investor" db_table_headers = """ investor_id text, name text, address text, phone_number text """ #create_table investor table if it does not exist db.create_table(db_name, table_name, db_table_headers) #create instance of Investor Object uuid generates unique ID in hex format as string investor = Investor(uuid.uuid1().hex, "Bob Smith", "2199 S University Blvd, Denver, CO 80208", "303-871-2000") #content to add to database record content = (investor.investor_id, investor.name, investor.address, investor.phone_number) #create record in investor table db.add_one(db_name, table_name, content) #date object with today's date print() #[0][0]access first list and first tuple itme in db query print("Investor Name: " + db.get_selected_data(db_name, table_name, "name")[0][0]) print("Investor Address: " + db.get_selected_data(db_name, table_name, "address")[0][0]) print("Investor Phone: " + db.get_selected_data(db_name, table_name, "phone_number")[0][0]) ''' ==================================================================== STOCK SECTION ==================================================================== ''' #declare variables sub_header = [] stocks = [] #stores stock object(s) stock_file = "Lesson6_Data_Stocks.csv" #opening stock file try: read_file = open(stock_file, "r") except FileNotFoundError: print("Could not open the file, program terminated! I'll be back!") exit() #exit application if file cannot be found #create list of items separated by comma delimiters sub_header = read_file.readline().split(',') #remove the '\n' character at the end of the line sub_header[-1] = sub_header[-1][:-1] #add investor id to subheader list sub_header.append("investor_id") #create stocks table in database db_name = "accounts.db" table_name = "stocks" #sub_header = [0] = SYMBOL, [1] = NO_SHARES, [2] = PUR_PRICE, [3] = CUR_VALUE, [4] = PUR_DATE db_table_headers = "investor_id text, stock_id text," + sub_header[0] + " text, " \ + sub_header[1] + " integer, " + sub_header[2] + " real, " \ + sub_header[3] + " real, " + sub_header[4] + " text" #create_table investor table if it does not exist db.create_table(db_name, table_name, db_table_headers) #read data from stock file and store in stocks[] for line in read_file: line_split = line.split(',') #removed the '/n' from the last item line_split[-1] = line_split[-1][:-1] symbol = line_split[0] quantity = int(line_split[1]) purchase_price = float(line_split[2]) current_price = float(line_split[3]) #converts string formated as MM/DD/YYYY to date object purchase_date = datetime.strptime(line_split[4], '%m/%d/%Y').date() #create object and appends to list stock = Stock(symbol, purchase_price, current_price,quantity,purchase_date, \ investor.investor_id, uuid.uuid1().hex ) #uuid generates unique transaction number stocks.append(stock) #add record to database content = (investor.investor_id, stock.id, stock.symbol, stock.quantity, stock.purchase_price, stock.current_price, stock.purchase_date) #create record in investor table db.add_one(db_name, table_name, content) read_file.close() #sub_header = [0] = SYMBOL, [1] = NO_SHARES, [2] = PUR_PRICE, [3] = CUR_VALUE, [4] = PUR_DATE data = db.get_selected_data(db_name,"stocks", sub_header[0] + ", " + sub_header[1] + ", " + \ sub_header[2] + ", " + sub_header[3] + ", " + sub_header[4]) #print table stock table print() print("=================== Stock Positions ===================") stock_table = PrettyTable() stock_table.field_names = [ sub_header[0], sub_header[1], "Earnings/Loss", "Yearly Earning/Loss" ] for row in data: #instance of stock class stock = Stock(row[0], row[2], row[3], row[1], row[4], None, None) earnings = round(stock.calculate_earnings(row[3], row[2], row[1]), 2) purchase_date = datetime.strptime(row[4], '%Y-%m-%d').date() yearly_earnings = round(stock.calculate_yearly_earnings(row[3], row[2], \ current_date, purchase_date), 2) stock_table.add_row([ row[0], row[1], "$ {:,.2f}".format(earnings), str(yearly_earnings) + " %" ]) print(stock_table) ''' ============================================================= Week 8 JSON to DB ============================================================= ''' filename = "AllStocks.json" dates = [] transactions = [] symbols = ["GOOG", "MSFT", "RDS-A", "AIG", "FB", "M", "F", "IBM"] db_name = "accounts.db" table_name = "json_data" db_table_headers = """ Symbol text, Date text, Open text, High text, Low text, Close real, Volume integer """ #load JSON file try: with open(filename) as f: stocks = json.load(f) except FileNotFoundError: print("Could not find file") exit() # #create database db.create_table(db_name, table_name, db_table_headers) #pass informatiom from JSON to DB for stock in stocks: content = (stock["Symbol"], stock["Date"], stock["Open"], stock["High"], stock["Low"], stock["Close"], stock["Volume"]) db.add_one(db_name, table_name, content) for stock in stocks: #convert date string to date object purchase_date = datetime.strptime(stock["Date"], '%d-%b-%y').date() transactions.append({ "Symbol": stock["Symbol"], "Date": purchase_date, "Close": float(stock["Close"]) }) # creates lists with all the different dates for stock in transactions: date = stock["Date"] if date in dates: pass else: dates.append(date) dates = sorted(dates) #hold total portifolio value per day total = [] #make data symetrical so it can be graphed data_to_graph = [] for date in dates: for symbol in symbols: close_price = get_close_price(symbol, date, transactions) data_graph = add_stock(symbol, date, close_price, transactions, data_to_graph) total data_to_graph = sorted(data_to_graph, key=lambda stock: (stock['Symbol'], stock['Date'])) plt.plot(dates, get_stock_value_history("GOOG", 125, data_to_graph)) plt.plot(dates, get_stock_value_history("MSFT", 85, data_to_graph)) plt.plot(dates, get_stock_value_history("RDS-A", 400, data_to_graph)) plt.plot(dates, get_stock_value_history("AIG", 235, data_to_graph)) plt.plot(dates, get_stock_value_history("FB", 150, data_to_graph)) plt.plot(dates, get_stock_value_history("M", 425, data_to_graph)) plt.plot(dates, get_stock_value_history("F", 85, data_to_graph)) plt.plot(dates, get_stock_value_history("IBM", 80, data_to_graph)) plt.legend(symbols) plt.title("Stock Positions") plt.ylabel('Value in Dollars') plt.xlabel("Date") plt.savefig('stock_positions.png') plt.show() ''' ==================================================================== BOND SECTION ==================================================================== ''' sub_header = [] bonds = [] #hold bond object(s) bond_file = "Lesson6_Data_Bonds.csv" #try opening stock file try: read_file = open(bond_file, "r") except FileNotFoundError: print("Could not open the file, program terminated! I'll be back!") exit() #exit application if file cannot be found sub_header = read_file.readline().split(',') #remove the '\n' character at the end of the line sub_header[-1] = sub_header[-1][:-1] #create bonds table in database db_name = "accounts.db" table_name = "bonds" #sub_header = [0] = SYMBOL, [1] = NO_SHARES, [2] = PUR_PRICE, [3] = CUR_VALUE, [4] = PUR_DATE #[5] = COUPON, [6] = YIELD db_table_headers = "investor_id text, bond_id text," + sub_header[0] + " text, " \ + sub_header[1] + " integer, " + sub_header[2] + " real, " \ + sub_header[3] + " real, " + sub_header[4] + " text," \ + sub_header[5] + " real, " + sub_header[6] + " real" #create_table investor table if it does not exist db.create_table(db_name, table_name, db_table_headers) #read data from bond file and store in bonds[] for line in read_file: line_split = line.split(',') #removed the '/n' from the last item line_split[-1] = line_split[-1][:-1] symbol = line_split[0] quantity = int(line_split[1]) purchase_price = float(line_split[2]) current_price = float(line_split[3]) #converts string formated as MM/DD/YYYY to date object purchase_date = datetime.strptime(line_split[4], '%m/%d/%Y').date() coupon = float(line_split[5]) bond_yield = float(line_split[6]) bond = Bond(symbol, purchase_price, current_price, quantity, purchase_date, investor.investor_id, uuid.uuid1().hex, coupon, bond_yield) bonds.append(bond) #add record to database content = (investor.investor_id, bond.id, bond.symbol, bond.quantity, bond.purchase_price, bond.current_price, bond.purchase_date, bond.coupon, bond.bond_yield) #create record in investor table db.add_one(db_name, table_name, content) read_file.close() #sub_header = [0] = SYMBOL, [1] = NO_SHARES, [2] = PUR_PRICE, [3] = CUR_VALUE, [4] = PUR_DATE # [5] = COUPON, [6] = YIELD data = db.get_selected_data(db_name,"bonds", \ sub_header[0] + ", " + sub_header[1] + ", " + \ sub_header[2] + ", " + sub_header[3] + ", " + \ sub_header[4] + ", " + sub_header[5] + ", " + \ sub_header[6]) #print table bond table print() print("=================== Bond Positions ===================") bond_table = PrettyTable() bond_table.field_names = [sub_header[0], sub_header[1], "Earnings/Loss", \ "Yearly Earning/Loss", sub_header[5], sub_header[6]] for row in data: #instance of stock class #[0] = SYMBOL, [1] = NO_SHARES, [2] = PUR_PRICE, [3] = CUR_VALUE, [4] = PUR_DATE #[5] = COUPON, [6] = YIELD bond = Bond(row[0], row[2], row[3], row[1], row[4], None, None, row[5], row[6]) earnings = round(bond.calculate_earnings(row[3], row[2], row[1]), 2) purchase_date = datetime.strptime(row[4], '%Y-%m-%d').date() yearly_earnings = round(bond.calculate_yearly_earnings(row[3], row[2], \ current_date, purchase_date), 2) #[0] = SYMBOL, [1] = NO_SHARES, [5] = COUPON, [6] = YIELD bond_table.add_row([row[0], row[1], "$ {:,.2f}".format(earnings), \ str(yearly_earnings) + " %", row[5], row[6]]) print(bond_table)