我对python编程很陌生。我试图使用python xlwt模块将结果写入excel。错误是 TypeError:' float'对象不可迭代。我无法修复它。有谁可以帮助我这个。我感谢任何帮助。
from math import *
import pylab as z;
from matplotlib import style
import numpy as np;
from xlwt import *
import xlwt
SMALL_FONT =("Verdana", 8)
style.use('ggplot')
def PriceMovements(S0, down, up, totalsteps, upsteps):
S = S0*(pow(up, upsteps))*(pow(down, totalsteps-upsteps))
return S
def binomial(d, u, p):
g = np.random.binomial(1,p)
if g == 1:
return u
else:
return d
def write(self, r, c, label =""):
self.row(r).write(c, label)
#Use the following numbers to console the setting for binomial graph
nodes = 8 #Nodes
S = 100.0 #Initial spot price
u = 1.1346 #Up factor
d = 0.8814 #Down factor
p = 0.7844 # Probability
r = 1.08 #1+Interest rate
n = 3 #Steps
numberofpaths = 2**nodes
valuelist = [] #Emptylist
z.figure(0) #Generating the figure
temp = S #Temporary variable
for i in range(0, numberofpaths, 1):
valuelist =[]
S = temp;
for c in range(0, nodes + 1, 1):
valuelist.append(S)
S = S*binomial(d, u, p)
z.plot(range(0, nodes + 1, 1), valuelist)
for i in range(nodes):
z.text(i+.2,valuelist[i]-25,'{:4.1f}'.format(valuelist[i]))
wb = xlwt.Workbook()
ws = wb.add_sheet('Sheet1')
for r, row in enumerate(valuelist):
for c, col in enumerate(row):
ws.write(r, 2+c, lable = col)
wb.save('exampleResult.xls')
答案 0 :(得分:2)
IIUC您需要枚举列表valuelist
,因为row
的值为type
float
:
print valuelist
[100.0, 113.46000000000001, 100.00364400000001, 113.46413448240001, 128.73640698373106,
146.06432736374126, 165.72458582690084, 146.06964994783038, 165.73062483080835]
for r, row in enumerate(valuelist):
print r
print row
ws.write(r, 2+r, label = row)
0
100.0
1
113.46
2
100.003644
3
113.464134482
4
128.736406984
5
146.064327364
6
165.724585827
7
146.069649948
8
165.730624831
wb.save('exampleResult.xls')
通过评论编辑:
我认为您需要在每个循环中创建由list
填充的新lists
valuelist
。然后,您可以创建DataFrame
并将其写为to_excel
:
import pandas as pd
...
numberofpaths = 2**nodes
valuelist = [] #Emptylist
#add listofvaluelists
listofvaluelists = []
z.figure(0) #Generating the figure
temp = S #Temporary variable
for i in range(0, numberofpaths, 1):
valuelist =[]
S = temp;
for c in range(0, nodes + 1, 1):
valuelist.append(S)
S = S*binomial(d, u, p)
z.plot(range(0, nodes + 1, 1), valuelist)
#append listofvaluelists
listofvaluelists.append(valuelist)
for i in range(nodes):
z.text(i+.2,valuelist[i]-25,'{:4.1f}'.format(valuelist[i]))
#print listofvaluelists
#create new DataFrame
df = pd.DataFrame(listofvaluelists)
print df
#write DataFrame to excel
df.to_excel('exampleResult.xls', sheet_name='Sheet1')