[英]How do I make my code read a specific column in Python?
对于我的第一个 Python 项目,我选择制作交易算法。 为此,我在 Google 电子表格中有一些信息,并且有一列包含确定我应该买入还是卖出的值,我已将其下载为 csv 文件,现在我想让我的 python 代码读取该列而不是“关闭”列。 我试图用我的列名中的术语更改所有“关闭”术语。 我不能让它工作,有人可以帮我吗?
这是我在 backtrader 网站上使用的:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.