Spaces:
Runtime error
Runtime error
Create calculator2.py
Browse files- utils/calculator2.py +44 -0
utils/calculator2.py
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import pandas as pd
|
| 2 |
+
|
| 3 |
+
def simulate_all_in_trading(signals_data):
|
| 4 |
+
"""
|
| 5 |
+
Simulates trading by going all-in on the first buy signal and selling all on the first sell signal,
|
| 6 |
+
then repeating the process with the new amount of cash including profit or loss.
|
| 7 |
+
|
| 8 |
+
Parameters:
|
| 9 |
+
- signals_data (pd.DataFrame): DataFrame with 'Close', 'Buy_Signal', and 'Sell_Signal'.
|
| 10 |
+
|
| 11 |
+
Returns:
|
| 12 |
+
- float: The final amount of cash after applying the trading strategy.
|
| 13 |
+
- int: The number of trades executed.
|
| 14 |
+
"""
|
| 15 |
+
cash = 1000 # Initial cash
|
| 16 |
+
holding = False
|
| 17 |
+
trades_executed = 0
|
| 18 |
+
|
| 19 |
+
for index, row in signals_data.iterrows():
|
| 20 |
+
if not holding and row['Buy_Signal']:
|
| 21 |
+
# Buy all you can with the available cash
|
| 22 |
+
shares = cash / row['Close']
|
| 23 |
+
holding = True
|
| 24 |
+
trades_executed += 1
|
| 25 |
+
|
| 26 |
+
elif holding and row['Sell_Signal']:
|
| 27 |
+
# Sell all shares
|
| 28 |
+
cash = shares * row['Close']
|
| 29 |
+
holding = False
|
| 30 |
+
trades_executed += 1
|
| 31 |
+
|
| 32 |
+
return cash, trades_executed
|
| 33 |
+
|
| 34 |
+
if __name__ == "__main__":
|
| 35 |
+
# Example DataFrame with close prices and buy/sell signals
|
| 36 |
+
signals_data = pd.DataFrame({
|
| 37 |
+
'Close': [100, 105, 103, 108, 107, 110, 108, 112], # Example close prices
|
| 38 |
+
'Buy_Signal': [False, True, False, False, True, False, False, False],
|
| 39 |
+
'Sell_Signal': [False, False, True, False, False, True, False, False]
|
| 40 |
+
})
|
| 41 |
+
|
| 42 |
+
final_cash, trades = simulate_all_in_trading(signals_data)
|
| 43 |
+
print(f"Final Cash: ${final_cash:.2f}")
|
| 44 |
+
print(f"Trades Executed: {trades}")
|