Spaces:
Runtime error
Runtime error
Create calculator.py
Browse files- utils/calculator.py +46 -0
utils/calculator.py
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
def simulate_trading(signals_data, initial_capital=1000, investment_per_buy=100):
|
| 2 |
+
"""
|
| 3 |
+
Simulates trading based on buy and sell signals.
|
| 4 |
+
|
| 5 |
+
Parameters:
|
| 6 |
+
- signals_data (pd.DataFrame): DataFrame with 'Close', 'Buy_Signal', and 'Sell_Signal'.
|
| 7 |
+
- initial_capital (float): The initial capital at the start of the trading period.
|
| 8 |
+
- investment_per_buy (float): The fixed amount in dollars to invest at each buy signal.
|
| 9 |
+
|
| 10 |
+
Returns:
|
| 11 |
+
- float: The value of the stock currently held at the end of the period.
|
| 12 |
+
- float: The amount of cash remaining if any.
|
| 13 |
+
"""
|
| 14 |
+
cash = initial_capital
|
| 15 |
+
holdings = 0
|
| 16 |
+
|
| 17 |
+
for _, row in signals_data.iterrows():
|
| 18 |
+
# Buy
|
| 19 |
+
if row['Buy_Signal'] and cash >= investment_per_buy:
|
| 20 |
+
shares_bought = investment_per_buy / row['Close']
|
| 21 |
+
holdings += shares_bought
|
| 22 |
+
cash -= investment_per_buy
|
| 23 |
+
|
| 24 |
+
# Sell
|
| 25 |
+
if row['Sell_Signal'] and holdings > 0:
|
| 26 |
+
shares_sold = holdings * 0.25
|
| 27 |
+
holdings -= shares_sold
|
| 28 |
+
cash += shares_sold * row['Close']
|
| 29 |
+
|
| 30 |
+
# Calculate the value of the remaining stock holdings at the last known price
|
| 31 |
+
final_stock_value = holdings * signals_data.iloc[-1]['Close']
|
| 32 |
+
|
| 33 |
+
return final_stock_value, cash
|
| 34 |
+
|
| 35 |
+
# Example usage
|
| 36 |
+
if __name__ == "__main__":
|
| 37 |
+
# Assuming signals_data DataFrame exists with 'Close', 'Buy_Signal', 'Sell_Signal'
|
| 38 |
+
signals_data = pd.DataFrame({
|
| 39 |
+
'Close': [100, 105, 103, 108, 107], # Example close prices
|
| 40 |
+
'Buy_Signal': [True, False, True, False, False],
|
| 41 |
+
'Sell_Signal': [False, True, False, True, False]
|
| 42 |
+
}, index=pd.date_range(start='2020-01-01', periods=5, freq='D'))
|
| 43 |
+
|
| 44 |
+
final_stock_value, remaining_cash = simulate_trading(signals_data)
|
| 45 |
+
print(f"Final Value of Stock Holdings: ${final_stock_value:.2f}")
|
| 46 |
+
print(f"Remaining Cash: ${remaining_cash:.2f}")
|