Click here to Skip to main content
15,891,184 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the historic NSE data of 2016 and 2017 in a CSV file. Now I want a graph which plots my opening values vs the timestamp present in the csv file. If the timestamp has been sorted by me, what is the code to sort the opening values too such that they too are sorted in accordance with the time stamp?

The following is the code. I need the code to sort my opening values (openf) in accordance with the date.

What I have tried:

import csv
import codecs
import numpy as np
import matplotlib.pyplot as plt
# reading csv file
filepath = "nse_data.csv"
with codecs.open(filepath,"r") as csvfile:
    reader = csv.reader(csvfile)
    data = [row for row in reader]
    
x = np.shape(data)
i = 2
j = 0
openf = []
close = []
high = []
low = []
date = []
openf.append(data[1][2])
close.append(data[1][5])
high.append(data[1][3])
low.append(data[1][4])
date.append(data[1][10])
while(i<x[0]):
    if(data[i][j] == data[1][0]):
        openf.append(data[i][2])
        date.append(data[i][10])
        close.append(data[i][5])
        high.append(data[i][3])
        low.append(data[i][4])
        print("Analysed ",data[i][j])
        print("Analysed ",data[i][10])
    i = i + 1
print(openf)
#print(close)
#print(high)
#print(low)
print(len(openf))
print(len(date))
date.sort() #date has been sorted in increasing order
print(date)
plt.plot(date,openf, label = "Opening Values")
plt.xlabel('date')
plt.ylabel('openf')
plt.title('Graph of opening Values')
plt.legend()
plt.show()
Posted
Updated 9-Jun-18 22:06pm

1 solution

Rather than creating separate arrays for openf, close, high, low and date, you could create a class that has these properties:
class Row:

	def __init__(self, openf, close, high, low, date):
		self.openf = openf
		self.close = close
		self.high = high
		self.low = low
		self.date = date

Create an array of this class:
rows = []

Fill it:
while(i<x[0]):
	if(data[i][j] == data[1][0]):
		rows.append(Row(data[i][2], data[i][5], data[i][3], data[i][4], data[i][10]))
		print("Analysed ",data[i][j])
		print("Analysed ",data[i][10])
	i = i + 1

And sort it:
rows.sort(key=lambda x: x.date)

If your plotting code requires separate arrays and you want to keep it that way, you can then create the arrays like so:
date = []
openf = []
for row in rows:
	date.append(row.date)
	openf.append(row.openf)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900