Home

Team_test_ipynb_2_


Program with Output:

import numpy as np
import pandas as pd
import pandas_datareader.data as web
# Get stock data  
all_data = {ticker: web.DataReader(ticker,'stooq')
           for ticker in ['AAPL', 'NVDA', 'MSFT', 'TSLA', 'AMZN', 'NFLX', 'QCOM', 'SBUX']}
# Extract the 'Adjusted Closing Price'
price = pd.DataFrame({ticker: data['Close']
                     for ticker, data in all_data.items() })
import matplotlib.pyplot as plt
fig1, axes1 = plt.subplots(2,4, sharex = True, sharey = True)

axes1[0,0].plot(price['AAPL'],'-', color = 'gold', label = 'AAPL')
axes1[0,0].legend(loc = 'best')

axes1[0,1].plot(price['NVDA'],'-', color = 'red', label = 'NVDA')
axes1[0,1].legend(loc = 'best')

axes1[0,2].plot(price['MSFT'],'-', color = 'blue', label = 'MSFT')
axes1[0,2].legend(loc = 'best')

axes1[0,3].plot(price['TSLA'],'-', color = 'royalblue', label = 'TSLA')
axes1[0,3].legend(loc = 'best')

axes1[1,0].plot(price['AMZN'],'-', color = 'black', label = 'AMZN')
axes1[1,0].legend(loc = 'best')

axes1[1,1].plot(price['NFLX'],'-', color = 'purple', label = 'NFLX')
axes1[1,1].legend(loc = 'best')

axes1[1,2].plot(price['QCOM'],'-', color = 'pink', label = 'QCOM')
axes1[1,2].legend(loc = 'best')

axes1[1,3].plot(price['SBUX'],'-', color = 'green', label = 'SBUX')
axes1[1,3].legend(loc = 'best') 

# fig1.savefig('stocks1.pdf')
fig = plt.figure()
ax = fig.add_subplot(1,1,1)
plt.plot(price['AAPL'], '-',color = 'gold', label = 'AAPL')
plt.plot(price['NVDA'],'-', color = 'red', label = 'NVDA')
plt.plot(price['MSFT'],'-', color = 'blue', label = 'MSFT')
plt.plot(price['TSLA'],'-', color = 'royalblue', label = 'TSLA')
plt.plot(price['AMZN'],'-', color = 'black', label = 'AMZN')
plt.plot(price['NFLX'],'-', color = 'purple', label = 'NFLX')
plt.plot(price['QCOM'],'-', color = 'pink', label = 'QCOM')
plt.plot(price['SBUX'],'-', color = 'green', label = 'SBUX')
ax.legend(loc = 'best')
ax.set_ylabel("Price", fontsize=12)
ax.set_xlabel("Year", fontsize=12)
ax.set_title("Sample Portfolio", fontsize = 16)

Program with Input/Output:

import getpass, sys

def question_and_answer(prompt):
    print("Question: " + prompt)
    msg = input()
    print("Answer: " + msg)


def question_with_response(prompt):
    print("Question: " + prompt)
    msg = input()
    return msg

questions = 10
correct = 0

print('Hello, ' + getpass.getuser() + " running " + sys.executable)
print("You will be asked " + str(questions) + " questions.")
question_and_answer("Are you ready to take a test?")

rsp = question_with_response("What does “www” stand for in a website browser?")
if rsp == "World Wide Web":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")

rsp = question_with_response("How long is an Olympic swimming pool (in meters)")
if rsp == "50":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")

rsp = question_with_response("What geometric shape is generally used for stop signs?")
if rsp == "Octagon":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Which animal can be seen on the Porsche logo?")
if rsp == "Horse":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Who was the first woman to win a Nobel Prize (in 1903)?")
if rsp == "Marie Curie":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Worship of Krishna is observed by which Religious Faith?")
if rsp == "Hinduism":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("What happned on Sept 11, 2001")
if rsp == "Terrorists attacked the World Trade Centers":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Who invented French fries?")
if rsp == "Belgium":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Whats the game plan?")
if rsp == "I hate my life":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")
    
rsp = question_with_response("Which side of Abundante is better?")
if rsp == "Right side":
    print(rsp + " is correct!")
    correct += 1
else:
    print(rsp + " is incorrect!")

print(getpass.getuser() + " you scored " + str(correct) +"/" + str(questions))

Program with list:

import numpy as np
import pandas as pd
import pandas_datareader.data as web
# Get stock data  
all_data = {ticker: web.DataReader(ticker,'stooq')
           for ticker in ['AAPL', 'NVDA', 'MSFT', 'TSLA', 'AMZN', 'NFLX', 'QCOM', 'SBUX']}
# Extract the 'Adjusted Closing Price'
price = pd.DataFrame({ticker: data['Close']
                     for ticker, data in all_data.items() })
import matplotlib.pyplot as plt
colors = ['gold', 'red', 'blue', 'royalblue', 'black', 'purple', 'pink', 'green']

fig6 = plt.figure(figsize=(6, 6))
axes6 = fig6.add_subplot(1, 1, 1)

# Create the bar chart with custom colors
priceSTD = price.std()
priceSTD.plot(ax=axes6, kind="bar", rot=45, color=colors)

axes6.set_ylabel("STD", fontsize=12)
axes6.set_xlabel("Stocks", fontsize=12)
axes6.set_title("STD of all 8 stocks", fontsize=20)

plt.show()

#fig6.savefig('stocks4.png')

We create and use a list called ‘colors’ which dictates the colors of each of the bars in the graph. Without the list all 8 graphs would be one color, but with it we get that APPL is gold, NVDA is red, and so on and so forth.

priceCORR = price.corr()

fig, ax = plt.subplots(figsize=(10, 6))
priceCORR.plot(kind='bar', stacked=True, ax=ax, color=colors)
ax.set_ylabel("Correlation", fontsize=12)
ax.set_xlabel("Stocks", fontsize=12)
ax.set_title("Correlation between Stocks", fontsize=16)

plt.legend(title='Stocks', loc='upper right')
plt.xticks(rotation=0)  # Rotate x-axis labels if needed
plt.show()

#fig.savefig('stocks5.png')

Since the list ‘color’ is already defined in the previous cell we don’t have to redefine it in order to reuse it.


Program with a dictionary:

# Command: 
personal_data = {'age': 30, 'pets': [0, 1, 2], 'drinks': ['coffee', 'tea']}
personal_data
# Command: 
personal_data.keys()
# Command: 
personal_data.values()
# Command: 
type(personal_data)
# Command: 
personal_data['age']
# Command: 
personal_data['pets']
# Command: 
personal_data['drinks']
# Command: 
personal_data['age'] = 40
personal_data
# Command: 
personal_data['sport'] = 'Chess'
personal_data
# Command: 
del personal_data['sport']
personal_data

Program with iteration

Write a for loop that sums up integers in the list below, and skips None values.

sequence = [None, 2, 3, 6, None, 8, None, 11]
sequence = [None, 12, 832, 2, None, 2, None, 11]
total = 0
for i in range(0,len(sequence)): 
    if type(sequence[i]) == int: 
        total += sequence[i]
total

Write a while-loop that prints a number as long as it is an even number less than 10, but otherwise, prints it is not less than 10. For example, your output should look like this:

0 is even and less than 10
2 is even and less than 10
.
.
.
10 is not less than 10
number = 0

while number <= 10:
    if number % 2 == 0 and number < 10:
        print(f"{number} is even and less than 10")
    else:
        print(f"{number} is not less than 10")
    number += 2


Program with Math

def annuity(rate, C, months, rate_check, month_check): 
    if str(rate_check) == "percent": 
        rate=rate/100
        
    if str(month_check) == 'year': 
        months = months*12
        
    PV = (C/rate)*(1-(1/(1+rate)**months))
    annuity = PV + C
    print("The annuity is: {:.2f}$".format(annuity))
    
def perpetuity(rate, C, rate_check): 
        if str(rate_check) == "percent": 
            rate = rate/100
            
        PV = C/rate
        print("The perpetuity of your deposit is: {:.2f}$".format(PV))
        
def futureValue(rate, PV, months, rate_check, month_check):
        if str(rate_check) == "percent": 
            rate = rate/100
        
        if str(month_check) == "year": 
            months = months*12
        
        FV = float(PV)*(1+float(rate))**float(months)
        print("The future value of your deposit is: {:.2f}$".format(FV))
    
def presentValue(rate, FV, months, rate_check, month_check): 
        if str(rate_check) == "percent": 
            rate = rate/100
        
        if str(month_check) == "year": 
            months = months*12
            
        PV = float(FV)/((1+float(rate))**float(months))
        print("The present value of your deposit is: {:.2f}$".format(PV))
annuity(0.12, 1000, 12, "NA", 'months')
perpetuity(12, 1000, 'percent')
futureValue(0.12, 1000, 12, 'NA', 'months')
presentValue(12, 1000, 1, 'percent', 'year')

Viual Illustration:


Program with a Selection/Condition

class Health: 
    weight = 0
    height = 0
    age = 0
    
    def __init__(measurements, weight, height, gender, age): 
        measurements.weight = weight
        measurements.height = height
        measurements.gender = gender
        measurements.age = age
        
    def bmi(measurements):
        bmi_temp = (measurements.weight/(measurements.height**2))*703
        if bmi_temp < 18.5:
            print(f"Based on your BMI = {bmi_temp:.2f}, you are considered Underweight")
        elif 18.5 < bmi_temp < 24.9:
            print(f"Based on your BMI = {bmi_temp:.2f}, you are considered Normal")
        elif 25 < bmi_temp < 29.9:
            print(f"Based on your BMI = {bmi_temp:.2f}, you are considered Overweight")
        else:    
            print(f"Based on your BMI = {bmi_temp:.2f}, you are considered Obese")
       # return (measurements.weight/(measurements.height**2))*703
    
    def bmr(measurements):
        bmr_temp_M = 66 + (6.3*measurements.weight) + (12.9*measurements.height) - (6.8*measurements.age)
        bmr_temp_F = 655 + (4.3*measurements.weight) + (4.7*measurements.height) - (4.7*measurements.age)
        if measurements.gender == "M":
            print(f"Based on your BMR = {bmr_temp_M:.2f} here are your recommended caloric intakes per activity level:")
            print(f"Sedentary: little or no exercise = {1.2*bmr_temp_M:.2f} Calories")
            print(f"Lightly Active: exercise/sports 1-3 days/week = {1.375*bmr_temp_M:.2f} Calories")
            print(f"Moderately Active: exercise/sports 3-5 days/week = {1.55*bmr_temp_M:.2f} Calories")
            print(f"Very Active: exercise/sports 6-7 days/week = {1.725*bmr_temp_M:.2f} Calories")
            print(f"Extra Active: exercise daily, or physical job = {1.9*bmr_temp_M:.2f} Calories")
        else:
            print(bmr_temp_F)
            print(f"Based on your BMR = {bmr_temp_F:.2f}, here are your recommended caloric intakes per activity level:")
            print(f"Sedentary: little or no exercise = {1.2*bmr_temp_F:.2f} Calories")
            print(f"Lightly Active: exercise/sports 1-3 days/week = {1.375*bmr_temp_F:.2f} Calories")
            print(f"Moderately Active: exercise/sports 3-5 days/week = {1.55*bmr_temp_F:.2f} Calories")
            print(f"Very Active: exercise/sports 6-7 days/week = {1.725*bmr_temp_F:.2f} Calories")
            print(f"Extra Active: exercise daily, or physical job = {1.9*bmr_temp_F:.2f} Calories")
       
vitals = Health(130, 70.8,"F",48)
vitals.bmi()
vitals.bmr()

Program with purpose:

# Function to calculate tax based on income
def calculate_tax(income):
    if income <= 10000:
        tax = income * 0.10
    elif income <= 50000:
        tax = 10000 * 0.10 + (income - 10000) * 0.20
    else:
        tax = 10000 * 0.10 + 40000 * 0.20 + (income - 50000) * 0.30
    return tax

# Input the income
income = float(input("Enter your income: "))

# Calculate the tax
tax = calculate_tax(income)

# Display the tax amount
print(f"Your tax amount is: ${tax:.2f}")


Tester function

First import that math module to take square roots

import math

Create a function that takes a square root of a number. However, there is an error where the code doesn’t know what to do if the number is negative as square roots of negative numbers are not real and it can cause issues.

# Original code with errors
def calculate_square_root(num):
    return math.sqrt(num)

Start debugging the function with try, except, if, and else. Then give the function two numbers. One negative and one positive. The negative will print an error but the positive will print a real number

def test_calculate_square_root(num):
    try:
        if num < 0:
            raise ValueError("Cannot calculate square root for a negative number")
        else:
            print(f"The square root of {num} is: {math.sqrt(num)}")
    except ValueError as e:
        print(f"Error: {e}")


# Test and debug function
test_calculate_square_root(-9)  
test_calculate_square_root(25)   

Correct the function to explain the error

def calculate_square_root(num):
    try:
        if num < 0:
            raise ValueError(f"Cannot calculate square root for {num} as it is a negative number.")
        else:
            print(f"The square root of {num} is: {math.sqrt(num)}")
    except ValueError as e:
        print(f"{e}")
        return None

# Test the final function
calculate_square_root(-9)  
calculate_square_root(25) 
© 2024    •  Powered by Soopr   •  Theme  Moonwalk