Generative-AI-Tools für Entwickler

CodeWhisperer, Bard und Copilot X im Test

30.06.2023
Von 
Martin Heller schreibt als freier Autor für die Schwesterpublikation InfoWorld.

Google Bard

Auch Googles Bard greift seit Ende April 2023 Programmierern unter die Arme. Bard unterstützt dabei - laut eigener Aussage - folgende Programmiersprachen:

  • C++

  • Go

  • Java

  • JavaScript

  • Python

  • TypeScript

  • C#

  • PHP

  • Ruby

  • Swift

  • Kotlin

  • Rust

  • Julia

  • R

  • Haskell

  • Erlang

  • Scala

  • Lua

  • OCaml

  • Scheme

Bard kann Code in diesen Sprachen generieren, debuggen und erklären. Darüber hinaus ist Googles Generative AI für Developer auch in der Lage, von einer Programmiersprache in eine andere zu übersetzen:

Die Codegenerierung für den Site Scraper sah auf den ersten Blick relativ glaubwürdig aus, wies aber bei näherer Betrachtung mehrere Probleme auf. Es genügte ein Doppelklick, um den Code in Colab zu öffnen, aber beim Versuch, ihn auszuführen, trat ein Typfehler auf. Anstatt die Probleme zu beheben, haben wir die Codegenerierung erneut ausgeführt - und das Ergebnis machte etwas mehr Sinn. Beim Versuch, den Code in Colab auszuführen, wurde jedoch ein Attributfehler ausgegeben. Nachdem dieser Traceback an Bard zurückgegeben wurde, lieferte das Tool eine Korrektur - die wiederum einen Typfehler an einer anderen Stelle verursachte.

Im Folgenden der von Bard generierte Code für den InfoWorld.com-Scraper:

import requests

from bs4 import BeautifulSoup

def scrape_infoworld():

"""Scrape the InfoWorld front page and return a list of articles."""

# Get the HTML from the InfoWorld front page.

response = requests.get("https://www.infoworld.com/")

soup = BeautifulSoup(response.content, "html.parser")

# Find all articles by looking for links with 'article' in the href.

articles = soup.find_all("a", href=lambda x: "article" in x["href"])

# Extract the title, author, and date from each article.

article_data = []

for article in articles:

title = article.find("h3").text

author = article.find("span", class_="byline").text

date = article.find("time").text

article_data.append({

"title": title,

"author": author,

"date": date,

})

# Sort the articles alphabetically by title.

article_data.sort(key=lambda x: x["title"])

# Remove any duplicate articles.

article_data = list(set(article_data))

# Sort the articles alphabetically by author last name.

article_data.sort(key=lambda x: x["author"].split()[-1])

# Sort the articles latest first.

article_data.sort(key=lambda x: x["date"], reverse=True)

return article_data

if __name__ == "__main__":

articles = scrape_infoworld()

# Print the articles.

for article in articles:

print(article)

Explanation:

This code will first get the HTML from the InfoWorld front page. Then, it will find all articles by looking for links with 'article' in the href. For each article, it will extract the title, author, and date. The articles will then be sorted alphabetically by title, removed of any duplicates, sorted alphabetically by author last name, and sorted latest first. Finally, the articles will be printed.

Und hier das Laufzeitergebnis:

---------------------------------------------------------------------------

TypeError Traceback (most recent call last)

<ipython-input-1-afbe7808577e> in <cell line: 40>()

39

40 if __name__ == "__main__":

---> 41 articles = scrape_infoworld()

42

43 # Print the articles.

6 frames

<ipython-input-1-afbe7808577e> in <lambda>(x)

10

11 # Find all articles by looking for links with 'article' in the href.

---> 12 articles = soup.find_all("a", href=lambda x: "article" in x["href"])

13

14 # Extract the title, author, and date from each article.

TypeError: string indices must be integers

Geht es darum, Quell- und Programmcode zu erklären, lieferte Bard im Test eine bessere Vorstellung ab. Seine Erklärung des MIT-Codebeispiels war so gut, dass wir uns gefragt haben, ob es Teil seiner Trainingsdaten gewesen ist. Hier der bereitgestellte Code:

import pylab, random

class Stock(object):

def __init__(self, price, distribution, vol):

self.price = price

self.history = [price]

self.distribution = distribution

self.vol = vol

self.lastChangeInfluence = 0.0

def setPrice(self, price):

self.price = price

self.history.append(price)

def getPrice(self):

return self.price

def makeMove(self, bias, mo):

oldPrice = self.price

baseMove = self.distribution(self.vol) + bias

self.price = self.price * (1.0 + baseMove)

self.price += mo*random.choice([0.0, 1.0])*self.lastChangeInfluence

self.history.append(self.price)

change = self.price - oldPrice

if change >= 0:

self.lastChangeInfluence = min(change, oldPrice*0.01)

else:

self.lastChangeInfluence = max(change, -oldPrice*0.01)

def showHistory(self, fig, test):

pylab.figure(fig)

pylab.plot(self.history)

pylab.title('Closing Prices, Test ' + test)

pylab.xlabel('Day')

pylab.ylabel('Price')

class SimpleMarket(object):

def __init__(self, numStks, volUB):

self.stks = []

self.bias = 0.0

for n in range(numStks):

volatility = random.uniform(0, volUB)

distribution = lambda vol: random.gauss(0.0, vol)

stk = Stock(100.0, distribution, volatility)

self.addStock(stk)

def addStock(self, stk):

self.stks.append(stk)

def setBias(self, bias):

self.bias = bias

def getBias(self):

return self.bias

def getStocks(self):

return self.stks[:]

def move(self, mo):

prices = []

for s in self.stks:

s.makeMove(self.bias, mo)

prices.append(s.getPrice())

return prices

class Market(SimpleMarket):

def __init__(self, numStks, volUB, dailyBiasRange):

SimpleMarket.__init__(self, numStks, volUB)

self.dailyBiasRange = dailyBiasRange

def move(self, mo):

prices = []

for s in self.stks:

s.makeMove(self.bias + dailyBias, mo)

prices.append(s.getPrice())

return prices

def simMkt(mkt, numDays, mo):

endPrices = []

for i in range(numDays):

vals = mkt.move(mo)

vals = pylab.array(vals)

mean = vals.sum()/float(len(vals))

endPrices.append(mean)

return endPrices

def plotAverageOverTime(endPrices, title):

pylab.plot(endPrices)

pylab.title(title)

pylab.xlabel('Days')

pylab.ylabel('Price')

def plotDistributionAtEnd(mkt, title, color):

prices = []

sumSoFar = 0

for s in mkt.getStocks():

prices.append(s.getPrice())

sumSoFar += s.getPrice()

mean = sumSoFar/float(len(prices))

prices.sort()

pylab.plot(prices, color)

pylab.axhline(mean, color = color)

pylab.title(title)

pylab.xlabel('Stock')

pylab.ylabel('Last Sale')

pylab.semilogy()

def runTrial(showHistory, test, p):

colors = ['b','g','r','c','m','y','k']

mkt = Market(p['numStocks'], p['volUB'], p['dailyBiasRange'])

mkt.setBias(p['bias'])

endPrices = simMkt(mkt, p['numDays'], p['mo'])

pylab.figure(1)

plotAverageOverTime(endPrices, 'Average Closing Prices')

pylab.figure(2)

plotDistributionAtEnd(mkt, 'Distribution of Prices', colors[test%len(colors)])

if showHistory:

for s in mkt.getStocks():

s.showHistory(test+2, str(test))

def runTest(numTrials):

#Constants used in testing

numDaysPerYear = 200.0

params = {}

params['numDays'] = 200

params['numStocks'] = 500

params['bias'] = 0.1/numDaysPerYear #General market bias

params['volUB'] = 12.0/numDaysPerYear #Upper bound on volatility for a stock

params['mo'] = 1.1/numDaysPerYear #Momentum factor

params['dailyBiasRange'] = (0.0, 4.0/200.0)

for t in range(1, numTrials+1):

runTrial(True, t, params)

runTest(3)

pylab.show()

Und Auszüge der mitunter sehr ausführlichen Antwort von Bard:

The code you have provided is a Python program that simulates a stock market. The program defines three classes:

Stock: This class represents a single stock. It has properties for the stock's price, history, distribution, volatility, and last change influence.

SimpleMarket: This class represents a simple stock market. It has a list of stocks, a bias, and a volatility upper bound.

Market: This class inherits from SimpleMarket and adds a daily bias range property. The program also defines several functions:

• simMkt: This function simulates the market for a given number of days and momentum factor.

• plotAverageOverTime: This function plots the average closing price of the stocks over time.

• plotDistributionAtEnd: This function plots the distribution of prices at the end of the simulation.

• runTrial: This function runs a single simulation and plots the results.

• runTest: This function runs a number of simulations and plots the results.

The program is run by calling the runTest function with the desired number of simulations. The program will then generate three plots:

• A plot of the average closing price of the stocks over time.

• A plot of the distribution of prices at the end of the simulation.

• A plot of the history of prices for each stock.

The program can be used to simulate a variety of different stock markets. By changing the values of the parameters, you can change the volatility of the market, the bias of the market, and the momentum factor. You can also use the program to simulate different trading strategies. For example, you could simulate a strategy that buys stocks when they are undervalued and sells them when they are overvalued.

Google Bard - Fazit

Bard verfügt über eine Chat-Schnittstelle, generiert und erklärt Code, verfügt aber nicht über eine interaktive IDE-Integration. Wenn Sie Code in einer der eingangs genannten Programmiersprachen generieren, debuggen oder erklären wollen, ist Googles vollständig kostenloses Generative-AI-Tool zumindest ein Experiment wert.