0

I am new to Stack Overflow and Python as well. I am struggling to find if there is a way to save a plot or figure. Is this possible using this Pandas package? My plot displays ok and I am Python v 2.7.11. Code below and thanks

#pg 73 from Python in Finance
import numpy as np
import pandas as pd
import pandas.io.data as web



sym1 = 'AAPL'
sym2 = 'FB'

symbol1 = web.DataReader(sym1, data_source='yahoo',start='1/1/2015', end='1/28/2016')
symbol2 = web.DataReader(sym2, data_source='yahoo',start='1/1/2015', end='1/28/2016')
ratio = symbol1; 
ratio['Close'] = symbol1['Close'] / symbol2['Close'];

#symbol1['Close'].plot(grid=True, figsize=(8, 5))
#symbol2['Close'].plot(grid=True, figsize=(8, 5))

ratio['Close'].plot(grid=True, figsize=(8, 5))

ratio['42d'] = np.round(pd.rolling_mean(ratio['Close'], window=42), 2)
ratio['252d'] = np.round(pd.rolling_mean(ratio['Close'], window=252), 2)
ratio[['Close', '42d', '252d']].plot(grid=True, figsize=(8, 5))
Bryan Downing
  • 207
  • 2
  • 14
  • 1
    You can just drag the printout to your desktop. Or use savefig, ie. [one of many similar questions to yours](http://stackoverflow.com/q/16183462/896802). – samthebrand Jan 29 '16 at 04:27

2 Answers2

1

pandas use matplotlib to draw so you can use this

import matplotlib.pyplot as plt

plt.savefig('image.png') # save to png
plt.savefig('image.pdf') # save to pdf

in your code

#pg 73 from Python in Finance
import numpy as np
import pandas as pd
import pandas.io.data as web
import matplotlib.pyplot as plt

sym1 = 'AAPL'
sym2 = 'FB'

symbol1 = web.DataReader(sym1, data_source='yahoo',start='1/1/2015', end='1/28/2016')
symbol2 = web.DataReader(sym2, data_source='yahoo',start='1/1/2015', end='1/28/2016')
ratio = symbol1; 
ratio['Close'] = symbol1['Close'] / symbol2['Close'];

#symbol1['Close'].plot(grid=True, figsize=(8, 5))
#symbol2['Close'].plot(grid=True, figsize=(8, 5))

ratio['Close'].plot(grid=True, figsize=(8, 5))

ratio['42d'] = np.round(pd.rolling_mean(ratio['Close'], window=42), 2)
ratio['252d'] = np.round(pd.rolling_mean(ratio['Close'], window=252), 2)
ratio[['Close', '42d', '252d']].plot(grid=True, figsize=(8, 5))

plt.savefig('foo.png') # save to png
plt.savefig('foo.png') # save to pdf
# plt.show() shows image

EDIT: see: https://stackoverflow.com/a/25588487/1832058

You can use

ax = df.plot() # your plot
fig = ax.get_figure()
fig.savefig('image.png')
Community
  • 1
  • 1
furas
  • 134,197
  • 12
  • 106
  • 148
0
import matplotlib.pyplot as plt

plt.savefig('image.png')
Danila Ganchar
  • 10,266
  • 13
  • 49
  • 75
Rich
  • 1