Created
May 6, 2023 05:39
-
-
Save PandaWhoCodes/c04de9a9856ce4b9b04d449b67632e2d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
To sell only the stocks that are not there in this week's new strategy and keep the stocks that still remain, you can modify the code as follows: | |
```python | |
import backtrader as bt | |
import pandas as pd | |
# Define the strategy | |
class MyStrategy(bt.Strategy): | |
def __init__(self): | |
self.market_cap = self.datas[0].market_cap | |
self.pb_ratio = self.datas[0].pb_ratio | |
self.debt_to_equity = self.datas[0].debt_to_equity | |
self.eps_latest_quarter = self.datas[0].eps_latest_quarter | |
self.eps_last_year = self.datas[0].eps_last_year | |
self.pat_last_year = self.datas[0].pat_last_year | |
self.volume_1week_avg = self.datas[0].volume_1week_avg | |
self.weekly_sma = bt.indicators.SimpleMovingAverage(self.data.close, period=5) | |
self.weekly_rsi = bt.indicators.RelativeStrengthIndex(self.data.close, period=14) | |
self.weekly_buy_signal = False | |
self.weekly_stocks = [] | |
def next(self): | |
if self.datas[0].datetime.date(0).weekday() == 0: | |
# Every Monday | |
self.weekly_buy_signal = False | |
self.weekly_stocks = [] | |
if self.market_cap[0] > 300 and self.pb_ratio[0] < self.data.close[0] and \ | |
self.debt_to_equity[0] < 0.25 and self.eps_latest_quarter[0] > self.eps_latest_quarter[-1] and \ | |
self.eps_last_year[0] > self.eps_last_year[-1] and self.pat_last_year[0] > 0 and \ | |
self.volume_1week_avg[0] > 700000 and self.weekly_rsi[0] > 50: | |
self.weekly_buy_signal = True | |
self.weekly_stocks = [data._name for data in self.datas if self.market_cap[data]._value[0] > 300 and | |
self.pb_ratio[data]._value[0] < self.data.close[data]._value[0] and | |
self.debt_to_equity[data]._value[0] < 0.25 and | |
self.eps_latest_quarter[data]._value[0] > self.eps_latest_quarter[data]._value[-1] and | |
self.eps_last_year[data]._value[0] > self.eps_last_year[data]._value[-1] and | |
self.pat_last_year[data]._value[0] > 0 and | |
self.volume_1week_avg[data]._value[0] > 700000] | |
for data in self.datas: | |
if data._name not in self.weekly_stocks and self.getposition(data).size != 0: | |
self.sell(data=data, size=self.getposition(data).size) | |
if self.weekly_buy_signal: | |
cash = self.broker.getcash() | |
if cash > 0: | |
target_value = cash / 15 | |
size = int(target_value / self.data.close[0]) | |
for data in self.datas: | |
if data._name in self.weekly_stocks and self.getposition(data).size == 0: | |
self.buy(data=data, size=size) | |
# Load the data | |
data = bt.feeds.GenericCSVData( | |
dataname='data.csv', | |
fromdate=pd.Timestamp('2010-01-01'), | |
todate=pd.Timestamp('2021-12-31'), | |
nullvalue=0.0, | |
dtformat='%Y-%m-%d', | |
datetime=0, | |
open=1, | |
high=2, | |
low=3, | |
close=4, | |
volume=5, | |
openinterest=-1, | |
market_cap=6, | |
pb_ratio=7, | |
debt_to_equity=8, | |
eps_latest_quarter=9, | |
eps_last_year=10, | |
pat_last_year=11, | |
volume_1week_avg=12 | |
) | |
# Create the cerebro instance | |
cerebro = bt.Cerebro() | |
# Add the data feed | |
cerebro.adddata(data) | |
# Add the strategy | |
cerebro.addstrategy(MyStrategy) | |
# Set the initial capital | |
cerebro.broker.setcash | |
# Set the commission | |
cerebro.broker.setcommission(commission=0.001) | |
# Run the backtest | |
cerebro.run() | |
# Print the final portfolio value | |
print('Final Portfolio Value: %.2f' % cerebro.broker.getvalue()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment