如何使代码读取Python中的特定列



对于我的第一个Python项目,我选择制作一个交易算法。为此,我在谷歌电子表格中有一些信息,并有一个特定的列,其中包含决定我应该购买还是出售的值,我已经将其下载为csv文件,现在我想让我的python代码读取该列,而不是"关闭"列。我已经尝试用我的列名中的术语来更改所有的"close"术语。我做不到,有人能帮我吗?

这是我在后台交易网站上使用的:

class H_strategy(backtrader.Strategy):
def log(self, txt, dt=None):
''' Logging function for this strategy'''
dt = dt or self.datas[0].datetime.date(0)
print('%s, %s' % (dt.isoformat(), txt))
def __init__(self):
# Keep a reference to the "close" line in the data[0] dataseries
self.dataclose = self.datas[0].close
self.order = None
def notify_order(self, order):
if order.status in [order.Submitted, order.Accepted]:
return
if order.status in [order.Completed]:
if order.isbuy():
self.log('BUY EXECUTED {}'.format(order.executed.price))
elif order.issell():
self.log('SELL EXECUTED {}'.format(order.executed.price))
self.bar_executed = len(self)
self.order = None
def next(self):
# Simply log the closing price of the series from the reference
self.log('Close, %.2f' % self.dataclose[0])
if self.order:
return
if not self.position:   
if self.dataclose[0] < self.dataclose[-1]:
# current close less than previous close
if self.dataclose[-1] < self.dataclose[-2]:
# previous close less than the previous close
# BUY, BUY, BUY!!! (with all possible default parameters)
self.log('BUY CREATE, %.2f' % self.dataclose[0])
self.order = self.buy()
else:
if len(self) >= (self.bar_executed +5):
self.log('SELL CREATED {}'.format(self.dataclose[0]))
self.order = self.sell()

如果我有你的问题,你实际上想读一个csv文件,更具体地说,只读csv文件的一列。您可以在python中使用csv模块。

import csv
f = open("your_file_name.csv") # note that the file should be in the same directory as your main python file
reader = csv.reader(f)
for col1, col2, col3 in reader: # Here col1, col2, col3 are the names given to the columns in your csv file.
Do_whatever_you_want_to_do

最新更新