Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions examples/finance.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""
Some examples playing around with yahoo finance data
"""
# foo

from datetime import datetime

Expand Down
3 changes: 2 additions & 1 deletion pandas/core/panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,8 @@ def f(self, other, axis='items'):
return self._combine(other, op, axis=axis)

f.__name__ = name
f.__doc__ = f.__doc__ % str(op)
if __debug__:
f.__doc__ = f.__doc__ % str(op)

return f

Expand Down
41 changes: 41 additions & 0 deletions pandas/io/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import numpy as np
import datetime as dt
import urllib
import urllib2

from zipfile import ZipFile
from StringIO import StringIO
Expand Down Expand Up @@ -65,6 +66,46 @@ def _sanitize_dates(start, end):
end = dt.datetime.today()
return start, end

def get_quote_yahoo(symbols):
"""
Get current yahoo quote

Returns a DataFrame
"""
if not isinstance(symbols,list):
raise TypeError, "symbols must be a list"
# for codes see: http://www.gummy-stuff.org/Yahoo-data.htm
codes = {'symbol':'s','last':'l1','change_pct':'p2','PE':'r','time':'t1','short_ratio':'s7'}
request = str.join('',codes.values()) # code request string
header = codes.keys()

data = dict(zip(codes.keys(),[[] for i in range(len(codes))]))

urlStr = 'http://finance.yahoo.com/d/quotes.csv?s=%s&f=%s' % (str.join('+',symbols), request)

try:
lines = urllib2.urlopen(urlStr).readlines()
except Exception, e:
s = "Failed to download:\n{0}".format(e);
print s
return None

for line in lines:
fields = line.strip().split(',')
#print fields
for i,field in enumerate(fields):
if field[0] == '"':
data[header[i]].append( field.strip('"'))
else:
try:
data[header[i]].append(float(field))
except ValueError:
data[header[i]].append(np.nan)

idx = data.pop('symbol')

return DataFrame(data,index=idx)

def get_data_yahoo(name=None, start=None, end=None):
"""
Get historical data for the given name from yahoo.
Expand Down
114 changes: 114 additions & 0 deletions pandas/sandbox/qtpandas.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
'''
Easy integration of DataFrame into pyqt framework

@author: Jev Kuznetsov
'''
from PyQt4.QtCore import (QAbstractTableModel,Qt,QVariant,QModelIndex, SIGNAL)
from PyQt4.QtGui import (QApplication,QDialog,QVBoxLayout, QTableView, QWidget)

from pandas import DataFrame, Index



class DataFrameModel(QAbstractTableModel):
''' data model for a DataFrame class '''
def __init__(self):
super(DataFrameModel,self).__init__()
self.df = DataFrame()

def setDataFrame(self,dataFrame):
self.df = dataFrame

def signalUpdate(self):
''' tell viewers to update their data (this is full update, not efficient)'''
self.layoutChanged.emit()

#------------- table display functions -----------------
def headerData(self,section,orientation,role=Qt.DisplayRole):
if role != Qt.DisplayRole:
return QVariant()

if orientation == Qt.Horizontal:
try:
return self.df.columns.tolist()[section]
except (IndexError, ):
return QVariant()
elif orientation == Qt.Vertical:
try:
#return self.df.index.tolist()
return self.df.index.tolist()[section]
except (IndexError, ):
return QVariant()

def data(self, index, role=Qt.DisplayRole):
if role != Qt.DisplayRole:
return QVariant()

if not index.isValid():
return QVariant()

return QVariant(str(self.df.ix[index.row(),index.column()]))


def rowCount(self, index=QModelIndex()):
return self.df.shape[0]

def columnCount(self, index=QModelIndex()):
return self.df.shape[1]


class DataFrameWidget(QWidget):
''' a simple widget for using DataFrames in a gui '''
def __init__(self,dataFrame, parent=None):
super(DataFrameWidget,self).__init__(parent)

self.dataModel = DataFrameModel()
self.dataModel.setDataFrame(dataFrame)

self.dataTable = QTableView()
self.dataTable.setModel(self.dataModel)
self.dataModel.signalUpdate()

layout = QVBoxLayout()
layout.addWidget(self.dataTable)
self.setLayout(layout)



def resizeColumnsToContents(self):
self.dataTable.resizeColumnsToContents()

#-----------------stand alone test code

def testDf():
''' creates test dataframe '''
data = {'int':[1,2,3],'float':[1.5,2.5,3.5],'string':['a','b','c'],'nan':[np.nan,np.nan,np.nan]}
return DataFrame(data, index=Index(['AAA','BBB','CCC']))[['int','float','string','nan']]


class Form(QDialog):
def __init__(self,parent=None):
super(Form,self).__init__(parent)

df = testDf() # make up some data
widget = DataFrameWidget(df)
widget.resizeColumnsToContents()

layout = QVBoxLayout()
layout.addWidget(widget)
self.setLayout(layout)

if __name__=='__main__':
import sys
import numpy as np

app = QApplication(sys.argv)
form = Form()
form.show()
app.exec_()