[英]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.