1
import pandas as pd
import matplotlib.pyplot as plt

> importing csv files
january = pd.read_csv('divident_month/january.csv')
april = pd.read_csv('divident_month/april.csv')
july = pd.read_csv('divident_month/july.csv')
october = pd.read_csv('divident_month/october.csv')

> substracting column 'Open' to column close
jangain = january['Open']-january['Close']
aprgain = april['Open']-april['Close']
julgain = july['Open']-july['Close']
octgain = october['Open']-october['Close']

>plotting  
medium=[jangain, aprgain, julgain, octgain]
plt.plot(medium)
plt.show()

## jan = plt.plot(jangain, label='january')
## apr =plt.plot(aprgain, label='april')
## jul =plt.plot(julgain, label='july')
## oct =plt.plot(octgain, label='october')
## plt.legend()

how can i plot multiple items into a graph without repeating myself as i have in the ##. i have multiple files with repetitive code for diferent months(their grouped in different files for Before div months,div months, and after div months ).

i have tried grouping them into a list(medium) and passing the list into plt.plot(medium) but that doesn't seem to work.

i have also given the plots names(such as Jan, apr...)because im importing them into a different file for q1,q2,q3,q4 analysis(just in case that info confusing)

this is me trying to do finance with python btw

1 Answers1

0

You can do this:

import os
import pandas as pd, collections as co, matplotlib.pyplot as plt

the_dir = 'divident_month/'
months = co.OrderedDict() # use if order of csv files is important 

# iterate over files in directory
for a_file in sorted(os.listdir(the_dir)):
    if os.path.splitext(a_file)[-1] == '.csv':
        # add DataFrame entries to dictionary 
        months[a_file.rstrip('.csv')] = pd.read_csv(os.path.join(the_dir,a_file))

# perform gain calculation (k: dictionary `k`ey, v: dictionary `v`alue)
for k,v in months.items():
    months[k] = v['Open'] - v['Close']

# get an axes handle from matplotlib so you can re-use it
fig,ax = plt.subplots()

# plot without manual repetition of plot command
for k,v in months.items():
    ax = v.plot(ax=ax,label=k) 

# add title and show plot
plt.gcf().suptitle('Gain')
plt.show()
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
  • what does collections do ? i have 4 csv files imported and they have 5 columns with 20 rows of data. column named 'open' and 'close' has float values, I'm doing this for each csv file and plotting it into one single graph with 4 different lines of data for each month – anthony pizarro May 05 '20 at 02:44
  • Collections has a container called an ordered dictionary. It is used in case the order of the csv files is important. If it's not important you can use a regular dictionary. – mechanical_meat May 05 '20 at 02:46
  • I added some comments explaining each part. – mechanical_meat May 05 '20 at 02:51