Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

TRAINING

MATERIAL
About the doc
These exercises are to make sure that you have enough familiarity with
programming and, in particular, Python programming. This is not meant to
be a stand-alone introduction to computer programming. Rather, it’s a way
for someone with almost no previous exposure to programming to get some
practice and to learn the basics of Python. The goal of the exercises is to give
you practice with Python concepts and to help diagnose your level of
programming ability. Some of the problem sets are much longer than the
earlier ones, because we need the concepts in the earlier sections before we
can really write many interesting programs. So, don’t be misled by the short
length of the early problem sets. The presented solutions are just a sample
solution. There are many different ways to arrive to the same result.

1
]\

About the doc 1

Exercises 7
Question: Time Counter 7
Question: The biggest number I 7
Question: The biggest number II 7
Question: If and not If 8
Question: Product & sum 8
Question: Pandas I 8
Question: Pandas II 9
Question: Pandas III 9
Question: Pandas IV 10
Question: Pandas V 11
Question: Pandas VI 11
Question: Pandas VII 13
Question: Pandas VIII 13
Question: Pandas IX 14
Question: Pandas X 14
Question: Pandas XI 15
Question: Pandas XII 16
Question: Pandas XIII 16
Question: Pandas XIV 17
Question: Pandas XV 18
Question: The Descent 20
Question: Onboarding 20
Question: Weather 20
Question: Power of the light 21
Question: Time Series I 23
Question: Time Series II 23
Question: Time Series III 23
Question: Time Series IV 24
Question: Time Series V 24
Question: Time Series VI 24
Question: Time Series VII 24
Question: Time Series VIII 24

2
]\

Question: Time Series IX 25


Question: Time Series X 25
Question: Time Series XI 25
Question: Time Series XII 25
Question: Time Series XIII 25
Question: Time Series XIV 26
Question: Time Series XV 26
Question: Time Series XVI 26
Question: Time Series XVII 26
Question: Time Series XVIII 26
Question: Time Series XIX 26
Question: Time Series XX 27
Question: Time Series XXI 27
Question: Time Series XXII 27
Question: Time Series XXIII 27
Question: Time Series XXIV 27
Question: Time Series XXV 28
Question: Time Series XXVI 28
Question: Time Series XXVII 28
Question: Time Series XXVIII 28
Question: Time Series XXIX 28
Question: Time Series XXX 29
Question: Time Series XXXI 29
Question: Time Series XXXII 29
Question: Plotting I 29
Question: Plotting II 30
Question: Plotting III 30
Question: Plotting IV 31
Question: Plotting V 31
Question: Plotting VI 31
Question: Plotting VII 31
Question: Plotting VIII 31
Question: Plotting IX 32
Question: Plotting X 32
Question: Plotting XI 32
Question: Plotting XII 32
Question: Plotting XIII 32

3
]\

Question: Plotting XIV 33


Question: Plotting XV 33
Question: Plotting XVI 34
Question: Plotting XVII 34
Question: Plotting XVIII 35
Question: Plotting XIX 35

Solutions 36
Question: Time Counter 36
Question: The biggest number I 36
Question: The biggest number II 37
Question: If and not If (A): 37
Question: If and not If (B): 37
Question: Product & Sum: 37
Question: Pandas I 38
Question: Pandas II 38
Question: Pandas III 38
Question: Pandas IV 39
Question: Pandas V 39
Question: Pandas VI 40
Question: Pandas VII 40
Question: Pandas VIII 41
Question: Pandas IX 41
Question: Pandas X 42
Question: Pandas XI 42
Question: Pandas XII 42
Question: Pandas XIII 43
Question: Pandas XIV 43
Question: Pandas XV 44
Question: The Descent 45
Question: Onboarding 45
Question: Weather 45
Question: Power of the light 46
Question: Time Series I 47
Question: Time Series II 48
Question: Time Series III 48
Question: Time Series IV 48

4
]\

Question: Time Series V 49


Question: Time Series VI 49
Question: Time Series VII 50
Question: Time Series VIII 50
Question: Time Series IX 50
Question: Time Series X 51
Question: Time Series XI 51
Question: Time Series XII 51
Question: Time Series XIII 52
Question: Time Series XIV 52
Question: Time Series XV 52
Question: Time Series XVI 53
Question: Time Series XVII 53
Question: Time Series XVIII 53
Question: Time Series XIX 54
Question: Time Series XX 54
Question: Time Series XXI 55
Question: Time Series XXII 55
Question: Time Series XXIII 55
Question: Time Series XXIV 56
Question: Time Series XXV 56
Question: Time Series XXVI 57
Question: Time Series XXVII 57
Question: Time Series XXVIII 58
Question: Time Series XXIX 58
Question: Time Series XXX 59
Question: Time Series XXXI 59
Question: Time Series XXXII 59
Question: Plotting II 60
Question: Plotting II 60
Question: Plotting III 61
Question: Plotting IV 61
Question: Plotting V 62
Question: Plotting VI 62
Question: Plotting VII 63
Question: Plotting VIII 63
Question: Plotting IX 64

5
]\

Question: Plotting X 64
Question: Plotting XI 65
Question: Plotting XII 65
Question: Plotting XIII 66
Question: Plotting XIV 66
Question: Plotting XV 67
Question: Plotting XVI 68
Question: Plotting XVII 68
Question: Plotting XVIII 69
Question: Plotting XIX 69

6
]\

Exercises
Question: Time Counter
Write a program that asks for a number of seconds and retrieves how many
days, hours, minutes and seconds that number has.
Example:
Number of seconds: 345 678
Output: days: 4 hours: 0 minutes: 1 seconds: 18

Question: The biggest number I


Write a program in Python that reads 3 consecutive number (comma
separated), and it displays which of them is the biggest one.
Example:
Number of seconds: 6, 19, -3
Output: The biggest one is 19

Question: The biggest number II


Write a program in Python that reads 3 consecutive number (comma
separated), and it displays which of them is the biggest one. You must use 2
function and a single if clause condition.
Example:
Number of seconds: 6, 19, -3
Output: The biggest one is 19

7
]\

Question: If and not If


Write a function to ckeck if the input is equal to 5:
A. Using an If-else condition;
B. Without if-else condition.
Example:
Input: 6
Output: False

Question: Product & sum


Calculate the multiplication and sum of two numbers. Given two integer
numbers return their product only if the product is equal to or lower than
1000, else return their sum.
Example:
number1 = 20
number2 = 30
Output: The result is 600

Question: Pandas I
Write a Pandas program to get the powers of an array values element-wise.
Sample data: {'X':[78,85,96,80,86], 'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]}
Expected Output:
XYZ
0 78 84 86
1 85 94 97
2 96 89 96

8
]\

3 80 83 72
4 86 86 83

Question: Pandas II
Write a Pandas program to create and display a DataFrame from a specified
dictionary data which has the index labels. Sample Python dictionary data
and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Expected Output:
attempts name qualify score
a 1 Anastasia yes 12.5
b 3 Dima no 9.0
.... i 2 Kevin no 8.0
j 1 Jonas yes 19.0

Question: Pandas III


Write a Pandas program to display a summary of the basic information about
a specified DataFrame and its data. Sample Python dictionary data and list
labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],

9
]\

'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],


'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Expected Output:
Summary of the basic information about this DataFrame and its data:
<class 'pandas.core.frame.DataFrame'>
Index: 10 entries, a to j
Data columns (total 4 columns):
.... dtypes: float64(1), int64(1), object(2)
memory usage: 400.0+ bytes
None

Question: Pandas IV
Write a Pandas program to select the rows where the score is missing, i.e. is
NaN. Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Expected Output:
Rows where score is missing:
attempts name qualify score
d 3 James no NaN
h 1 Laura no NaN

10
]\

Question: Pandas V
Write a Pandas program to select the rows where number of attempts in the
examination is less than 2 and score greater than 15. Sample Python
dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Expected Output:
Number of attempts in the examination is less than 2 and score greater than
15 :
name score attempts qualify
j Jonas 19.0 1 yes

Question: Pandas VI
Write a Pandas program to sort the DataFrame first by 'name' in descending
order, then by 'score' in ascending order. Sample Python dictionary data and
list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

11
]\

Values for each column will be:


name : "Suresh", score: 15.5, attempts: 1, qualify: "yes", label: "k"
Expected Output:
Orginal rows:
name score attempts qualify
a Anastasia 12.5 1 yes
b Dima 9.0 3 no
c Katherine 16.5 2 yes
d James NaN 3 no
e Emily 9.0 2 no
f Michael 20.0 3 yes
g Matthew 14.5 1 yes
h Laura NaN 1 no
i Kevin 8.0 2 no
j Jonas 19.0 1 yes
Sort the data frame first by 'name' in descending order, then by 'score' in
ascending order:
name score attempts qualify
a Anastasia 12.5 1 yes
b Dima 9.0 3 no
c Katherine 16.5 2 yes
d James NaN 3 no
e Emily 9.0 2 no
f Michael 20.0 3 yes
g Matthew 14.5 1 yes
h Laura NaN 1 no
i Kevin 8.0 2 no
j Jonas 19.0 1 yes

12
]\

Question: Pandas VII


Write a Pandas program to replace the 'qualify' column contains the values
'yes' and 'no' with True and False. Sample Python dictionary data and list
labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Expected Output:
Replace the 'qualify' column contains the values 'yes' and 'no' with T
rue and False:
attempts name qualify score
a 1 Anastasia True 12.5
b 3 Dima False 9.0
......
i 2 Kevin False 8.0
j 1 Jonas True 19.0

Question: Pandas VIII


Write a Pandas program to insert a new column in existing DataFrame.
Sample Python dictionary data and list labels:
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],

13
]\

'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],


'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Expected Output:
New DataFrame after inserting the 'color' column
attempts name qualify score color
a 1 Anastasia yes 12.5 Red
b 3 Dima no 9.0 Blue
.......
i 2 Kevin no 8.0 Green
j 1 Jonas yes 19.0 Red

Question: Pandas IX
Write a Pandas program to iterate over rows in a DataFrame. Sample Python
dictionary data and list labels:
exam_data = [{'name':'Anastasia', 'score':12.5}, {'name':'Dima','score':9},
{'name':'Katherine','score':16.5}]
Expected Output:
Anastasia 12.5
Dima 9.0
Katherine 16.5

Question: Pandas X
Write a Pandas program to change the order of a DataFrame columns.
Sample data:
Original DataFrame

14
]\

col1 col2 col3


0147
1458
2369
3470
4581
After altering col1 and col3
col3 col2 col1
0741
1854
2963
3074
4185

Question: Pandas XI
Write a Pandas program to write a DataFrame to CSV file using tab separator.
Sample data:
Original DataFrame
col1 col2 col3
0147
1458
2369
3470
4581
Data from new_file.csv file:
col1\tcol2\tcol3
0 1\t4\t7
1 4\t5\t8

15
]\

2 3\t6\t9
3 4\t7\t0
4 5\t8\t1

Question: Pandas XII


Write a Pandas program to count city wise number of people from a given of
data set (city, name of the person).
Sample data:
My_info = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael',
'Matthew', 'Laura', 'Kevin', 'Jonas'],
'city': ['California', 'Los Angeles', 'California', 'California', 'California', 'Los Angeles',
'Los Angeles', 'Georgia', 'Georgia', 'Los Angeles']}
Output:
city Number of people
0 California 4
1 Georgia 2
2 Los Angeles 4

Question: Pandas XIII


Write a Pandas program to replace all the NaN values with Zero's in a column
of a dataframe.
Sample data:
Original DataFrame
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0

16
]\

2 2 Katherine yes 16.5


3 3 James no NaN
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no NaN
8 2 Kevin no 8.0
9 1 Jonas yes 19.0
New DataFrame replacing all NaN with 0:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0
2 2 Katherine yes 16.5
3 3 James no 0.0
4 2 Emily no 9.0
5 3 Michael yes 20.0
6 1 Matthew yes 14.5
7 1 Laura no 0.0
8 2 Kevin no 8.0
9 1 Jonas yes 19.0

Question: Pandas XIV


Write a Pandas program to sort a given DataFrame by two or more columns.
Sample data:
Original DataFrame:
attempts name qualify score
0 1 Anastasia yes 12.5
1 3 Dima no 9.0

17
]\

........
8 2 Kevin no 8.0
9 1 Jonas yes 19.0

Sort the above DataFrame on attempts, name:


attempts name qualify score
0 1 Anastasia yes 12.5
9 1 Jonas yes 19.0
7 1 Laura no NaN
6 1 Matthew yes 14.5
4 2 Emily no 9.0
2 2 Katherine yes 16.5
8 2 Kevin no 8.0
1 3 Dima no 9.0
3 3 James no NaN
5 3 Michael yes 20.0

Question: Pandas XV
Write a Pandas program to merge datasets and check uniqueness.
Sample Output:
Original DataFrame:
Name Date_Of_Birth Age
0 Alberto Franco 17/05/2002 18.5
1 Gino Mcneill 16/02/1999 21.2
2 Ryan Parkes 25/09/1998 22.5
3 Eesha Hinton 11/05/2002 22.0
4 Syed Wharton 15/09/1997 23.0

18
]\

New DataFrames:
Name Date_Of_Birth Age
2 Ryan Parkes 25/09/1998 22.5
3 Eesha Hinton 11/05/2002 22.0
4 Syed Wharton 15/09/1997 23.0
Name Date_Of_Birth Age
0 Alberto Franco 17/05/2002 18.5
1 Gino Mcneill 16/02/1999 21.2
3 Eesha Hinton 11/05/2002 22.0
4 Syed Wharton 15/09/1997 23.0

"one_to_one": check if merge keys are unique in both left and right
datasets:"
Name Date_Of_Birth Age
0 Eesha Hinton 11/05/2002 22.0
1 Syed Wharton 15/09/1997 23.0

"one_to_many" or "1:m": check if merge keys are unique in left dataset:


Name Date_Of_Birth Age
0 Eesha Hinton 11/05/2002 22.0
1 Syed Wharton 15/09/1997 23.0

"any_to_one" or "m:1": check if merge keys are unique in right dataset:


Name Date_Of_Birth Age
0 Eesha Hinton 11/05/2002 22.0
1 Syed Wharton 15/09/1997 23.0

19
]\

Question: The Descent


Write a program to find the highest mountains before your airplan collides
with one of them. For that, identify the highest mountain on your path.
Within an infinite loop, read the heights of the mountains from the standard
input and print to the standard output the index of the mountain to avoid.
Input:
one integer mountainH per line. Each represents the height of one mountain
given in the order of their index (from 0 to 7).
Output:
A single line with one integer for the index of which mountain to avoid.

Question: Onboarding
Your program must destroy the enemy ships by shooting the closest enemy
on each turn. On each start of turn (within the infinite game loop), you obtain
information on the two closest enemies:
● enemy1 and dist1: the name and the distance to enemy 1.
● enemy2 and dist2: the name and the distance to enemy 2.
Before your turn is over (end of the loop), output the value of either enemy1 or
enemy2 to shoot the closest enemy.

Question: Weather
In this exercise, you have to analyze records of temperature to find the closest
to zero. Write a program that prints the temperature closest to 0 among input
data. If two numbers are equally close to zero, positive integer has to be
considered closest to zero (for instance, if the temperatures are -5 and 5, then

20
]\

display 5). Your program must read the data from the standard input and
write the result on the standard output.

Input:
Line 1: N, the number of temperatures to analyze
Line 2: A string with the N temperatures expressed as integers ranging from
-273 to 5526
Output:
Display 0 (zero) if no temperatures are provided. Otherwise, display the
temperature closest to 0.

Question: Power of the light


Write a program that helps a Roomba vacuum cleaner to reach the light.
Roomba moves on a map which is 40 wide by 18 high. Note that the
coordinates (X and Y) start at the top left! This means the most top left cell has
the coordinates "X=0,Y=0" and the most bottom right one has the coordinates
"X=39,Y=17". Once the program starts you are given:
● the variable lightX: the X position of the light of power that Roomba
must reach.
● the variable lightY: the Y position of the light of power that Roomba
must reach.

21
]\

● the variable initialTX: the starting X position of Roomba .


● the variable initialTY: the starting Y position of Roomba .
At the end of the game turn, you must output the direction in which you
want Roomba to go among:

Input:
The program must first read the initialization data from the standard input,
then, in an infinite loop, provides on the standard output the instructions to
move Roomba.
Initialization input
Line 1: 4 integers lightX lightY initialTX initialTY. (lightX, lightY) indicates the
position of the light. (initialTX, initialTY) indicates the initial position of
Roomba.
Input for a game round
Line 1: the number of remaining moves for Roomba to reach the light of
power: remainingTurns. You can ignore this data but you must read it.
Output for a game round
A single line providing the move to be made: N NE E SE S SW W NW
Constraints
● 0 ≤ lightX < 40
● 0 ≤ lightY < 18

22
]\

● 0 ≤ initialTX < 40
● 0 ≤ initialTY < 18

Question: Time Series I


Write a Pandas program to create
a) Datetime object for Jan 15 2012.
b) Specific date and time of 9:20 pm.
c) Local date and time.
d) A date without time.
e) Current date.
f) Time from a datetime.
g) Current local time.

Question: Time Series II


Write a Pandas program to create
a) a specific date using timestamp.
b) date and time using timestamp.
c) a time adds in the current local date using timestamp.
d) current date and time using timestamp.

Question: Time Series III


Write a Pandas program to create a date from a given year, month, day and
another date from a given string formats.

23
]\

Question: Time Series IV


Write a Pandas program to print the day after and before a specified date.
Also print the days between two given dates.

Question: Time Series V


Write a Pandas program to create a time-series with two index labels and
random values. Also print the type of the index.

Question: Time Series VI


Write a Pandas program to create a time-series from a given list of dates as
strings.

Question: Time Series VII


Write a Pandas program to create a time series object that has time indexed
data. Also select the dates of same year and select the dates between certain
dates.

Question: Time Series VIII


Write a Pandas program to create a date range using a startpoint date and a
number of periods.

24
]\

Question: Time Series IX


Write a Pandas program to create a whole month of dates in daily
frequencies. Also find the maximum, minimum timestamp and indexs.

Question: Time Series X


Write a Pandas program to create a time series using three months
frequency.

Question: Time Series XI


Write a Pandas program to create a sequence of durations increasing by an
hour.

Question: Time Series XII


Write a Pandas program to convert year and day of year into a single datetime
column of a dataframe.

Question: Time Series XIII


Write a Pandas program to create a series of Timestamps from a DataFrame
of integer or string columns. Also create a series of Timestamps using
specified columns.

25
]\

Question: Time Series XIV


Write a Pandas program to check if a day is a business day (weekday) or not.

Question: Time Series XV


Write a Pandas program to get a time series with the last working days of
each month of a specific year.

Question: Time Series XVI


Write a Pandas program to create a time series combining hour and minute.

Question: Time Series XVII


Write a Pandas program to convert unix/epoch time to a regular time stamp
in UTC. Also convert the said timestamp in to a given time zone.

Question: Time Series XVIII


Write a Pandas program to create a time series object with a time zone.

Question: Time Series XIX


Write a Pandas program to remove the time zone information from a Time
series data.

26
]\

Question: Time Series XX


Write a Pandas program to subtract two timestamps of same time zone or
different time zone.

Question: Time Series XXI


Write a Pandas program to calculate all Thursdays between two given days.

Question: Time Series XXII


Write a Pandas program to find the all the business quarterly begin and end
dates of a specified year.

Question: Time Series XXIII


Write a Pandas program to generate sequences of fixed-frequency dates and
time spans intervals.

Question: Time Series XXIV


Write a Pandas program to generate time series combining day and intraday
offsets intervals.

27
]\

Question: Time Series XXV


Write a Pandas program to extract the day name from a specified date. Add 2
days and 1 business day with the specified date.

Question: Time Series XXVI


Write a Pandas program to convert integer or float epoch times to Timestamp
and DatetimeIndex.

Question: Time Series XXVII


Write a Pandas program to calculate one, two, three business day(s) from a
specified date. Also find the next business month end from a specific date.

Question: Time Series XXVIII


Write a Pandas program to create a period index represent all monthly
boundaries of a given year. Also print start and end time for each period
object in the said index.

Question: Time Series XXIX


Write a Pandas program create a series with a PeriodIndex which represents
all the calendar month periods in 2029 and 2031. Also print the values for all
periods in 2030.

28
]\

Note: PeriodIndex is an immutable ndarray holding ordinal values indicating


regular periods in time such as particular years, quarters, months, etc.

Question: Time Series XXX


Write a Pandas program to generate holidays between two dates using the
US federal holiday calendar.

Question: Time Series XXXI


Write a Pandas program to create a monthly time period and display the list
of names in the current local scope.

Question: Time Series XXXII


Write a Pandas program to create a yearly time period from a specified year
and display the properties of this period

Question: Plotting I
Dataset:
Historical stock prices of Alphabet Inc. (GOOG)
Time Period: April 01, 2020 - October 01, 2020
Download here:
https://drive.google.com/file/d/1hKxLZLTx2rWPM1zid6cTAXs-33OgoTBj/view?us
p=sharing
Description of Dataset:

29
]\

● Date: It gives the date of which stocks details are given.


● Open: It gives the opening price of stock on that date.
● High: It gives the highest price to which the stock ascened on that day.
● Low: It gives the highest price to which the stock plummeted on that
day.
● Close: It gives the closing price of stock on that date.
● Volume: It gives the amount of stock traded on that date.
● Adjusted Close: An adjusted closing price is a stock’s closing price on
any given day of trading that has been amended to include any
distributions and corporate actions that occurred at any time prior to
the next day’s open.

Write a Pandas program to create a line plot of the historical stock prices of
Alphabet Inc. between two specific dates.

Question: Plotting II
Write a Pandas program to create a line plot of the opening, closing stock
prices of Alphabet Inc. between two specific dates.

Question: Plotting III


Write a Pandas program to create a bar plot of the trading volume of
Alphabet Inc. stock between two specific dates.

30
]\

Question: Plotting IV
Write a Pandas program to create a bar plot of opening, closing stock prices
of Alphabet Inc. between two specific dates.

Question: Plotting V
Write a Pandas program to create a stacked bar plot of opening, closing stock
prices of Alphabet Inc. between two specific dates.

Question: Plotting VI
Write a Pandas program to create a horizontal stacked bar plot of opening,
closing stock prices of Alphabet Inc. between two specific dates.

Question: Plotting VII


Write a Pandas program to create a histograms plot of opening, closing, high,
low stock prices of Alphabet Inc. between two specific dates.

Question: Plotting VIII


Write a Pandas program to create a stacked histograms plot of opening,
closing, high, low stock prices of Alphabet Inc. between two specific dates.

31
]\

Question: Plotting IX
Write a Pandas program to draw a horizontal and cumulative histograms plot
of opening stock prices of Alphabet Inc. between two specific dates.

Question: Plotting X
Write a Pandas program to create a stacked histograms plot of opening,
closing, high, low stock prices of Alphabet Inc. between two specific dates
with more bins.

Question: Plotting XI
Write a Pandas program to create a stacked histograms plot with more bins
of opening, closing, high, low stock prices of Alphabet Inc. between two
specific dates.

Question: Plotting XII


Write a Pandas program to create a plot of stock price and trading volume of
Alphabet Inc. between two specific dates.

Question: Plotting XIII


Write a Pandas program to create a plot of Open, High, Low, Close, Adjusted
Closing prices and Volume of Alphabet Inc. between two specific dates.

32
]\

Question: Plotting XIV


Write a Pandas program to create a plot of adjusted closing prices, thirty days
and forty days simple moving average of Alphabet Inc. between two specific
dates.

Question: Plotting XV
Write a Pandas program to create a plot of adjusted closing prices, 30 days
simple moving average and exponential moving average of Alphabet Inc.
between two specific dates.

What is Simple Moving Average (SMA)?


In financial applications a simple moving average (SMA) is the unweighted
mean of the previous n data. However, in science and engineering, the mean
is normally taken from an equal number of data on either side of a central
value. This ensures that variations in the mean are aligned with the variations
in the data rather than being shifted in time.

What Is an Exponential Moving Average (EMA)?


From investopedia.com - An exponential moving average (EMA) is a type of
moving average (MA) that places a greater weight and significance on the
most recent data points. The exponential moving average is also referred to as
the exponentially weighted moving average. An exponentially weighted
moving average reacts more significantly to recent price changes than a
simple moving average (SMA), which applies an equal weight to all
observations in the period.

33
]\

Question: Plotting XVI


Write a Pandas program to create a scatter plot of the trading volume/stock
prices of Alphabet Inc. stock between two specific dates.

Question: Plotting XVII


Write a Pandas program to create a plot to visualize daily percentage returns
of Alphabet Inc. stock price between two specific dates.

34
]\

Question: Plotting XVIII


Write a Pandas program to plot the volatility over a period of time of Alphabet
Inc. stock price between two specific dates.

Question: Plotting XIX


Write a Pandas program to create a histogram to visualize daily return
distribution of Alphabet Inc. stock price between two specific dates.

35
]\

Solutions
Question: Time Counter

secs = eval(input('Write a number of seconds\n'))

days = secs // (24 * 60 * 60)


secs = secs % (24 * 60 * 60)

hours = secs // (60 * 60)


secs = secs % (60 * 60)

minutes = secs // 60
secs = secs % 60

print('days: ', days, ' hours: ', hours, ' minutes: ', minutes, '
seconds: ', secs)

Question: The biggest number I

print('Please write 3 comma separated number')


N1, n2, n3 = eval(input('? '))

if n1 > n2:
if n2 > n3:
biggest = n1

else:
if n1 > n3:
biggest = n2
else:
biggest = n3

print('The biggest one is: ', biggest)

36
]\

Question: The biggest number II

print('Please write 3 comma separated number')


n1, n2, n3 = eval(input('? '))

def max_of_two( x, y ):
if x > y:
return x
return y

def max_of_three( x, y, z):


return max_of_two( x, max_of_two( y, z ))

print('The biggest one is: ', max_of_three(n1, n2, n3))

Question: If and not If (A):

def equal_five(input_number):
if input_number == 5:
return True
else:
return False

Question: If and not If (B):

def belowFive(input_number):
return input_number == 5

Question: Product & Sum:

def multiplication_or_sum(num1, num2):


# calculate product of two number
product = num1 * num2
# check if product is less then 1000
if product <= 1000:
return product

37
]\

else:
# product is greater than 1000 calculate sum
return num1 + num2

# first condition
result = multiplication_or_sum(20, 30)
print("The result is", result)

Question: Pandas I

import pandas as pd
df = pd.DataFrame({'X':[78,85,96,80,86],
'Y':[84,94,89,83,86],'Z':[86,97,96,72,83]});
print(df)

Question: Pandas II

import pandas as pd
import numpy as np

exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',


'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(exam_data , index=labels)
print(df)

Question: Pandas III

import pandas as pd
import numpy as np

exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',

38
]\

'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],


'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(exam_data , index=labels)
print("Summary of the basic information about this DataFrame and its
data:")
print(df.info())

Question: Pandas IV

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

df = pd.DataFrame(exam_data , index=labels)
print("Rows where score is missing:")
print(df[df['score'].isnull()])

Question: Pandas V

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',

39
]\

'no', 'no', 'yes']}


labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("Number of attempts in the examination is less than 2 and score
greater than 15 :")
print(df[(df['attempts'] < 2) & (df['score'] > 15)])

Question: Pandas VI

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("Orginal rows:")
print(df)
df.sort_values(by=['name', 'score'], ascending=[False, True])
print("Sort the data frame first by 'name' in descending order, then
by 'score' in ascending order:")
print(df)

Question: Pandas VII

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

40
]\

df = pd.DataFrame(exam_data , index=labels)
print("Original rows:")
print(df)
print("\nReplace the 'qualify' column contains the values 'yes' and
'no' with True and False:")
df['qualify'] = df['qualify'].map({'yes': True, 'no': False})
print(df)

Question: Pandas VIII

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
df = pd.DataFrame(exam_data , index=labels)
print("Original rows:")
print(df)
color =
['Red','Blue','Orange','Red','White','White','Blue','Green','Green','
Red']
df['color'] = color
print("\nNew DataFrame after inserting the 'color' column")
print(df)

Question: Pandas IX

import pandas as pd
import numpy as np
exam_data = [{'name':'Anastasia', 'score':12.5},
{'name':'Dima','score':9}, {'name':'Katherine','score':16.5}]

41
]\

df = pd.DataFrame(exam_data)
for index, row in df.iterrows():
print(row['name'], row['score'])

Question: Pandas X

import pandas as pd
import numpy as np
d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8,
9, 0, 1]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
print('After altering col1 and col3')
df = df[['col3', 'col2', 'col1']]
print(df)

Question: Pandas XI

import pandas as pd
import numpy as np
d = {'col1': [1, 4, 3, 4, 5], 'col2': [4, 5, 6, 7, 8], 'col3': [7, 8,
9, 0, 1]}
df = pd.DataFrame(data=d)
print("Original DataFrame")
print(df)
print('Data from new_file.csv file:')
df.to_csv('new_file.csv', sep='\t', index=False)
new_df = pd.read_csv('new_file.csv')
print(new_df)

Question: Pandas XII

import pandas as pd
df1 = pd.DataFrame({'name': ['Anastasia', 'Dima', 'Katherine',
'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'city': ['California', 'Los Angeles', 'California', 'California',

42
]\

'California', 'Los Angeles', 'Los Angeles', 'Georgia', 'Georgia',


'Los Angeles']})
g1 = df1.groupby(["city"]).size().reset_index(name='Number of
people')
print(g1)

Question: Pandas XIII

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
df = pd.DataFrame(exam_data)
print("Original DataFrame")
print(df)
df = df.fillna(0)
print("\nNew DataFrame replacing all NaN with 0:")
print(df)

Question: Pandas XIV

import pandas as pd
import numpy as np
exam_data = {'name': ['Anastasia', 'Dima', 'Katherine', 'James',
'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes',
'no', 'no', 'yes']}
df = pd.DataFrame(exam_data)
print("Original DataFrame:")

43
]\

print(df)
print("\nSort the above DataFrame on attempts, name:")
df = df.sort_values(['attempts', 'name'], ascending=[True, True])
print(df)

Question: Pandas XV

import pandas as pd
df = pd.DataFrame({
'Name': ['Alberto Franco','Gino Mcneill','Ryan Parkes', 'Eesha
Hinton', 'Syed Wharton'],
'Date_Of_Birth ':
['17/05/2002','16/02/1999','25/09/1998','11/05/2002','15/09/1997'],
'Age': [18.5, 21.2, 22.5, 22, 23]
})
print("Original DataFrame:")
print(df)
df1 = df.copy(deep = True)
df = df.drop([0, 1])
df1 = df1.drop([2])
print("\nNew DataFrames:")
print(df)
print(df1)
print('\n"one_to_one": check if merge keys are unique in both left
and right datasets:"')
df_one_to_one = pd.merge(df, df1, validate = "one_to_one")
print(df_one_to_one)
print('\n"one_to_many" or "1:m": check if merge keys are unique in
left dataset:')
df_one_to_many = pd.merge(df, df1, validate = "one_to_many")
print(df_one_to_many)
print('"many_to_one" or "m:1": check if merge keys are unique in
right dataset:')
df_many_to_one = pd.merge(df, df1, validate = "many_to_one")
print(df_many_to_one)

44
]\

Question: The Descent

# game loop
while True:
amax = 0
imax = 0

for i in range(8):
# represents the height of one mountain.
mountain_h = int(input())

if mountain_h > amax:


amax = mountain_h
imax = i

print(imax)

Question: Onboarding

#Game loop.
while True:
#Read inputs.
enemy1 = input()
dist1 = int(input())

enemy2 = input()
dist2 = int(input())

#Output nearest enemy.


print(enemy1 if dist1 < dist2 else enemy2)

Question: Weather

#Read inputs.
N = int(input())

45
]\

inputs = input().split()

#If there are no temperatures provided, output 0.


if N <= 0:
print(0)
quit()

closestToZero = 5526

for i in range(N):
T = int(inputs[i])

#Find the closest to zero.


if abs(T) < abs(closestToZero):
closestToZero = T
#Find the positive number that is closest to zero instead of the
negative number (see 5 and -5).
elif abs(T) == abs(closestToZero):
closestToZero = max(closestToZero, T)

#Print output.
print(closestToZero)

Question: Power of the light

#Read inputs.
inputs = input().split(' ')

lightX = int(inputs[0])
lightY = int(inputs[1])
initialTX = int(inputs[2])
initialTY = int(inputs[3])

while True:
remainingTurns = int(input())

move = ''

46
]\

#Vertical movement.
if lightY > initialTY:
initialTY += 1
move += 'S'
elif lightY < initialTY:
initialTY -= 1
move += 'N'

#Horizontal movement.
if lightX > initialTX:
initialTX += 1
move += 'E'
elif lightX < initialTX:
initialTX -= 1
move += 'W'

#Output next move.


print(move)

Question: Time Series I

import datetime
from datetime import datetime
print("Datetime object for Jan 11 2012:")
print(datetime(2012, 1, 11))
print("\nSpecific date and time of 9:20 pm")
print(datetime(2011, 1, 11, 21, 20))
print("\nLocal date and time:")
print(datetime.now())
print("\nA date without time: ")
print(datetime.date(datetime(2012, 5, 22)))
print("\nCurrent date:")
print(datetime.now().date())
print("\nTime from a datetime:")
print(datetime.time(datetime(2012, 12, 15, 18, 12)))
print("\nCurrent local time:")

47
]\

print(datetime.now().time())

Question: Time Series II

import pandas as pd
#from datetime import datetime
print("\nA specific date using timestamp:")
print(pd.Timestamp('2016-11-10'))
print("\nDate and time using timestamp:")
print(pd.Timestamp('2012-05-03 11:30'))
print("\nA time adds in the current local date using timestamp:")
print(pd.Timestamp('11:30'))
print("\nCurrent date and time using timestamp:")
print(pd.Timestamp("now"))

Question: Time Series III

from datetime import datetime


date1 = datetime(year=2020, month=12, day=25)
print("Date from a given year, month, day:")
print(date1)
from dateutil import parser
date2 = parser.parse("1st of January, 2021")
print("\nDate from a given string formats:")
print(date2)

Question: Time Series IV

import pandas as pd
import datetime

48
]\

from datetime import datetime, date


today = datetime(2012, 10, 30)
print("Current date:", today)
tomorrow = today + pd.Timedelta(days=1)
print("Tomorrow:", tomorrow)
yesterday = today - pd.Timedelta(days=1)
print("Yesterday:", yesterday)
date1 = datetime(2016, 8, 2)
date2 = datetime(2016, 7, 19)
print("\nDifference between two dates: ",(date1 - date2))

Question: Time Series V

import pandas as pd
import numpy as np
import datetime
from datetime import datetime, date
dates = [datetime(2011, 9, 1), datetime(2011, 9, 2)]
print("Time-series with two index labels:")
time_series = pd.Series(np.random.randn(2), dates)
print(time_series)
print("\nType of the index:")
print(type(time_series.index))

Question: Time Series VI

import pandas as pd
import numpy as np
import datetime
from datetime import datetime, date
dates = ['2014-08-01','2014-08-02','2014-08-03','2014-08-04']
time_series = pd.Series(np.random.randn(4), dates)
print(time_series)

49
]\

Question: Time Series VII

import pandas as pd
index = pd.DatetimeIndex(['2011-09-02', '2012-08-04',
'2015-09-03', '2010-08-04',
'2015-03-03', '2011-08-04',
'2015-04-03', '2012-08-04'])

s_dates = pd.Series([0, 1, 2, 3, 4, 5, 6, 7], index=index)

print("Time series object with indexed data:")


print(s_dates)
print("\nDates of same year:")
print(s_dates['2015'])
print("\nDates between 2012-01-01 and 2012-12-31")
print(s_dates['2012-01-01':'2012-12-31'])

Question: Time Series VIII

import pandas as pd
date_range = pd.date_range('2020-01-01', periods=45)
print("Date range of perods 45:")
print(date_range)

Question: Time Series IX

import pandas as pd
dates = pd.Series(pd.date_range('2020-12-01',periods=31, freq='D'))
print("Month of December 2020:")
print(dates)
dates = pd.Series(pd.date_range('2020-12-01',periods=31, freq='D'))

50
]\

print("\nMaximum date: ", dates.max())


print("Minimum date: ", dates.min())
print("Maximum index: ", dates.idxmax())
print("Minimum index: ", dates.idxmin())

Question: Time Series X

import pandas as pd
time_series = pd.date_range('1/1/2021', periods = 36, freq='3M')
print("Time series using three months frequency:")
print(time_series)

Question: Time Series XI

import pandas as pd
date_range = pd.timedelta_range(0, periods=49, freq='H')
print("Hourly range of perods 49:")
print(date_range)

Question: Time Series XII

import pandas as pd
data = {\
"year": [2002, 2003, 2015, 2018],
"day_of_the_year": [250, 365, 1, 140]
}
df = pd.DataFrame(data)
print("Original DataFrame:")
print(df)
df["combined"] = df["year"]*1000 + df["day_of_the_year"]
df["date"] = pd.to_datetime(df["combined"], format = "%Y%j")
print("\nNew DataFrame:")

51
]\

print(df)

Question: Time Series XIII

import pandas as pd
df = pd.DataFrame({'year': [2018, 2019, 2020],
'month': [2, 3, 4],
'day': [4, 5, 6],
'hour': [2, 3, 4]})
print("Original dataframe:")
print(df)
result = pd.to_datetime(df)
print("\nSeries of Timestamps from the said dataframe:")
print(result)
print("\nSeries of Timestamps using specified columns:")
print(pd.to_datetime(df[['year', 'month', 'day']]))

Question: Time Series XIV

import pandas as pd
def is_business_day(date):
return bool(len(pd.bdate_range(date, date)))
print("Check busines day or not?")
print('2020-12-01: ',is_business_day('2020-12-01'))
print('2020-12-06: ',is_business_day('2020-12-06'))
print('2020-12-07: ',is_business_day('2020-12-07'))
print('2020-12-08: ',is_business_day('2020-12-08'))

Question: Time Series XV

import pandas as pd
s = pd.date_range('2021-01-01', periods=12, freq='BM')

52
]\

df = pd.DataFrame(s, columns=['Date'])
print('last working days of each month of a specific year:')
print(df)

Question: Time Series XVI

import pandas as pd
result = pd.timedelta_range(0, periods=30, freq="1H20T")
print("For a frequency of 1 hours 20 minutes, here we have combined
the hour (H) and minute (T):\n")
print(result)

Question: Time Series XVII

import pandas as pd
epoch_t = 1621132355
time_stamp = pd.to_datetime(epoch_t, unit='s')
# UTC (Coordinated Universal Time) is one of the well-known names of
UTC+0 time zone which is 0h.
# By default, time series objects of pandas do not have an assigned
time zone.
print("Regular time stamp in UTC:")
print(time_stamp)
print("\nConvert the said timestamp in to US/Pacific:")
print(time_stamp.tz_localize('UTC').tz_convert('US/Pacific'))
print("\nConvert the said timestamp in to Europe/Berlin:")
print(time_stamp.tz_localize('UTC').tz_convert('Europe/Berlin'))

Question: Time Series XVIII

import pandas as pd
print("Timezone: Europe/Berlin:")

53
]\

print("Using pytz:")
date_pytz = pd.Timestamp('2019-01-01', tz = 'Europe/Berlin')
print(date_pytz.tz)
print("Using dateutil:")
date_util = pd.Timestamp('2019-01-01', tz = 'dateutil/Europe/Berlin')
print(date_util.tz)
print("\nUS/Pacific:")
print("Using pytz:")
date_pytz = pd.Timestamp('2019-01-01', tz = 'US/Pacific')
print(date_pytz.tz)
print("Using dateutil:")
date_util = pd.Timestamp('2019-01-01', tz = 'dateutil/US/Pacific')
print(date_util.tz)

Question: Time Series XIX

import pandas as pd
date1 = pd.Timestamp('2019-01-01', tz='Europe/Berlin')
date2 = pd.Timestamp('2019-01-01', tz='US/Pacific')
date3 = pd.Timestamp('2019-01-01', tz='US/Eastern')
print("Time series data with time zone:")
print(date1)
print(date2)
print(date3)
print("\nTime series data without time zone:")
print(date1.tz_localize(None))
print(date2.tz_localize(None))
print(date3.tz_localize(None))

Question: Time Series XX

import pandas as pd
print("Subtract two timestamps of same time zone:")
date1 = pd.Timestamp('2019-03-01 12:00', tz='US/Eastern')

54
]\

date2 = pd.Timestamp('2019-04-01 07:00', tz='US/Eastern')


print("Difference: ", (date2-date1))
print("\nSubtract two timestamps of different time zone:")
date1 = pd.Timestamp('2019-03-01 12:00', tz='US/Eastern')
date2 = pd.Timestamp('2019-03-01 07:00', tz='US/Pacific')
# Remove the time zone and do the subtraction
print("Difference: ", (date1.tz_localize(None) -
date2.tz_localize(None)))

Question: Time Series XXI

import pandas as pd
thursdays = pd.date_range('2020-01-01',
'2020-12-31', freq="W-THU")
print("All Thursdays between 2020-01-01 and 2020-12-31:\n")
print(thursdays.values)

Question: Time Series XXII

import pandas as pd
q_start_dates = pd.date_range('2020-01-01', '2020-12-31',
freq='BQS-JUN')
q_end_dates = pd.date_range('2020-01-01', '2020-12-31',
freq='BQ-JUN')
print("All the business quarterly begin dates of 2020:")
print(q_start_dates.values)
print("\nAll the business quarterly end dates of 2020:")
print(q_end_dates.values)

Question: Time Series XXIII

import pandas as pd

55
]\

print("Sequences of fixed-frequency dates and time spans (1 H):\n")


r1 = pd.date_range('2030-01-01', periods=10, freq='H')
print(r1)
print("\nSequences of fixed-frequency dates and time spans (3 H):\n")
r2 = pd.date_range('2030-01-01', periods=10, freq='3H')
print(r2)

Question: Time Series XXIV

import pandas as pd
dateset1 = pd.date_range('2029-01-01 00:00:00', periods=20,
freq='3h10min')
print("Time series with frequency 3h10min:")
print(dateset1)
dateset2 = pd.date_range('2029-01-01 00:00:00', periods=20,
freq='1D10min20U')
print("\nTime series with frequency 1 day 10 minutes and 20
microseconds:")
print(dateset2)

Question: Time Series XXV

import pandas as pd
newday = pd.Timestamp('2020-02-07')
print("First date:")
print(newday)
print("\nThe day name of the said date:")
print(newday.day_name())
print("\nAdd 2 days with the said date:")
newday1 = newday + pd.Timedelta('2 day')
print(newday1.day_name())
print("\nNext business day:")
nbday = newday + pd.offsets.BDay()
print(nbday.day_name())

56
]\

Question: Time Series XXVI

import pandas as pd
dates1 = pd.to_datetime([1329806505, 129806505, 1249892905,
1249979305, 1250065705], unit='s')
print("Convert integer or float epoch times to Timestamp and
DatetimeIndex upto second:")
print(dates1)
print("\nConvert integer or float epoch times to Timestamp and
DatetimeIndex upto milisecond:")
dates2 = pd.to_datetime([1249720105100, 1249720105200, 1249720105300,
1249720105400, 1249720105500], unit='ms')
print(dates2)

Question: Time Series XXVII

import pandas as pd
from pandas.tseries.offsets import *
import datetime
from datetime import datetime, date
dt = datetime(2020, 1, 4)
print("Specified date:")
print(dt)
print("\nOne business day from the said date:")
obday = dt + BusinessDay()
print(obday)
print("\nTwo business days from the said date:")
tbday = dt + 2 * BusinessDay()
print(tbday)
print("\nThree business days from the said date:")
thbday = dt + 3 * BusinessDay()
print(thbday)
print("\nNext business month end from the said date:")

57
]\

nbday = dt + BMonthEnd()
print(nbday)

Question: Time Series XXVIII

import pandas as pd
import datetime
from datetime import datetime, date
sdt = datetime(2020, 1, 1)
edt = datetime(2020, 12, 31)
dateset = pd.period_range(sdt, edt, freq='M')
print("All monthly boundaries of a given year:")
print(dateset)
print("\nStart and end time for each period object in the said
index:")
for d in dateset:
print ("{0} {1}".format(d.start_time, d.end_time))

Question: Time Series XXIX

import pandas as pd
import numpy as np
pi = pd.Series(np.random.randn(36),
pd.period_range('1/1/2029',
'12/31/2031', freq='M'))
print("PeriodIndex which represents all the calendar month periods in
2029 and 2030:")
print(pi)
print("\nValues for all periods in 2030:")
print(pi['2030'])

58
]\

Question: Time Series XXX

import pandas as pd
from pandas.tseries.holiday import *
sdt = datetime(2021, 1, 1)
edt = datetime(2030, 12, 31)
print("Holidays between 2021-01-01 and 2030-12-31 using the US
federal holiday calendar.")
cal = USFederalHolidayCalendar()
for dt in cal.holidays(start=sdt, end=edt):
print (dt)

Question: Time Series XXXI

import pandas as pd
mtp = pd.Period('2021-11','M')
print("Monthly time perid: ",mtp)
print("\nList of names in the current local scope:")
print(dir(mtp))

Question: Time Series XXXII

import pandas as pd
ytp = pd.Period('2020','A-DEC')
print("Yearly time perid:",ytp)
print("\nAll the properties of the said period:")
print(dir(ytp))

59
]\

Question: Plotting II

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-09-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1.set_index('Date')
plt.figure(figsize=(5,5))
plt.suptitle('Stock prices of Alphabet Inc.,\n01-04-2020 to
30-09-2020', \
fontsize=18, color='black')
plt.xlabel("Date",fontsize=16, color='black')
plt.ylabel("$ price", fontsize=16, color='black')

df2['Close'].plot(color='green');
plt.show()

Question: Plotting II

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-09-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df2 = df.loc[new_df]
plt.figure(figsize=(10,10))
df2.plot(x='Date', y=['Open', 'Close']);
plt.suptitle('Opening/Closing stock prices of Alphabet Inc.,\n
01-04-2020 to 30-09-2020', fontsize=12, color='black')

60
]\

plt.xlabel("Date",fontsize=12, color='black')
plt.ylabel("$ price", fontsize=12, color='black')
plt.show()

Question: Plotting III

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1.set_index('Date')
plt.figure(figsize=(6,6))
plt.suptitle('Trading Volume of Alphabet Inc. stock,\n01-04-2020 to
30-04-2020', fontsize=16, color='black')
plt.xlabel("Date",fontsize=12, color='black')
plt.ylabel("Trading Volume", fontsize=12, color='black')
df2['Volume'].plot(kind='bar');
plt.show()

Question: Plotting IV

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Date', 'Open', 'Close']]

61
]\

df3 = df2.set_index('Date')
plt.figure(figsize=(20,20))
df3.plot(kind='bar');
plt.suptitle('Opening/Closing stock prices Alphabet Inc.,\n01-04-2020
to 30-04-2020', fontsize=12, color='black')
plt.show()

Question: Plotting V

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Date', 'Open', 'Close']]
df3 = df2.set_index('Date')
plt.figure(figsize=(20,20))
df3.plot.bar(stacked=True);
plt.suptitle('Opening/Closing stock prices Alphabet Inc.,\n01-04-2020
to 30-04-2020', fontsize=12, color='black')
plt.show()

Question: Plotting VI

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)

62
]\

df1 = df.loc[new_df]
df2 = df1[['Date', 'Open', 'Close']]
df3 = df2.set_index('Date')
plt.figure(figsize=(20,20))
df3.plot.barh(stacked=True)
plt.suptitle('Opening/Closing stock prices Alphabet Inc.,\n01-04-2020
to 30-04-2020', fontsize=12, color='black')
plt.show()

Question: Plotting VII

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Open','Close','High','Low']]
#df3 = df2.set_index('Date')
plt.figure(figsize=(25,25))
df2.plot.hist(alpha=0.5)
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet
Inc.,\n From 01-04-2020 to 30-09-2020', fontsize=12, color='blue')
plt.show()

Question: Plotting VIII

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]

63
]\

df2 = df1[['Open','Close','High','Low']]
plt.figure(figsize=(25,25))
df2.plot.hist(stacked=True, bins=20)
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet
Inc.,\n From 01-04-2020 to 30-09-2020', fontsize=12, color='blue')
plt.show()

Question: Plotting IX

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-4-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Open']]
plt.figure(figsize=(15,15))
df2.plot.hist(orientation='horizontal', cumulative=True)
plt.suptitle('Opening stock prices of Alphabet Inc.,\n From
01-04-2020 to 30-04-2020', fontsize=12, color='black')
plt.show()

Question: Plotting X

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Open','Close','High','Low']]
plt.figure(figsize=(25,25))
df2.plot.hist(stacked=True, bins=200)

64
]\

plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet


Inc.,\n From 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.show()

Question: Plotting XI

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Open','Close','High','Low']]
plt.figure(figsize=(30,30))
df2.hist();
plt.suptitle('Opening/Closing/High/Low stock prices of Alphabet Inc.,
From 01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.show()

Question: Plotting XII

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
stock_data = df1.set_index('Date')
top_plt = plt.subplot2grid((5,4), (0, 0), rowspan=3, colspan=4)
top_plt.plot(stock_data.index, stock_data["Close"])
plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to
30-09-2020]')
bottom_plt = plt.subplot2grid((5,4), (3,0), rowspan=1, colspan=4)

65
]\

bottom_plt.bar(stock_data.index, stock_data['Volume'])
plt.title('\nAlphabet Inc. Trading Volume', y=-0.60)
plt.gcf().set_size_inches(12,8)

Question: Plotting XIII

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
stock_data = df1.set_index('Date')
stock_data.plot(subplots = True, figsize = (8, 8));
plt.legend(loc = 'best')
plt.suptitle('Open,High,Low,Close,Adj Close prices & Volume of
Alphabet Inc., From 01-04-2020 to 30-09-2020', fontsize=12,
color='black')
plt.show()

Question: Plotting XIV

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
stock_data = df1.set_index('Date')
close_px = stock_data['Adj Close']
stock_data['SMA_30_days'] =
stock_data.iloc[:,4].rolling(window=30).mean()
stock_data['SMA_40_days'] =

66
]\

stock_data.iloc[:,4].rolling(window=40).mean()
plt.figure(figsize=[10,8])
plt.grid(True)
plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to
30-09-2020]\n',fontsize=18, color='black')
plt.plot(stock_data['Adj Close'],label='Adjusted Closing Price',
color='black')
plt.plot(stock_data['SMA_30_days'],label='30 days simple moving
average', color='red')
plt.plot(stock_data['SMA_40_days'],label='40 days simple moving
average', color='green')
plt.legend(loc=2)
plt.show()

Question: Plotting XV

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
stock_data = df1.set_index('Date')
close_px = stock_data['Adj Close']
stock_data['SMA_30_days'] =
stock_data.iloc[:,4].rolling(window=30).mean()
stock_data['EMA_20_days'] =
stock_data.iloc[:,4].ewm(span=20,adjust=False).mean()
plt.figure(figsize=[15,10])
plt.grid(True)
plt.title('Historical stock prices of Alphabet Inc. [01-04-2020 to
30-09-2020]\n',fontsize=18, color='black')
plt.plot(stock_data['Adj Close'],label='Adjusted Closing Price',
color='black')
plt.plot(stock_data['SMA_30_days'],label='30 days Simple moving

67
]\

average', color='red')
plt.plot(stock_data['EMA_20_days'],label='20 days Exponential moving
average', color='green')
plt.legend(loc=2)
plt.show()

Question: Plotting XVI

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1.set_index('Date')
x= ['Close']; y = ['Volume']
plt.figure(figsize=[15,10])
df2.plot.scatter(x, y, s=50);
plt.grid(True)
plt.title('Trading Volume/Price of Alphabet Inc. stock,\n01-04-2020
to 30-09-2020', fontsize=14, color='black')
plt.xlabel("Stock Price",fontsize=12, color='black')
plt.ylabel("Trading Volume", fontsize=12, color='black')
plt.show()

Question: Plotting XVII

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]

68
]\

df2 = df1[['Date', 'Adj Close']]


df3 = df2.set_index('Date')
daily_changes = df3.pct_change(periods=1)
daily_changes['Adj
Close'].plot(figsize=(10,7),legend=True,linestyle='--',marker='o')
plt.suptitle('Daily % return of Alphabet Inc. stock
price,\n01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.grid(True)
plt.show()

Question: Plotting XVIII

import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Date', 'Close']]
df3 = df2.set_index('Date')
data_filled = df3.asfreq('D', method='ffill')
data_returns = data_filled.pct_change()
data_std = data_returns.rolling(window=30, min_periods=30).std()
plt.figure(figsize=(20,20))
data_std.plot();
plt.suptitle('Volatility over a period of time of Alphabet Inc.
stock price,\n01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.grid(True)
plt.show()

Question: Plotting XIX

import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

69
]\

df = pd.read_csv("alphabet_stock_data.csv")
start_date = pd.to_datetime('2020-4-1')
end_date = pd.to_datetime('2020-9-30')
df['Date'] = pd.to_datetime(df['Date'])
new_df = (df['Date']>= start_date) & (df['Date']<= end_date)
df1 = df.loc[new_df]
df2 = df1[['Date', 'Adj Close']]
df3 = df2.set_index('Date')
daily_changes = df3.pct_change(periods=1)
sns.distplot(daily_changes['Adj
Close'].dropna(),bins=100,color='purple')
plt.suptitle('Daily % return of Alphabet Inc. stock
price,\n01-04-2020 to 30-09-2020', fontsize=12, color='black')
plt.grid(True)
plt.show()

70

You might also like