Question

THIS IS A PYTHON PROGRAM Part 1 – Stocks Research and Program Setup Find five (5)...

THIS IS A PYTHON PROGRAM

Part 1 – Stocks Research and Program Setup

Find five (5) of your favorite stocks. In your research you will find the daily closing prices of those stocks from February 11, 2019 through February 15, 2019. Write prices out in a table (5 rows by 5 columns).

Part 2 – Python Program

Begin writing a Python program that will do the following:

  • create a 2D list named stocks to store the data for each of your companies.
  • include a 1D list of five (5) strings (named companies) that represent the names of the companies.
  • include a separate function named average that will calculate (and display to the screen) the average closing price for each stock.
  • call the function to execute within the “main” method
0 0
Add a comment Improve this question Transcribed image text
Answer #1

import matplotlib.pyplot as plt   # Import matplotlib

# This line is necessary for the plot to appear in a Jupyter notebook

%matplotlib inline

# Control the default size of figures in this Jupyter notebook

%pylab inline

pylab.rcParams['figure.figsize'] = (15, 9)   # Change the size of plots

apple["Adj Close"].plot(grid = True) # Plot the adjusted closing price of AAPL

Populating the interactive namespace from numpy and matplotlib

100 95 90 85 Feb 2016 Mar 2016 Apr 2016 May 2016 ul 2016 Aug 2016 Sep 2016

A linechart is fine, but there are at least four variables involved for each date (open, high, low, and close), and we would like to have some visual way to see all four variables that does not require plotting four separate lines. Financial data is often plotted with a Japanese candlestick plot, so named because it was first created by 18th century Japanese rice traders. Such a chart can be created with matplotlib, though it requires considerable effort.

I have made a function you are welcome to use to more easily create candlestick charts from pandas data frames, and use it to plot our stock data. (Code is based off this example, and you can read the documentation for the functions involved here.)

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

from matplotlib.dates import DateFormatter, WeekdayLocator,\

    DayLocator, MONDAY

from matplotlib.finance import candlestick_ohlc

def pandas_candlestick_ohlc(dat, stick = "day", otherseries = None):

    """

    :param dat: pandas DataFrame object with datetime64 index, and float columns "Open", "High", "Low", and "Close", likely created via DataReader from "yahoo"

    :param stick: A string or number indicating the period of time covered by a single candlestick. Valid string inputs include "day", "week", "month", and "year", ("day" default), and any numeric input indicates the number of trading days included in a period

    :param otherseries: An iterable that will be coerced into a list, containing the columns of dat that hold other series to be plotted as lines

    This will show a Japanese candlestick plot for stock data stored in dat, also plotting other series if passed.

    """

    mondays = WeekdayLocator(MONDAY)        # major ticks on the mondays

    alldays = DayLocator()              # minor ticks on the days

    dayFormatter = DateFormatter('%d')      # e.g., 12

    # Create a new DataFrame which includes OHLC data for each period specified by stick input

    transdat = dat.loc[:,["Open", "High", "Low", "Close"]]

    if (type(stick) == str):

        if stick == "day":

            plotdat = transdat

            stick = 1 # Used for plotting

        elif stick in ["week", "month", "year"]:

            if stick == "week":

                transdat["week"] = pd.to_datetime(transdat.index).map(lambda x: x.isocalendar()[1]) # Identify weeks

            elif stick == "month":

                transdat["month"] = pd.to_datetime(transdat.index).map(lambda x: x.month) # Identify months

            transdat["year"] = pd.to_datetime(transdat.index).map(lambda x: x.isocalendar()[0]) # Identify years

            grouped = transdat.groupby(list(set(["year",stick]))) # Group by year and other appropriate variable

            plotdat = pd.DataFrame({"Open": [], "High": [], "Low": [], "Close": []}) # Create empty data frame containing what will be plotted

            for name, group in grouped:

                plotdat = plotdat.append(pd.DataFrame({"Open": group.iloc[0,0],

                                            "High": max(group.High),

                                            "Low": min(group.Low),

                                            "Close": group.iloc[-1,3]},

                                           index = [group.index[0]]))

            if stick == "week": stick = 5

            elif stick == "month": stick = 30

            elif stick == "year": stick = 365

    elif (type(stick) == int and stick >= 1):

        transdat["stick"] = [np.floor(i / stick) for i in range(len(transdat.index))]

        grouped = transdat.groupby("stick")

        plotdat = pd.DataFrame({"Open": [], "High": [], "Low": [], "Close": []}) # Create empty data frame containing what will be plotted

        for name, group in grouped:

            plotdat = plotdat.append(pd.DataFrame({"Open": group.iloc[0,0],

                                        "High": max(group.High),

                                        "Low": min(group.Low),

                                        "Close": group.iloc[-1,3]},

                                       index = [group.index[0]]))

    else:

        raise ValueError('Valid inputs to argument "stick" include the strings "day", "week", "month", "year", or a positive integer')

    # Set plot parameters, including the axis object ax used for plotting

    fig, ax = plt.subplots()

    fig.subplots_adjust(bottom=0.2)

    if plotdat.index[-1] - plotdat.index[0] < pd.Timedelta('730 days'):

        weekFormatter = DateFormatter('%b %d') # e.g., Jan 12

        ax.xaxis.set_major_locator(mondays)

        ax.xaxis.set_minor_locator(alldays)

    else:

        weekFormatter = DateFormatter('%b %d, %Y')

    ax.xaxis.set_major_formatter(weekFormatter)

    ax.grid(True)

    # Create the candelstick chart

    candlestick_ohlc(ax, list(zip(list(date2num(plotdat.index.tolist())), plotdat["Open"].tolist(), plotdat["High"].tolist(),

                      plotdat["Low"].tolist(), plotdat["Close"].tolist())),

                      colorup = "black", colordown = "red", width = stick * .4)

    # Plot other series (such as moving averages) as lines

    if otherseries != None:

        if type(otherseries) != list:

            otherseries = [otherseries]

        dat.loc[:,otherseries].plot(ax = ax, lw = 1.3, grid = True)

    ax.xaxis_date()

    ax.autoscale_view()

    plt.setp(plt.gca().get_xticklabels(), rotation=45, horizontalalignment='right')

    plt.show()

pandas_candlestick_ohlc(apple)

Add a comment
Know the answer?
Add Answer to:
THIS IS A PYTHON PROGRAM Part 1 – Stocks Research and Program Setup Find five (5)...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Python Program 5. Write a Python program in a file named validTime.py. Include a function named...

    Python Program 5. Write a Python program in a file named validTime.py. Include a function named string parameter of the form hh:mm: ss in which these are numeric validTime that takes a values and returns True or False indicating whether or not the time is valid. The number of hours, minutes, and seconds must two digits and use a between 0 and 9). The number of hours must be between 0 and 23, the number of minutes and seconds must...

  • Python: Using your favorite text editor, write a program that outputs the string representation of numbers...

    Python: Using your favorite text editor, write a program that outputs the string representation of numbers from 1 to n. But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”. Submit by uploading a .py file Example: n = 15, Return: [ "1", "2", "Fizz", "4", "Buzz", "Fizz", "7", "8", "Fizz", "Buzz", "11", "Fizz", "13", "14", "FizzBuzz"...

  • 5 5 - Parallel Arrays in Python Mind Tap - Cengage Lea x + V A...

    5 5 - Parallel Arrays in Python Mind Tap - Cengage Lea x + V A https//ng.cengage.com/static/nb/ui/evo/index.html?deploymentid=5745322406056533358933471518eISBN=9781337274509&id=586434 145&snapshotld: L x ... € → O 1 » CENGAGE MINDTAP Q Search this course x Parallel Arrays in Python D Parallel Lists Jumpinjive.py + > Terminal + 1 # Jumpin Java.py - This program looks up and prints the names and prices of coffee orders. 2 # Input: Interactive 3 # Output: Name and price of coffee orders or error message if...

  • Having trouble with python! Write a program to build a list of grades, print them out,...

    Having trouble with python! Write a program to build a list of grades, print them out, add to them and count occurrences, and find the amount of the 2-digit grade values. Here are the criteria a) Your program “L6QI initials.py" must start with a commented ID Box AND include a comment that indicates the e of the program. EACH of the five functions in your program must state its purpose in comments too The main function in your program must...

  • Write a Python program that tests the function main and the functions discussed in parts a...

    Write a Python program that tests the function main and the functions discussed in parts a through g. Create the following lists: inStock - 2D list (row size:10, column size:4) alpha - 1D list with 20 elements. beta - 1D list with 20 elements. gamma = [11, 13, 15, 17] delta = [3, 5, 2, 6, 10, 9, 7, 11, 1, 8] a. Write the definition of the function setZero that initializes any one-dimensional list to 0 (alpha and beta)....

  • (I would like this to be in five parts.) Write a program (Python module) that includes...

    (I would like this to be in five parts.) Write a program (Python module) that includes a function named studentrecords. This function must support execution of two loops. The first loop is to query the user whether they wish to enter additional records or not. It must accept responses of either yes or no as input, regardless of the letter-cases used for individual letters in the response. If the response is not recognized ( it isn’t yes or no) it...

  • The Valley Research Inc. is contemplating a research and development (R&D) program encompassing five potential research...

    The Valley Research Inc. is contemplating a research and development (R&D) program encompassing five potential research projects named 1, 2, 3, 4, and 5. All the projects are expected to go on simultaneously. The company is constrained from embarking on all projects by the number of scientists it has and the budget available for R&D projects. The company has 23 scientists and $300,000 (three hundred thousand dollars) budgeted for R&D projects. Furthermore, since projects 2 and 5 require the involvement...

  • Python 3.5 Code Part A: 10 points A tick is a short line that is used...

    Python 3.5 Code Part A: 10 points A tick is a short line that is used to mark off units of distance along a line. Write a function named drawTick() that uses a turtle parameter to draw a single tick of specified length perpendicular to the initial orientation of the turtle. The function drawTick() takes two parameters: 1. a turtle, t, that is used to draw 2. an integer, tickLen, that is the length of the tick When drawTick() is...

  • Python 5. Write a function named grade_components that has one parameter, a dictionary. The keys for...

    Python 5. Write a function named grade_components that has one parameter, a dictionary. The keys for the dictionary are strings and the values are lists of numbers. The function should create a new dictionary where the keys are the same strings as the original dictionary and the values are tuples. The first entry in each tuple should be the weighted average of the non-negative values in the list (where the weight was the number in the 0 position of the...

  • I really need help with this python programming assignment Program Requirements For part 2, i need...

    I really need help with this python programming assignment Program Requirements For part 2, i need the following functions • get floats(): It take a single integer argument and returns a list of floats. where it was something like this def get_floats(n):   lst = []   for i in range(1,n+1):     val = float(input('Enter float '+str(i)+': '))     lst.append(val)   return lst • summer(): This non-void function takes a single list argument, and returns the sum of the list. However, it does not use...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT