WebFaction
Community site: login faq

this is my view function

import matplotlib.pyplot as plt, mpld3
import pandas as pd
import math
import copy
import numpy as np
from copy import deepcopy
import mpld3
from mpld3 import plugins
from pylab import *

def draw_fig(stocks, start_date, stop_date):
    print start_date
    print stop_date
    ls_symbols = stocks

    # Start and End date of the charts
    dt_start = dt.datetime.strptime(start_date, '%Y, %m, %d')
    dt_end = dt.datetime.strptime(stop_date, '%Y, %m, %d')

    # We need closing prices so the timestamp should be hours=16.
    dt_timeofday = dt.timedelta(hours=16)

    # Get a list of trading days between the start and the end.
    ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)

    print ldt_timestamps
    # Creating an object of the dataaccess class with Yahoo as the source.
    c_dataobj = da.DataAccess('Yahoo')

    # Keys to be read from the data, it is good to read everything in one go.
    ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']

    # Reading the data, now d_data is a dictionary with the keys above.
    # Timestamps and symbols are the ones that were specified before.
    ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys)
    d_data = dict(zip(ls_keys, ldf_data))

    # Getting the numpy ndarray of close prices.
    na_price = d_data['open'].values

    # Plotting the prices with x-axis=timestamps
    plt.clf()

    plt.legend(ls_symbols)
    plt.ylabel('Adjusted Close')
    plt.xlabel('Date')
    plt.savefig('adjustedclose.pdf', format='pdf')

    # Normalizing the prices to start at 1 and see relative returns
    na_normalized_price = na_price / na_price[0, :]

    # Plotting the prices with x-axis=timestamps
    plt.clf()
    fig, ax = subplots()
    ax.plot(ldt_timestamps, na_normalized_price)

    plt.legend(ls_symbols)
    plt.ylabel('Normalized Close')
    plt.xlabel('Date')
    plt.grid(True)
    plt.savefig('normalized.pdf', format='pdf')

    return mpld3.fig_to_html(fig)

none of the figures get are plotted but the data is ok

asked 07 Sep '15, 13:03

samcace
1114
accept rate: 0%

edited 07 Sep '15, 16:37

seanf
12.2k41836


I don't have any way to test this for you, but I see the following error in your app's error log (in ~/logs/user): matplotlib.use() must be called *before* pylab, matplotlib.pyplot, or matplotlib.backends is imported for the first time.

You're not calling matplotlib.use() in the code that you've provided, so that may be the issue.

permanent link

answered 07 Sep '15, 16:52

seanf
12.2k41836
accept rate: 37%

Is there a URL we can visit to test this?

(08 Sep '15, 21:33) seanf

yes the url is

samcace.webfactional.com/viewstocks

username: TestUser password: test123

(09 Sep '15, 07:50) samcace

On the page just tick UNGA radio button, this is the only dataset I have uploaded and scanned also using python command line interpreter these commands get me a plot

import QSTK.qstkutil.qsdateutil as du
import QSTK.qstkutil.tsutil as tsu
import QSTK.qstkutil.DataAccess as da

import datetime as dt
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt, mpld3
import pandas as pd

import mpld3
from mpld3 import plugins
from pylab import *

ls_symbols = ["UNGA"]
dt_start = dt.datetime(2014, 1, 1)
dt_end = dt.datetime(2014, 12, 31)
dt_timeofday = dt.timedelta(hours=16)
ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)

c_dataobj = da.DataAccess('Yahoo')
ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']
ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys)
d_data = dict(zip(ls_keys, ldf_data))

na_price = d_data['open'].values
na_normalized_price = na_price / na_price[0, :]
plt.clf()
plt.plot(ldt_timestamps, na_normalized_price)
plt.legend(ls_symbols)
plt.ylabel('Adjusted Close')
plt.xlabel('Date')
plt.savefig('unganorm.png')
(09 Sep '15, 07:56) samcace

draw_fig() is clearly being called but seems to not be returning any data. Your python interactive interpreter example doesn't seem to demonstrate the functionality of mpld3.fig_to_html using your fig figure. Have you tested that part as well?

One thing I would try would be inserting:

import code; code.interact(local=dict(globals(), **locals()))

directly before:

return mpld3.fig_to_html(fig)

and then run your application in the foreground. When this line is executed, it should drop you into a python interpreter within the context of your application. Then you can run mpld3.fig_to_html(fig) manually and ensure that it's producing the output that you expect (before returning it from draw_fig())

(09 Sep '15, 10:27) ryans ♦♦

i added the mpld3.fig_to_html() functionality to the python interactive interpreter and i got a plot inside the interpreter, it was coordinates of html, when saving the plot using mpld3.save_html(fig) igot a plot on disk, but the browser functionality seems still not to work. Here is my code edit

import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt, mpld3

import mpld3
from mpld3 import fig_to_html, plugins
from pylab import *

ls_symbols = ["UNGA"]
dt_start = dt.datetime(2014, 1, 1)
dt_end = dt.datetime(2014, 12, 31)
dt_timeofday = dt.timedelta(hours=16)
ldt_timestamps = du.getNYSEdays(dt_start, dt_end, dt_timeofday)
c_dataobj = da.DataAccess('Yahoo')
ls_keys = ['open', 'high', 'low', 'close', 'volume', 'actual_close']
ldf_data = c_dataobj.get_data(ldt_timestamps, ls_symbols, ls_keys)
d_data = dict(zip(ls_keys, ldf_data))
na_price = d_data['open'].values
na_normalized_price = na_price / na_price[0, :]
fig = plt.figure()
fid = plt.plot(ldt_timestamps, na_normalized_price)
plt.legend(ls_symbols)
plt.ylabel('Adjusted Close')
plt.xlabel('Date')
fig_to_html(fig)
I also tried adding the suggested
import code; code.interact(local=dict(globals(), **locals()))

but i did not get dropped into an interpreter please explain what you meant by foreground

(11 Sep '15, 09:23) samcace

By "foreground", I mean to run the entire application with python from the command line (not just extracted draw_fig() code). This way, it's your full application that's running, but it's not running via mod_wsgi during this test. When run in the foreground like this, code.interact() should produce an interactive interpreter when the draw_fig method is triggered by a browser request. You can then jump in and interactively examine the output of the methods you're calling to determine why fig_to_html isn't producing output.

(12 Sep '15, 10:30) ryans ♦♦
showing 5 of 6 show 1 more comments
Your answer
toggle preview

Follow this question

By Email:

Once you sign in you will be able to subscribe for any updates here

By RSS:

Answers

Answers and Comments

Markdown Basics

  • *italic* or _italic_
  • **bold** or __bold__
  • link:[text](http://url.com/ "title")
  • image?![alt text](/path/img.jpg "title")
  • numbered list: 1. Foo 2. Bar
  • to add a line break simply add two spaces to where you would like the new line to be.
  • basic HTML tags are also supported

Question tags:

×44
×7
×1
×1
×1

question asked: 07 Sep '15, 13:03

question was seen: 4,441 times

last updated: 14 Sep '15, 17:10

WEBFACTION
REACH US
SUPPORT
AFFILIATE PROGRAM
LEGAL
© COPYRIGHT 2003-2019 SWARMA LIMITED - WEBFACTION IS A SERVICE OF SWARMA LIMITED
REGISTERED IN ENGLAND AND WALES 5729350 - VAT REGISTRATION NUMBER 877397162
5TH FLOOR, THE OLD VINYL FACTORY, HAYES, UB3 1HA, UNITED KINGDOM