~ubuntu-branches/debian/sid/xlsxwriter/sid

« back to all changes in this revision

Viewing changes to examples/pandas_chart_stock.py

  • Committer: Package Import Robot
  • Author(s): Zygmunt Krynicki
  • Date: 2015-07-21 14:01:46 UTC
  • mfrom: (1.1.3)
  • Revision ID: package-import@ubuntu.com-20150721140146-17zfcjwpuyfoe4nm
Tags: 0.7.3-1
New upstream release 

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
##############################################################################
 
2
#
 
3
# An example of converting a Pandas dataframe with stock data taken from the
 
4
# web to an xlsx file with a line chart using Pandas and XlsxWriter.
 
5
#
 
6
# Copyright 2013-2015, John McNamara, jmcnamara@cpan.org
 
7
#
 
8
 
 
9
import pandas as pd
 
10
import pandas.io.data as web
 
11
 
 
12
# Create some sample data to plot.
 
13
all_data = {}
 
14
for ticker in ['AAPL', 'GOOGL', 'IBM', 'YHOO', 'MSFT']:
 
15
    all_data[ticker] = web.get_data_yahoo(ticker, '5/1/2014', '5/1/2015')
 
16
 
 
17
# Create a Pandas dataframe from the data.
 
18
df = pd.DataFrame({tic: data['Adj Close']
 
19
                   for tic, data in all_data.items()})
 
20
 
 
21
# Create a Pandas Excel writer using XlsxWriter as the engine.
 
22
sheet_name = 'Sheet1'
 
23
writer     = pd.ExcelWriter('pandas_chart_stock.xlsx', engine='xlsxwriter')
 
24
df.to_excel(writer, sheet_name=sheet_name)
 
25
 
 
26
# Access the XlsxWriter workbook and worksheet objects from the dataframe.
 
27
workbook  = writer.book
 
28
worksheet = writer.sheets[sheet_name]
 
29
 
 
30
# Adjust the width of the first column to make the date values clearer.
 
31
worksheet.set_column('A:A', 20)
 
32
 
 
33
# Create a chart object.
 
34
chart = workbook.add_chart({'type': 'line'})
 
35
 
 
36
# Configure the series of the chart from the dataframe data.
 
37
max_row = len(df) + 1
 
38
for i in range(len(['AAPL', 'GOOGL'])):
 
39
    col = i + 1
 
40
    chart.add_series({
 
41
        'name':       ['Sheet1', 0, col],
 
42
        'categories': ['Sheet1', 2, 0, max_row, 0],
 
43
        'values':     ['Sheet1', 2, col, max_row, col],
 
44
        'line':       {'width': 1.00},
 
45
    })
 
46
 
 
47
# Configure the chart axes.
 
48
chart.set_x_axis({'name': 'Date', 'date_axis': True})
 
49
chart.set_y_axis({'name': 'Price', 'major_gridlines': {'visible': False}})
 
50
 
 
51
# Position the legend at the top of the chart.
 
52
chart.set_legend({'position': 'top'})
 
53
 
 
54
# Insert the chart into the worksheet.
 
55
worksheet.insert_chart('H2', chart)
 
56
 
 
57
# Close the Pandas Excel writer and output the Excel file.
 
58
writer.save()