def get(self, request, tickers): if (tickers == 'all'): quotes = get_current_trade_data() else: quotes = get_current_trade_data(str(tickers)) #quotes = quotes.to_json(orient='records', lines=True, compression='gzip') quotes = quotes.to_json(orient='records', compression='gzip') return JsonResponse(ast.literal_eval(quotes), safe=False)
def get(self, request, tickers): if (tickers == 'all'): quotes = get_current_trade_data() else: quotes = get_current_trade_data(str(tickers)) # if(quotes): # quotes = quotes(orient='records', lines=True, compression='gzip') # _, created = TickerUpdate.objects.update_or_create() # dbquotes = TickerUpdate.objects.all() # results = QuotesSerializer(dbquotes, many=True).data # else: # dbquotes = TickerUpdate.objects.all() # results = QuotesSerializer(dbquotes, many=True).data quotes = quotes.to_json(orient='records', compression='gzip') return Response(ast.literal_eval(quotes))
def get_market_value(self): """ Return portfolio's market value. This is sum of cash and market value of long positions. Returns: float: portfolio's market value """ market_value = self.cash long_stocks = [stock for stock in self.stocks.all() if stock.quantity > 0] if long_stocks: long_stocks_tickers = ",".join([stock.ticker.symbol for stock in long_stocks]) long_stocks_quote = get_current_trade_data(long_stocks_tickers) for stock in long_stocks: market_value += long_stocks_quote[stock.ticker]['ltp']*stock.quantity return market_value
def test_get_current_trade_data(self): df = get_current_trade_data() print(df.to_string())
import sys from prettytable import PrettyTable t = PrettyTable(['\33[33m'+'Name', 'LTP', 'High','Low', 'YCP','Change(%)','Trade','Volume'+'\033[0m']) if (sys.argv[1]=='--add'): name = open("stocklist.txt", "w") addline='' for newstock in sys.argv[2:]: addline = addline + ','+ newstock name.write(addline) name.close() print("***The stocks have been added in the list***") quit() stock=open("stocklist.txt","r") kolla = stock.read().split(',') pad = kolla if sys.argv[1] == '--n' else sys.argv for stck in pad[1:]: df = get_current_trade_data(stck) ltp = str(df['ltp']).split()[1] High = str(df['high']).split()[1] low = str(df['low']).split()[1] ycp= str(df['ycp']).split()[1] Change= "{:.2f}".format((float(ltp)-float(ycp))*100/float(ycp)) change= '\033[91m'+str(Change)+'\033[0m' if float(Change)<= 0 else '\033[32m'+str(Change)+'\033[0m' Trade=str(df['trade']).split()[1] Volume=str(df['volume']).split()[1] t.add_row([stck, ltp, High , low, ycp, change, Trade, Volume]) print(t)
def perform_create(self, serializer): # Assign request data to local variables portfolio = get_object_or_404(Portfolio, id=self.kwargs['portfolio_id']) ticker = self.request.data['ticker'].upper() requested_quantity = int(self.request.data['quantity']) if requested_quantity <= 0: raise ValidationError("Cannot transact negative units.") transaction_type = self.request.data['transaction_type'] # Get price of ticker and total transaction amount price = get_current_trade_data(ticker)[ticker]['price'] transaction_amount = round(requested_quantity * price, 2) # Get the held stock if it already exists in the portfolio. Otherwise held_stock is None held_stock = portfolio.stocks.filter(ticker=ticker).first() if transaction_type == 'Buy': # Check if portfolio has sufficient funds to execute transaction if transaction_amount > portfolio.cash: raise ValidationError( 'Insufficient cash to buy {} shares of {}'.format( requested_quantity, ticker)) portfolio.cash -= transaction_amount portfolio.save() if held_stock: held_stock.quantity += requested_quantity if held_stock.quantity == 0: held_stock.delete() else: held_stock.save() else: # ticker doesn't exist in portfolio, create new Stock new_stock = Stock(ticker=ticker, quantity=requested_quantity, portfolio=portfolio) new_stock.save() elif transaction_type == 'Sell': # If you hold more units than you want to sell, proceed. if held_stock and held_stock.quantity >= requested_quantity: portfolio.cash += transaction_amount portfolio.save() held_stock.quantity -= requested_quantity if held_stock.quantity == 0: held_stock.delete() else: held_stock.save() # Else we attempt to short and must check if equity > 150% short exposure else: short_exposure = portfolio.get_short_exposure() # If we don't have stock or have a short position in it, increase our short exposure # by transaction amount. if not held_stock or held_stock.quantity < 0: short_exposure += transaction_amount # If we have stock but the sell transaction will move us into a short position, # add the remaining units to short exposure elif held_stock.quantity < requested_quantity: short_exposure += (requested_quantity - held_stock.quantity) * price # If our equity is > 150% of short exposure, proceed with transaction equity = portfolio.get_market_value() + transaction_amount if short_exposure * 1.5 < equity: portfolio.cash += transaction_amount portfolio.save() if held_stock: held_stock.quantity -= requested_quantity held_stock.save() else: # Create new short stock position if not held new_stock = Stock(ticker=ticker, quantity=-requested_quantity, portfolio=portfolio) new_stock.save() else: raise ValidationError(( "This transaction will bring your equity to {0}, but your total " "short exposure will be {1}. Your equity must be greater than " "150% of your total short exposure to proceed." ).format(equity, short_exposure)) serializer.save(ticker=ticker, portfolio=portfolio, price=price)