Advertisement
OreganoHauch

Plot stock market prices

Mar 30th, 2020
148
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.04 KB | None | 0 0
  1. %matplotlib inline
  2. import matplotlib.pyplot as plt
  3. import numpy as np
  4. import matplotlib.dates as mdates
  5.  
  6. def bytespdate2num(fmt, encoding="utf-8"):
  7. strconverter = mdates.strpdate2num(fmt)
  8. def bytesconverter(b):
  9. s = b.decode(encoding)
  10. return strconverter(s)
  11. return bytesconverter
  12.  
  13.  
  14.  
  15. def graph_data(name_of_file):
  16. date_data = []
  17. stock_data_interim = []
  18. file = open(name_of_file, "r")
  19. file_list = list(file)
  20.  
  21. # date
  22. for element in file_list:
  23. if " \"2020" in element:
  24. date_string = element[9:28]
  25. date_data.append(date_string)
  26.  
  27. # stock prices/volumes
  28. for element in file_list:
  29. for x in ["1. open", "2. high", "4. close", "5. volume"]:
  30. if "\"" + x in element:
  31. end_of_line = element.rfind("\"")
  32. stock_data_interim.append(element[24:end_of_line])
  33. # separately coding "3. low", because it is somehow formatted differently in the text file
  34. for x in ["3. low"]:
  35. if "\"" + x in element:
  36. end_of_line = element.rfind("\"")
  37. stock_data_interim.append(element[23:end_of_line])
  38.  
  39. # remove parantheses and spaces
  40. stock_data_output = []
  41. for element in stock_data_interim:
  42. if "\"" or " " in element:
  43. new_string = element.replace("\"", "").replace(" ", "")
  44. stock_data_output.append(new_string)
  45. else:
  46. stock_data_output.append(element)
  47.  
  48.  
  49. file.close()
  50.  
  51. date, closep, highp, loewp, openp, volume = np.loadtxt(stock_data_output,
  52. delimiter=",",
  53. unpack=True,
  54. converters={0: bytespdate2num("%Y-%m-%d")})
  55.  
  56.  
  57.  
  58. plt.plot_date(date, closep)
  59.  
  60. plt.xlabel("Date")
  61. plt.ylabel("Price")
  62. plt.title("Interesting Graph\nCheck it out!")
  63. plt.legend()
  64. plt.show()
  65.  
  66.  
  67. graph_data("Boring stock market price.txt")
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement